fix(wiki): mask image URLs before LLM to prevent UUID/path corruption
Wiki summary/entity/concept/page-modify prompts instructed the LLM to reproduce  verbatim, so high-entropy image URLs passed through generation and got corrupted (dropped UUID segments, duplicated or mangled path prefixes, even CJK chars inserted into the bucket name), producing object keys that don't exist -> 404. Mask all image URLs to opaque placeholders at the generateWithTemplate chokepoint and deterministically rehydrate after generation; drop corrupted/hallucinated placeholders so broken links never reach storage.
This commit is contained in:
@@ -1693,8 +1693,10 @@ func (s *wikiIngestService) generateWithTemplate(ctx context.Context, chatModel
|
||||
return "", fmt.Errorf("parse template: %w", err)
|
||||
}
|
||||
|
||||
maskedData, urlMap := maskTemplateDataImageURLs(data)
|
||||
|
||||
var buf strings.Builder
|
||||
if err := tmpl.Execute(&buf, data); err != nil {
|
||||
if err := tmpl.Execute(&buf, maskedData); err != nil {
|
||||
return "", fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
@@ -1710,7 +1712,7 @@ func (s *wikiIngestService) generateWithTemplate(ctx context.Context, chatModel
|
||||
Thinking: &thinking,
|
||||
})
|
||||
if err == nil {
|
||||
return response.Content, nil
|
||||
return unmaskImageURLs(response.Content, urlMap), nil
|
||||
}
|
||||
lastErr = err
|
||||
|
||||
@@ -1999,8 +2001,160 @@ var (
|
||||
// <image_caption>...</image_caption> blocks, and stripping the content
|
||||
// would silently destroy the very text we want to keep.
|
||||
imageWrapperTagRE = regexp.MustCompile(`(?i)</?image[a-z_]*\b[^>]*/?>`)
|
||||
|
||||
// Markdown image references with the URL captured separately so LLM-bound
|
||||
// image URLs can be frozen while captions remain editable.
|
||||
mdImageURLRE = regexp.MustCompile(`!\[[^\]]*\]\(([^)]*)\)`)
|
||||
|
||||
// Enriched image blocks store the original object URL as an attribute,
|
||||
// e.g. <image url="...">. Capture both double- and single-quoted forms.
|
||||
imageURLAttrRE = regexp.MustCompile(`(?i)<image\b[^>]*\surl\s*=\s*(?:"([^"]*)"|'([^']*)')`)
|
||||
|
||||
imagePlaceholderTokenRE = regexp.MustCompile(`wkimg:[A-Za-z0-9_-]+`)
|
||||
)
|
||||
|
||||
func maskTemplateDataImageURLs(data map[string]string) (map[string]string, map[string]string) {
|
||||
if len(data) == 0 {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
masked := make(map[string]string, len(data))
|
||||
urlToToken := make(map[string]string)
|
||||
tokenToURL := make(map[string]string)
|
||||
|
||||
keys := make([]string, 0, len(data))
|
||||
for key := range data {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
for _, key := range keys {
|
||||
masked[key] = maskImageURLsWithState(data[key], urlToToken, tokenToURL)
|
||||
}
|
||||
|
||||
return masked, tokenToURL
|
||||
}
|
||||
|
||||
// maskImageURLs replaces image URLs with low-entropy placeholders. It only
|
||||
// freezes URLs; alt/caption text remains in place for the LLM to edit.
|
||||
func maskImageURLs(s string) (string, map[string]string) {
|
||||
urlToToken := make(map[string]string)
|
||||
tokenToURL := make(map[string]string)
|
||||
return maskImageURLsWithState(s, urlToToken, tokenToURL), tokenToURL
|
||||
}
|
||||
|
||||
func maskImageURLsWithState(s string, urlToToken, tokenToURL map[string]string) string {
|
||||
urls := collectMaskableImageURLs(s)
|
||||
if len(urls) == 0 {
|
||||
return s
|
||||
}
|
||||
|
||||
for _, url := range urls {
|
||||
if _, ok := urlToToken[url]; ok {
|
||||
continue
|
||||
}
|
||||
token := fmt.Sprintf("wkimg:%04d", len(tokenToURL)+1)
|
||||
urlToToken[url] = token
|
||||
tokenToURL[token] = url
|
||||
}
|
||||
|
||||
replaceURLs := append([]string(nil), urls...)
|
||||
sort.SliceStable(replaceURLs, func(i, j int) bool {
|
||||
return len(replaceURLs[i]) > len(replaceURLs[j])
|
||||
})
|
||||
|
||||
masked := s
|
||||
for _, url := range replaceURLs {
|
||||
masked = strings.ReplaceAll(masked, url, urlToToken[url])
|
||||
}
|
||||
return masked
|
||||
}
|
||||
|
||||
func collectMaskableImageURLs(s string) []string {
|
||||
seen := make(map[string]struct{})
|
||||
var urls []string
|
||||
|
||||
addURL := func(url string) {
|
||||
url = strings.TrimSpace(url)
|
||||
if url == "" {
|
||||
return
|
||||
}
|
||||
if _, ok := seen[url]; ok {
|
||||
return
|
||||
}
|
||||
seen[url] = struct{}{}
|
||||
urls = append(urls, url)
|
||||
}
|
||||
|
||||
for _, match := range mdImageURLRE.FindAllStringSubmatch(s, -1) {
|
||||
addURL(match[1])
|
||||
}
|
||||
for _, match := range imageURLAttrRE.FindAllStringSubmatch(s, -1) {
|
||||
if match[1] != "" {
|
||||
addURL(match[1])
|
||||
continue
|
||||
}
|
||||
addURL(match[2])
|
||||
}
|
||||
|
||||
return urls
|
||||
}
|
||||
|
||||
// unmaskImageURLs restores known placeholders and drops any corrupted or
|
||||
// invented image placeholders so broken image links never reach storage.
|
||||
func unmaskImageURLs(out string, urlMap map[string]string) string {
|
||||
out = mdImageURLRE.ReplaceAllStringFunc(out, func(match string) string {
|
||||
parts := mdImageURLRE.FindStringSubmatch(match)
|
||||
if len(parts) != 2 {
|
||||
return match
|
||||
}
|
||||
url := strings.TrimSpace(parts[1])
|
||||
if realURL, ok := urlMap[url]; ok {
|
||||
idx := strings.LastIndex(match, "(")
|
||||
if idx < 0 {
|
||||
return match
|
||||
}
|
||||
return match[:idx+1] + realURL + ")"
|
||||
}
|
||||
if strings.HasPrefix(url, "wkimg:") {
|
||||
return ""
|
||||
}
|
||||
return match
|
||||
})
|
||||
|
||||
return replaceImagePlaceholderTokensOutsideMarkdown(out, urlMap)
|
||||
}
|
||||
|
||||
func replaceImagePlaceholderTokensOutsideMarkdown(s string, urlMap map[string]string) string {
|
||||
matches := mdImageURLRE.FindAllStringIndex(s, -1)
|
||||
if len(matches) == 0 {
|
||||
return replaceImagePlaceholderTokens(s, urlMap)
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
last := 0
|
||||
for _, match := range matches {
|
||||
if match[0] > last {
|
||||
b.WriteString(replaceImagePlaceholderTokens(s[last:match[0]], urlMap))
|
||||
}
|
||||
b.WriteString(s[match[0]:match[1]])
|
||||
last = match[1]
|
||||
}
|
||||
if last < len(s) {
|
||||
b.WriteString(replaceImagePlaceholderTokens(s[last:], urlMap))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func replaceImagePlaceholderTokens(s string, urlMap map[string]string) string {
|
||||
return imagePlaceholderTokenRE.ReplaceAllStringFunc(s, func(token string) string {
|
||||
if realURL, ok := urlMap[token]; ok {
|
||||
return realURL
|
||||
}
|
||||
return ""
|
||||
})
|
||||
}
|
||||
|
||||
// stripImageMarkup removes image-only placeholders (Markdown image refs,
|
||||
// <img> tags, <image_original> redundancy blocks) and unwraps the
|
||||
// <image>/<image_caption>/<image_ocr> XML wrappers produced by the search
|
||||
|
||||
Reference in New Issue
Block a user