fix(knowledge): rewrite parent text chunk image URLs via global pass
For document knowledge, extracted images live in independent image_ocr/ image_caption child chunks that carry image_info, while the parent text chunk embeds the  reference with an empty image_info. Rewriting content per-chunk therefore missed the parent text chunk, leaving it pointing at soon-to-be-deleted source storage. Move content URL rewriting to a final pass over all cloned chunks, run once urlCache holds the complete old->new mapping. FAQ chunks are self-contained, so they are rewritten inline from the same cache.
This commit is contained in:
@@ -43,55 +43,43 @@ func copyOwnedObject(
|
||||
// object into a NEW object owned by (tenantID, knowledgeID), and returns the
|
||||
// re-serialized image_info plus the list of newly-created object URLs (for
|
||||
// rollback on failure). urlCache dedups identical source objects across chunks
|
||||
// so the same source image is copied at most once per clone.
|
||||
// so the same source image is copied at most once per clone AND accumulates the
|
||||
// full old->new URL mapping so callers can rewrite in-content Markdown image
|
||||
// references (see rewriteContentImageURLs).
|
||||
//
|
||||
// srcContent is the chunk's Markdown content, which embeds the same image URLs
|
||||
// as  references. Because the source objects are deleted after some
|
||||
// clone/move flows, those in-content references must also be rewritten to the
|
||||
// newly-copied objects; otherwise the content would point at soon-to-be-deleted
|
||||
// storage while image_info points at the new copies. The rewritten content is
|
||||
// returned alongside the rewritten image_info so both stay consistent.
|
||||
//
|
||||
// An empty srcImageInfo yields (srcContent, "", nil, nil). A JSON parse failure
|
||||
// returns an error (the clone fails) rather than silently inheriting the
|
||||
// shared-reference bug. When an image's OriginalURL points at the same object as
|
||||
// its URL (the common case for extracted images), OriginalURL is rewritten to
|
||||
// the new path too; an OriginalURL from a different/external source is preserved.
|
||||
// An empty srcImageInfo yields ("", nil, nil). A JSON parse failure returns an
|
||||
// error (the clone fails) rather than silently inheriting the shared-reference
|
||||
// bug. When an image's OriginalURL points at the same object as its URL (the
|
||||
// common case for extracted images), OriginalURL is rewritten to the new path
|
||||
// too; an OriginalURL from a different/external source is preserved.
|
||||
func cloneChunkImageInfo(
|
||||
ctx context.Context,
|
||||
dstSvc interfaces.FileService,
|
||||
srcContent string,
|
||||
srcImageInfo string,
|
||||
tenantID uint64,
|
||||
knowledgeID string,
|
||||
urlCache map[string]string,
|
||||
) (newContent string, newImageInfo string, copiedURLs []string, err error) {
|
||||
) (newImageInfo string, copiedURLs []string, err error) {
|
||||
if srcImageInfo == "" {
|
||||
return srcContent, "", nil, nil
|
||||
return "", nil, nil
|
||||
}
|
||||
|
||||
var images []*types.ImageInfo
|
||||
if err := json.Unmarshal([]byte(srcImageInfo), &images); err != nil {
|
||||
return srcContent, "", nil, fmt.Errorf("failed to parse chunk image_info JSON: %w", err)
|
||||
return "", nil, fmt.Errorf("failed to parse chunk image_info JSON: %w", err)
|
||||
}
|
||||
|
||||
// urlReplacements maps every old (source) URL to its new (copied) URL so
|
||||
// the in-content Markdown image references can be rewritten to match.
|
||||
urlReplacements := make(map[string]string)
|
||||
|
||||
for _, img := range images {
|
||||
if img == nil || img.URL == "" {
|
||||
continue
|
||||
}
|
||||
oldURL := img.URL
|
||||
oldOriginalURL := img.OriginalURL
|
||||
originalMatchedURL := img.OriginalURL == img.URL
|
||||
|
||||
newURL, cached := urlCache[img.URL]
|
||||
if !cached {
|
||||
newURL, err = copyOwnedObject(ctx, dstSvc, dstSvc, img.URL, tenantID, knowledgeID)
|
||||
if err != nil {
|
||||
return srcContent, "", copiedURLs, fmt.Errorf("failed to copy chunk image %q: %w", img.URL, err)
|
||||
return "", copiedURLs, fmt.Errorf("failed to copy chunk image %q: %w", img.URL, err)
|
||||
}
|
||||
urlCache[img.URL] = newURL
|
||||
copiedURLs = append(copiedURLs, newURL)
|
||||
@@ -101,30 +89,33 @@ func cloneChunkImageInfo(
|
||||
img.OriginalURL = newURL
|
||||
}
|
||||
img.URL = newURL
|
||||
|
||||
urlReplacements[oldURL] = newURL
|
||||
if oldOriginalURL != "" {
|
||||
urlReplacements[oldOriginalURL] = img.OriginalURL
|
||||
}
|
||||
}
|
||||
|
||||
out, err := json.Marshal(images)
|
||||
if err != nil {
|
||||
return srcContent, "", copiedURLs, fmt.Errorf("failed to re-serialize chunk image_info: %w", err)
|
||||
return "", copiedURLs, fmt.Errorf("failed to re-serialize chunk image_info: %w", err)
|
||||
}
|
||||
return rewriteContentImageURLs(srcContent, urlReplacements), string(out), copiedURLs, nil
|
||||
return string(out), copiedURLs, nil
|
||||
}
|
||||
|
||||
// rewriteContentImageURLs replaces every occurrence of an old image URL with its
|
||||
// new URL in content. Replacements whose old and new URL are identical (e.g. an
|
||||
// external OriginalURL that was preserved) are skipped. Longer URLs are applied
|
||||
// first so a URL that is a prefix of another does not partially rewrite it.
|
||||
func rewriteContentImageURLs(content string, replacements map[string]string) string {
|
||||
if content == "" || len(replacements) == 0 {
|
||||
// new (copied) URL in content, using the old->new mapping accumulated in
|
||||
// urlCache. It is the second half of the image deep-copy: chunk Content embeds
|
||||
// image URLs as Markdown  references, but for document knowledge the
|
||||
// image objects live in independent image_ocr/image_caption child chunks — the
|
||||
// parent text chunk carries the  reference with an empty image_info. So
|
||||
// the old->new mapping is only known after every chunk's image_info has been
|
||||
// processed; this rewrite must therefore run as a final pass once urlCache is
|
||||
// complete, over ALL cloned chunks, not per-chunk.
|
||||
//
|
||||
// Replacements are applied longest-old-URL first so a URL that is a prefix of
|
||||
// another is not partially rewritten. Entries whose old==new are skipped.
|
||||
func rewriteContentImageURLs(content string, urlCache map[string]string) string {
|
||||
if content == "" || len(urlCache) == 0 {
|
||||
return content
|
||||
}
|
||||
oldURLs := make([]string, 0, len(replacements))
|
||||
for oldURL, newURL := range replacements {
|
||||
oldURLs := make([]string, 0, len(urlCache))
|
||||
for oldURL, newURL := range urlCache {
|
||||
if oldURL == "" || oldURL == newURL {
|
||||
continue
|
||||
}
|
||||
@@ -132,7 +123,7 @@ func rewriteContentImageURLs(content string, replacements map[string]string) str
|
||||
}
|
||||
slices.SortFunc(oldURLs, func(a, b string) int { return len(b) - len(a) })
|
||||
for _, oldURL := range oldURLs {
|
||||
content = strings.ReplaceAll(content, oldURL, replacements[oldURL])
|
||||
content = strings.ReplaceAll(content, oldURL, urlCache[oldURL])
|
||||
}
|
||||
return content
|
||||
}
|
||||
@@ -298,9 +289,13 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
|
||||
}
|
||||
|
||||
// Deep-copy extracted images into objects owned by the destination
|
||||
// knowledge so deleting the source never breaks this clone.
|
||||
newContent, newImageInfo, copied, copyErr := cloneChunkImageInfo(
|
||||
ctx, dstSvc, sourceChunk.Content, sourceChunk.ImageInfo, dst.TenantID, dst.ID, urlCache)
|
||||
// knowledge so deleting the source never breaks this clone. Content
|
||||
// URL rewriting happens in a final pass below, once urlCache holds
|
||||
// the complete old->new mapping (image objects live in independent
|
||||
// child chunks, so a parent text chunk's  reference cannot be
|
||||
// rewritten until its child image chunk has been processed).
|
||||
newImageInfo, copied, copyErr := cloneChunkImageInfo(
|
||||
ctx, dstSvc, sourceChunk.ImageInfo, dst.TenantID, dst.ID, urlCache)
|
||||
if copyErr != nil {
|
||||
err = fmt.Errorf("clone chunk image copy failed: %w", copyErr)
|
||||
return err
|
||||
@@ -313,7 +308,7 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
|
||||
KnowledgeID: dst.ID,
|
||||
KnowledgeBaseID: dst.KnowledgeBaseID,
|
||||
TagID: targetTagID,
|
||||
Content: newContent,
|
||||
Content: sourceChunk.Content,
|
||||
ChunkIndex: sourceChunk.ChunkIndex,
|
||||
IsEnabled: sourceChunk.IsEnabled,
|
||||
Flags: sourceChunk.Flags,
|
||||
@@ -335,6 +330,11 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
|
||||
}
|
||||
}
|
||||
for _, targetChunk := range targetChunks {
|
||||
// Rewrite in-content Markdown image URLs now that urlCache holds the
|
||||
// complete old->new mapping across all chunks. This fixes parent text
|
||||
// chunks whose  reference points at a source object copied while
|
||||
// processing an independent image_ocr/image_caption child chunk.
|
||||
targetChunk.Content = rewriteContentImageURLs(targetChunk.Content, urlCache)
|
||||
if val, ok := srcTodst[targetChunk.PreChunkID]; ok {
|
||||
targetChunk.PreChunkID = val
|
||||
} else {
|
||||
@@ -717,9 +717,12 @@ func (s *knowledgeService) cloneFAQKnowledgeBase(
|
||||
}
|
||||
|
||||
// Deep-copy extracted images into objects owned by the destination
|
||||
// FAQ knowledge so deleting the source never breaks this clone.
|
||||
newContent, newImageInfo, copied, copyErr := cloneChunkImageInfo(
|
||||
ctx, dstSvc, srcChunk.Content, srcChunk.ImageInfo, dstKB.TenantID, dstKnowledge.ID, imageURLCache)
|
||||
// FAQ knowledge so deleting the source never breaks this clone. A FAQ
|
||||
// chunk is self-contained (its own Content + image_info), so its
|
||||
//  references can be rewritten immediately using the mapping
|
||||
// just accumulated in imageURLCache.
|
||||
newImageInfo, copied, copyErr := cloneChunkImageInfo(
|
||||
ctx, dstSvc, srcChunk.ImageInfo, dstKB.TenantID, dstKnowledge.ID, imageURLCache)
|
||||
if copyErr != nil {
|
||||
logger.Errorf(ctx, "Failed to copy FAQ chunk images: %v", copyErr)
|
||||
handleError(progress, copyErr, "Failed to copy FAQ entry images")
|
||||
@@ -734,7 +737,7 @@ func (s *knowledgeService) cloneFAQKnowledgeBase(
|
||||
KnowledgeID: dstKnowledge.ID,
|
||||
KnowledgeBaseID: dstKB.ID,
|
||||
TagID: targetTagID,
|
||||
Content: newContent,
|
||||
Content: rewriteContentImageURLs(srcChunk.Content, imageURLCache),
|
||||
ChunkIndex: srcChunk.ChunkIndex,
|
||||
IsEnabled: srcChunk.IsEnabled,
|
||||
Flags: srcChunk.Flags,
|
||||
|
||||
Reference in New Issue
Block a user