diff --git a/internal/application/repository/resource.go b/internal/application/repository/resource.go index b3d724b7..da3ea7b5 100644 --- a/internal/application/repository/resource.go +++ b/internal/application/repository/resource.go @@ -88,6 +88,22 @@ func (r *resourceRepository) CountBindings(ctx context.Context, resourceID strin return count, err } +func (r *resourceRepository) ListHandlesByOwner( + ctx context.Context, ownerType string, ownerIDs, relations []string, +) ([]string, error) { + if ownerType == "" || len(ownerIDs) == 0 || len(relations) == 0 { + return nil, nil + } + var handles []string + err := r.db.WithContext(ctx). + Table("resource_bindings AS b"). + Joins("JOIN resources AS r ON r.id = b.resource_id AND r.state = ?", types.ResourceStateActive). + Where("b.owner_type = ? AND b.owner_id IN ? AND b.relation IN ?", ownerType, ownerIDs, relations). + Distinct("r.handle"). + Pluck("r.handle", &handles).Error + return handles, err +} + func (r *resourceRepository) CreateGrant(ctx context.Context, grant *types.ResourceAccessGrant) error { return r.db.WithContext(ctx).Create(grant).Error } diff --git a/internal/application/service/artifact_collector_test.go b/internal/application/service/artifact_collector_test.go index bbbbc9a6..4761e95c 100644 --- a/internal/application/service/artifact_collector_test.go +++ b/internal/application/service/artifact_collector_test.go @@ -164,6 +164,8 @@ type fakeCatalog struct { releaseRemaining map[string]int64 releaseErr error releases []string + ownerRefs map[string][]string + listErr error } func (c *fakeCatalog) Register(context.Context, uint64, string, interfaces.ResourceRegistration) (string, error) { @@ -195,6 +197,19 @@ func (c *fakeCatalog) Release(_ context.Context, ref, ownerType, ownerID string) return -1, nil } +func (c *fakeCatalog) ListReferencesByOwner(_ context.Context, _ string, ownerIDs ...string) ([]string, error) { + if c.listErr != nil { + return nil, c.listErr + } + var out []string + for _, id := range ownerIDs { + out = append(out, c.ownerRefs[id]...) + } + return out, nil +} + +var _ interfaces.ResourceCatalog = (*fakeCatalog)(nil) + func (c *fakeCatalog) CreateAccessGrant(context.Context, string, time.Duration) (string, error) { return "", nil } diff --git a/internal/application/service/file/resource_catalog_test.go b/internal/application/service/file/resource_catalog_test.go index e9c0a9d8..bab7390d 100644 --- a/internal/application/service/file/resource_catalog_test.go +++ b/internal/application/service/file/resource_catalog_test.go @@ -51,6 +51,11 @@ func (c *catalogStub) MarkDeleted(context.Context, string) error func (c *catalogStub) Release(context.Context, string, string, string) (int64, error) { return 0, nil } + +func (c *catalogStub) ListReferencesByOwner(context.Context, string, ...string) ([]string, error) { + return nil, nil +} + func (c *catalogStub) CreateAccessGrant(context.Context, string, time.Duration) (string, error) { return "GrantTokenAbCdEfGhIjKl", nil } diff --git a/internal/application/service/knowledge_clone_image_test.go b/internal/application/service/knowledge_clone_image_test.go index a894a530..83cb2d21 100644 --- a/internal/application/service/knowledge_clone_image_test.go +++ b/internal/application/service/knowledge_clone_image_test.go @@ -72,7 +72,7 @@ func mustImageInfoJSON(t *testing.T, imgs []types.ImageInfo) string { func TestCloneChunkImageInfo_Empty(t *testing.T) { svc := &countingFileService{} - out, copied, err := cloneChunkImageInfo(context.Background(), svc, "", 1, "kb-1", map[string]string{}) + out, copied, err := cloneChunkImageInfo(context.Background(), svc, "", 1, "kb-1", map[string]string{}, nil) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -89,7 +89,7 @@ func TestCloneChunkImageInfo_RewritesURLAndMatchedOriginal(t *testing.T) { src := mustImageInfoJSON(t, []types.ImageInfo{ {URL: "local://1/k0/a.png", OriginalURL: "local://1/k0/a.png", Caption: "cap"}, }) - out, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 7, "k-dst", map[string]string{}) + out, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 7, "k-dst", map[string]string{}, nil) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -125,7 +125,9 @@ func TestRewriteContentImageURLs_ParentTextChunk(t *testing.T) { {URL: "local://1/k0/a.png", OriginalURL: "local://1/k0/a.png"}, }) urlCache := map[string]string{} - if _, _, err := cloneChunkImageInfo(context.Background(), svc, childImageInfo, 7, "k-dst", urlCache); err != nil { + _, _, err := cloneChunkImageInfo( + context.Background(), svc, childImageInfo, 7, "k-dst", urlCache, nil) + if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -156,7 +158,7 @@ func TestCloneChunkImageInfo_PreservesUnmatchedOriginalURL(t *testing.T) { src := mustImageInfoJSON(t, []types.ImageInfo{ {URL: "local://1/k0/a.png", OriginalURL: "https://external.example.com/a.png"}, }) - out, _, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", map[string]string{}) + out, _, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", map[string]string{}, nil) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -176,7 +178,7 @@ func TestCloneChunkImageInfo_DedupsIdenticalURLs(t *testing.T) { {URL: "local://1/k0/same.png"}, {URL: "local://1/k0/other.png"}, }) - _, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", map[string]string{}) + _, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", map[string]string{}, nil) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -192,10 +194,10 @@ func TestCloneChunkImageInfo_DedupsAcrossCallsViaSharedCache(t *testing.T) { svc := &countingFileService{} cache := map[string]string{} src := mustImageInfoJSON(t, []types.ImageInfo{{URL: "local://1/k0/shared.png"}}) - if _, _, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", cache); err != nil { + if _, _, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", cache, nil); err != nil { t.Fatalf("first call error: %v", err) } - if _, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", cache); err != nil { + if _, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", cache, nil); err != nil { t.Fatalf("second call error: %v", err) } else if len(copied) != 0 { t.Fatalf("second call should reuse cache (0 new copies), got %v", copied) @@ -207,7 +209,7 @@ func TestCloneChunkImageInfo_DedupsAcrossCallsViaSharedCache(t *testing.T) { func TestCloneChunkImageInfo_ParseFailureAbortsClone(t *testing.T) { svc := &countingFileService{} - _, _, err := cloneChunkImageInfo(context.Background(), svc, "{not valid json", 1, "k-dst", map[string]string{}) + _, _, err := cloneChunkImageInfo(context.Background(), svc, "{not valid json", 1, "k-dst", map[string]string{}, nil) if err == nil { t.Fatal("expected error on invalid image_info JSON, got nil") } @@ -222,7 +224,7 @@ func TestCloneChunkImageInfo_CopyFailureReturnsPartialForCleanup(t *testing.T) { {URL: "local://1/k0/good.png"}, {URL: "local://1/k0/bad.png"}, }) - _, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", map[string]string{}) + _, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", map[string]string{}, nil) if err == nil { t.Fatal("expected error when an image copy fails") } @@ -235,7 +237,7 @@ func TestCloneChunkImageInfo_CopyFailureReturnsPartialForCleanup(t *testing.T) { func TestCloneChunkImageInfo_SkipsEmptyURL(t *testing.T) { svc := &countingFileService{} src := mustImageInfoJSON(t, []types.ImageInfo{{URL: "", Caption: "no-image"}}) - out, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", map[string]string{}) + out, copied, err := cloneChunkImageInfo(context.Background(), svc, src, 1, "k-dst", map[string]string{}, nil) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -250,3 +252,86 @@ func TestCloneChunkImageInfo_SkipsEmptyURL(t *testing.T) { t.Errorf("empty URL should stay empty, got %q", got[0].URL) } } + +type handleCopyFileService struct { + countingFileService + saveRef string + deleted []string +} + +func (f *handleCopyFileService) SaveBytes(_ context.Context, _ []byte, _ uint64, _ string, _ bool) (string, error) { + f.copyCalls++ + return f.saveRef, nil +} + +func (f *handleCopyFileService) DeleteFile(_ context.Context, filePath string) error { + f.deleted = append(f.deleted, filePath) + return nil +} + +func TestCopyOwnedObjectBindsCatalogHandles(t *testing.T) { + ref := contentRef("z") + files := &handleCopyFileService{saveRef: ref} + catalog := &fakeCatalog{} + + got, err := copyOwnedObject( + context.Background(), files, files, "local://7/src.png", 7, "kn-dst", + catalog, types.ResourceRelationExtractedImage, + ) + if err != nil { + t.Fatalf("copyOwnedObject: %v", err) + } + if got != ref { + t.Fatalf("path = %q, want %q", got, ref) + } + if len(catalog.binds) != 1 { + t.Fatalf("binds = %v, want one extracted_image claim", catalog.binds) + } + gotBind := catalog.binds[0] + if gotBind.ref != ref || gotBind.ownerType != types.ResourceOwnerKnowledge || + gotBind.ownerID != "kn-dst" || gotBind.relation != types.ResourceRelationExtractedImage { + t.Fatalf("bind = %+v", gotBind) + } +} + +func TestCopyOwnedObjectSkipsLegacyProviderPaths(t *testing.T) { + files := &countingFileService{} + catalog := &fakeCatalog{} + got, err := copyOwnedObject( + context.Background(), files, files, "local://7/src.png", 7, "kn-dst", + catalog, types.ResourceRelationExtractedImage, + ) + if err != nil { + t.Fatalf("copyOwnedObject: %v", err) + } + if !strings.HasPrefix(got, "local://") { + t.Fatalf("path = %q, want a legacy provider URL", got) + } + if len(catalog.binds) != 0 { + t.Fatalf("binds = %v, want none for provider:// paths", catalog.binds) + } +} + +// A catalog hiccup must not fail the clone. Every other claim path logs and +// continues; by the time the claim runs the copy is already written, so +// aborting here would discard a correct copy and strand the object it points +// at. The object stays reachable from its own workspace either way. +func TestCopyOwnedObjectKeepsCopyWhenBindFails(t *testing.T) { + ref := contentRef("y") + files := &handleCopyFileService{saveRef: ref} + catalog := &fakeCatalog{bindErr: fmt.Errorf("db down")} + + got, err := copyOwnedObject( + context.Background(), files, files, "local://7/src.png", 7, "kn-dst", + catalog, types.ResourceRelationSourceFile, + ) + if err != nil { + t.Fatalf("copyOwnedObject must be best-effort, got %v", err) + } + if got != ref { + t.Fatalf("path = %q, want the copied object %q", got, ref) + } + if len(files.deleted) != 0 { + t.Fatalf("deleted %v, want the copy kept", files.deleted) + } +} diff --git a/internal/application/service/knowledge_clone_move.go b/internal/application/service/knowledge_clone_move.go index 518e54f2..b8025158 100644 --- a/internal/application/service/knowledge_clone_move.go +++ b/internal/application/service/knowledge_clone_move.go @@ -42,8 +42,9 @@ func copyOwnedObject( srcPath string, tenantID uint64, knowledgeID string, + catalog interfaces.ResourceCatalog, + relation string, ) (string, error) { - _ = knowledgeID // exports objects are tenant-scoped, not knowledge-scoped rc, err := srcSvc.GetFile(ctx, srcPath) if err != nil { return "", fmt.Errorf("read source image %q: %w", srcPath, err) @@ -59,9 +60,35 @@ func copyOwnedObject( if err != nil { return "", fmt.Errorf("save copied image for %q: %w", srcPath, err) } + bindCopiedResource(ctx, catalog, newPath, knowledgeID, relation) return newPath, nil } +// bindCopiedResource claims a cloned object for the destination knowledge. +// Non-catalog paths (legacy provider:// URLs) are left unbound, matching +// Release's treatment of pre-registry locators. +// +// Best-effort, like every other claim path (bindContentResources, +// bindStoredImages): a missed claim degrades to an object only its own +// workspace can fetch -- the file proxies report 403 for everyone else. The +// copy is already written by the time we get here, so failing the clone would +// both discard a correct copy and strand the object we just created. +func bindCopiedResource( + ctx context.Context, + catalog interfaces.ResourceCatalog, + ref, knowledgeID, relation string, +) { + if catalog == nil || knowledgeID == "" || relation == "" { + return + } + if _, ok := types.ParseResourcePath(ref); !ok { + return + } + if err := catalog.Bind(ctx, ref, types.ResourceOwnerKnowledge, knowledgeID, relation); err != nil { + logger.Warnf(ctx, "Failed to bind cloned resource %s to knowledge %s: %v", ref, knowledgeID, err) + } +} + // imageExtForCopy resolves the file extension to use for a copied image. It // prefers an image extension already present on the source path, then falls // back to sniffing the content bytes, and finally defaults to ".png" (matching @@ -114,6 +141,7 @@ func cloneChunkImageInfo( tenantID uint64, knowledgeID string, urlCache map[string]string, + catalog interfaces.ResourceCatalog, ) (newImageInfo string, copiedURLs []string, err error) { if srcImageInfo == "" { return "", nil, nil @@ -132,7 +160,9 @@ func cloneChunkImageInfo( newURL, cached := urlCache[img.URL] if !cached { - newURL, err = copyOwnedObject(ctx, dstSvc, dstSvc, img.URL, tenantID, knowledgeID) + newURL, err = copyOwnedObject( + ctx, dstSvc, dstSvc, img.URL, tenantID, knowledgeID, + catalog, types.ResourceRelationExtractedImage) if err != nil { return "", copiedURLs, fmt.Errorf("failed to copy chunk image %q: %w", img.URL, err) } @@ -337,7 +367,7 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl // child chunks, so a parent text chunk's ![](url) 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) + ctx, dstSvc, sourceChunk.ImageInfo, dst.TenantID, dst.ID, urlCache, s.resourceCatalog) copiedURLs = append(copiedURLs, copied...) if copyErr != nil { err = fmt.Errorf("clone chunk image copy failed: %w", copyErr) @@ -402,6 +432,7 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl return err } } + s.bindChunkResources(ctx, dst.TenantID, dst.ID, targetChunks) tenantID := types.MustTenantIDFromContext(ctx) // Route CopyIndices via the source KB's bound store. This function does @@ -827,7 +858,7 @@ func (s *knowledgeService) cloneFAQKnowledgeBase( // Deep-copy extracted images into objects owned by the destination // FAQ knowledge so deleting the source never breaks this clone. newImageInfo, copied, copyErr := cloneChunkImageInfo( - ctx, dstSvc, srcChunk.ImageInfo, dstKB.TenantID, dstKnowledge.ID, imageURLCache) + ctx, dstSvc, srcChunk.ImageInfo, dstKB.TenantID, dstKnowledge.ID, imageURLCache, s.resourceCatalog) if copyErr != nil { logger.Errorf(ctx, "Failed to copy FAQ chunk images: %v", copyErr) handleError(progress, copyErr, "Failed to copy FAQ entry images") @@ -863,6 +894,7 @@ func (s *knowledgeService) cloneFAQKnowledgeBase( handleError(progress, err, "Failed to create FAQ entries") return err } + s.bindChunkResources(ctx, dstKB.TenantID, dstKnowledge.ID, newChunks) // Saved rows now own these images, including when indexing later fails. // A later batch failure must not delete files from an earlier saved batch. diff --git a/internal/application/service/knowledge_content_binding_test.go b/internal/application/service/knowledge_content_binding_test.go index 14b72ac9..ff0f1cf3 100644 --- a/internal/application/service/knowledge_content_binding_test.go +++ b/internal/application/service/knowledge_content_binding_test.go @@ -48,6 +48,10 @@ func (c *resolvingCatalog) Release(context.Context, string, string, string) (int return -1, nil } +func (c *resolvingCatalog) ListReferencesByOwner(context.Context, string, ...string) ([]string, error) { + return nil, nil +} + func (c *resolvingCatalog) MarkDeleted(context.Context, string) error { return nil } func (c *resolvingCatalog) CreateAccessGrant( @@ -120,3 +124,19 @@ func TestBindContentResourcesIsInertWithoutCatalog(t *testing.T) { // claim and keeps the pre-binding behaviour. svc.bindContentResources(context.Background(), 7, "kn-1", "![a]("+contentRef("f")+")") } + +func TestBindChunkResourcesClaimsContentAndImageInfo(t *testing.T) { + fromContent := contentRef("p") + fromInfo := contentRef("q") + catalog := &resolvingCatalog{tenantByRef: map[string]uint64{fromContent: 7, fromInfo: 7}} + svc := &knowledgeService{resourceCatalog: catalog} + + svc.bindChunkResources(context.Background(), 7, "kn-clone", []*types.Chunk{ + {Content: "![a](" + fromContent + ")"}, + {ImageInfo: `[{"url":"` + fromInfo + `"}]`}, + }) + + if len(catalog.binds) != 2 { + t.Fatalf("binds = %v, want content and image_info handles", catalog.binds) + } +} diff --git a/internal/application/service/knowledge_create.go b/internal/application/service/knowledge_create.go index f34c26c8..413dce68 100644 --- a/internal/application/service/knowledge_create.go +++ b/internal/application/service/knowledge_create.go @@ -1282,6 +1282,25 @@ func (s *knowledgeService) bindStoredImages( } } +func (s *knowledgeService) bindChunkResources( + ctx context.Context, tenantID uint64, knowledgeID string, chunks []*types.Chunk, +) { + if len(chunks) == 0 { + return + } + var b strings.Builder + for _, chunk := range chunks { + if chunk == nil { + continue + } + b.WriteString(chunk.Content) + b.WriteByte('\n') + b.WriteString(chunk.ImageInfo) + b.WriteByte('\n') + } + s.bindContentResources(ctx, tenantID, knowledgeID, b.String()) +} + func (s *knowledgeService) triggerManualProcessing(ctx context.Context, kb *types.KnowledgeBase, knowledge *types.Knowledge, content string, doSync bool, ) error { diff --git a/internal/application/service/knowledge_delete.go b/internal/application/service/knowledge_delete.go index fbf17573..4761d569 100644 --- a/internal/application/service/knowledge_delete.go +++ b/internal/application/service/knowledge_delete.go @@ -41,6 +41,55 @@ func collectImageURLs(ctx context.Context, imageInfos []string) []string { return urls } +// mergeKnowledgeReleaseURLs unions ImageInfo URLs with derived catalog +// bindings for the knowledge entries being removed. Parsed documents often +// embed resource:// handles only in markdown; multimodal ImageInfo is empty +// until (or unless) those tasks finish, so attachment/extracted-image rows +// are the complete claim set. Source files stay out of this list: reparse +// and manual cleanup must keep the original document, and knowledge delete +// already removes FilePath separately. +// +// Only call this from a path that is removing the knowledge for good +// (executeKnowledgeDelete, ProcessKBDelete). Cleanup that runs before a +// re-index must keep collecting ImageInfo alone: the knowledge survives it, +// and DeleteFile marks the object deleted, so the re-claim that follows could +// not resolve the handles it dropped. +func mergeKnowledgeReleaseURLs( + ctx context.Context, + catalog interfaces.ResourceCatalog, + knowledgeIDs []string, + imageURLs []string, +) []string { + seen := make(map[string]struct{}, len(imageURLs)) + out := make([]string, 0, len(imageURLs)) + add := func(url string) { + url = strings.TrimSpace(url) + if url == "" { + return + } + if _, exists := seen[url]; exists { + return + } + seen[url] = struct{}{} + out = append(out, url) + } + for _, url := range imageURLs { + add(url) + } + if catalog == nil || len(knowledgeIDs) == 0 { + return out + } + refs, err := catalog.ListReferencesByOwner(ctx, types.ResourceOwnerKnowledge, knowledgeIDs...) + if err != nil { + logger.Warnf(ctx, "Failed to list knowledge resource bindings for release: %v", err) + return out + } + for _, ref := range refs { + add(ref) + } + return out +} + // knowledgeResourceOwners builds the releaser for a set of knowledge entries // being deleted. A nil catalog (no resource registry) yields nil, which // deleteExtractedImages treats as "delete unconditionally", i.e. the behaviour @@ -476,6 +525,9 @@ func (s *knowledgeService) executeKnowledgeDelete(plan *knowledgeDeletePlan, sin for _, k := range knowledgeList { kbKnowledgeIDs[k.KnowledgeBaseID] = append(kbKnowledgeIDs[k.KnowledgeBaseID], k.ID) } + for kbID, ids := range kbKnowledgeIDs { + kbImageURLs[kbID] = mergeKnowledgeReleaseURLs(ctx, s.resourceCatalog, ids, kbImageURLs[kbID]) + } wg := errgroup.Group{} // 2. Delete knowledge embeddings from vector store @@ -669,6 +721,14 @@ func (s *knowledgeService) cleanupKnowledgeResources(ctx context.Context, knowle for _, ci := range chunkImageInfos { imageInfoStrs = append(imageInfoStrs, ci.ImageInfo) } + // Release only what ImageInfo accounts for. This cleanup runs before the + // knowledge is re-indexed (manual update, reparse, move with reparse), not + // before it goes away, and the re-claim in triggerManualProcessing can only + // succeed while the object is alive: DeleteFile marks the resource deleted, + // and Bind resolves through a state=active lookup, so the handle could never + // be re-bound. Unioning in catalog bindings here would therefore delete + // markdown-only images that the new body still references. The paths that + // actually remove a knowledge entry do union -- see mergeKnowledgeReleaseURLs. imageURLs := collectImageURLs(ctx, imageInfoStrs) if err := s.chunkRepo.DeleteChunksByKnowledgeID(ctx, knowledge.TenantID, knowledge.ID); err != nil { diff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.go index 86ec93cb..dd00eebc 100644 --- a/internal/application/service/knowledge_process.go +++ b/internal/application/service/knowledge_process.go @@ -98,7 +98,9 @@ func (s *knowledgeService) cloneKnowledge( } srcSvc := s.resolveFileServiceForPath(ctx, srcKB, src.FilePath) dstSvc := s.resolveFileService(ctx, targetKB) - newPath, copyErr := copyOwnedObject(ctx, srcSvc, dstSvc, src.FilePath, targetKB.TenantID, dst.ID) + newPath, copyErr := copyOwnedObject( + ctx, srcSvc, dstSvc, src.FilePath, targetKB.TenantID, dst.ID, + s.resourceCatalog, types.ResourceRelationSourceFile) if copyErr != nil { return fmt.Errorf("clone knowledge file copy failed: %w", copyErr) } diff --git a/internal/application/service/knowledge_resource_release_test.go b/internal/application/service/knowledge_resource_release_test.go index db19e6f9..ba118f3e 100644 --- a/internal/application/service/knowledge_resource_release_test.go +++ b/internal/application/service/knowledge_resource_release_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" ) // deleteRecorder captures which files a cleanup actually removed. @@ -104,3 +105,157 @@ func TestDeleteExtractedImagesWithoutCatalogDeletesEverything(t *testing.T) { t.Fatalf("deleted %v, want %v", files.deleted, urls) } } + +func TestMergeKnowledgeReleaseURLsIncludesOwnerBindings(t *testing.T) { + legacy := "local://7/exports/old.png" + bound := handleRef("m") + catalog := &fakeCatalog{ + ownerRefs: map[string][]string{"kn-1": {bound}}, + releaseRemaining: map[string]int64{bound: 0}, + } + files := &deleteRecorder{} + + urls := mergeKnowledgeReleaseURLs(context.Background(), catalog, []string{"kn-1"}, []string{legacy}) + deleteExtractedImages(context.Background(), files, knowledgeResourceOwners(catalog, "kn-1"), urls) + + want := []string{legacy, bound} + if len(files.deleted) != len(want) { + t.Fatalf("deleted %v, want %v", files.deleted, want) + } + for i, url := range want { + if files.deleted[i] != url { + t.Fatalf("deleted[%d] = %q, want %q", i, files.deleted[i], url) + } + } +} + +func TestMergeKnowledgeReleaseURLsReleasesMarkdownOnlyBindings(t *testing.T) { + bound := handleRef("n") + catalog := &fakeCatalog{ + ownerRefs: map[string][]string{"kn-1": {bound}}, + releaseRemaining: map[string]int64{bound: 0}, + } + files := &deleteRecorder{} + + urls := mergeKnowledgeReleaseURLs(context.Background(), catalog, []string{"kn-1"}, nil) + deleteExtractedImages(context.Background(), files, knowledgeResourceOwners(catalog, "kn-1"), urls) + + if len(files.deleted) != 1 || files.deleted[0] != bound { + t.Fatalf("deleted %v, want markdown-bound handle %q", files.deleted, bound) + } +} + +// Cleanup runs before a re-index (manual update, reparse), not before the +// knowledge goes away. A markdown-only attachment never appears in ImageInfo, +// so unioning the catalog bindings in here released it, DeleteFile marked the +// resource deleted, and the re-claim that follows could no longer resolve the +// handle -- the republished body was left pointing at a deleted image. The +// file and its binding must both outlive the cleanup. +func TestCleanupKeepsMarkdownOnlyAttachment(t *testing.T) { + catalog, _ := newResourceCatalogForTest(t) + handle, err := catalog.Register( + context.Background(), 7, "local://7/exports/markdown-only.png", + interfaces.ResourceRegistration{Kind: "image"}, + ) + if err != nil { + t.Fatalf("register markdown-only image: %v", err) + } + if err := catalog.Bind( + context.Background(), handle, types.ResourceOwnerKnowledge, "doc", + types.ResourceRelationAttachment, + ); err != nil { + t.Fatalf("bind markdown-only image: %v", err) + } + + f := newDocumentWriteFixture(t) + f.svc.resourceCatalog = catalog + row, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc") + if err != nil { + t.Fatalf("load knowledge: %v", err) + } + // The fixture chunk carries no ImageInfo, which is what makes this case + // invisible to the pre-change release set. + if err := f.svc.cleanupKnowledgeResources(f.ctx, row); err != nil { + t.Fatalf("cleanup: %v", err) + } + + if len(f.files.deleted) != 0 { + t.Fatalf("cleanup deleted %v, want the solely owned image kept", f.files.deleted) + } + refs, err := catalog.ListReferencesByOwner(f.ctx, types.ResourceOwnerKnowledge, "doc") + if err != nil { + t.Fatalf("list owner references: %v", err) + } + if len(refs) != 1 || refs[0] != handle { + t.Fatalf("owner references = %v, want the attachment %q still bound", refs, handle) + } + // Still resolvable, so the re-claim after cleanup can bind it again. + resource, err := catalog.Resolve(f.ctx, handle) + if err != nil || resource == nil { + t.Fatalf("resolve after cleanup = (%v, %v), want the live resource", resource, err) + } +} + +// The delete paths keep the union: the knowledge is going away, so a +// markdown-only attachment has no re-claim to survive for. +func TestKnowledgeDeleteReleasesMarkdownOnlyAttachment(t *testing.T) { + catalog, _ := newResourceCatalogForTest(t) + handle, err := catalog.Register( + context.Background(), 7, "local://7/exports/markdown-only.png", + interfaces.ResourceRegistration{Kind: "image"}, + ) + if err != nil { + t.Fatalf("register markdown-only image: %v", err) + } + if err := catalog.Bind( + context.Background(), handle, types.ResourceOwnerKnowledge, "doc", + types.ResourceRelationAttachment, + ); err != nil { + t.Fatalf("bind markdown-only image: %v", err) + } + + f := newDocumentWriteFixture(t) + f.svc.resourceCatalog = catalog + if err := f.svc.DeleteKnowledge(f.ctx, "doc"); err != nil { + t.Fatalf("delete knowledge: %v", err) + } + + if len(f.files.deleted) != 1 || f.files.deleted[0] != handle { + t.Fatalf("deleted %v, want the released markdown-only handle %q", f.files.deleted, handle) + } + refs, err := catalog.ListReferencesByOwner(f.ctx, types.ResourceOwnerKnowledge, "doc") + if err != nil { + t.Fatalf("list owner references: %v", err) + } + if len(refs) != 0 { + t.Fatalf("owner references = %v, want every claim released", refs) + } +} + +func TestMergeKnowledgeReleaseURLsOmitsSourceFileBinding(t *testing.T) { + catalog, _ := newResourceCatalogForTest(t) + ctx := context.Background() + image, err := catalog.Register(ctx, 7, "local://7/exports/a.png", interfaces.ResourceRegistration{}) + if err != nil { + t.Fatalf("register image: %v", err) + } + source, err := catalog.Register(ctx, 7, "local://7/docs/source.pdf", interfaces.ResourceRegistration{}) + if err != nil { + t.Fatalf("register source: %v", err) + } + if err := catalog.Bind( + ctx, image, types.ResourceOwnerKnowledge, "kn-1", types.ResourceRelationExtractedImage, + ); err != nil { + t.Fatalf("bind image: %v", err) + } + if err := catalog.Bind( + ctx, source, types.ResourceOwnerKnowledge, "kn-1", types.ResourceRelationSourceFile, + ); err != nil { + t.Fatalf("bind source: %v", err) + } + + urls := mergeKnowledgeReleaseURLs(ctx, catalog, []string{"kn-1"}, nil) + if len(urls) != 1 || urls[0] != image { + t.Fatalf("release URLs = %v, want only extracted image %q", urls, image) + } +} diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go index 94a5818b..4af4739f 100644 --- a/internal/application/service/knowledgebase.go +++ b/internal/application/service/knowledgebase.go @@ -1032,7 +1032,8 @@ func (s *knowledgeBaseService) ProcessKBDelete(ctx context.Context, t *asynq.Tas for _, ci := range chunkImageInfos { imageInfoStrs = append(imageInfoStrs, ci.ImageInfo) } - imageURLs := collectImageURLs(ctx, imageInfoStrs) + imageURLs := mergeKnowledgeReleaseURLs( + ctx, s.resourceCatalog, knowledgeIDs, collectImageURLs(ctx, imageInfoStrs)) // Delete all chunks logger.Infof(ctx, "Deleting all chunks in knowledge base") diff --git a/internal/application/service/resource.go b/internal/application/service/resource.go index c46443bc..b6434ee0 100644 --- a/internal/application/service/resource.go +++ b/internal/application/service/resource.go @@ -223,6 +223,38 @@ func (s *resourceCatalog) Release( return s.repo.CountBindings(ctx, resource.ID) } +func (s *resourceCatalog) ListReferencesByOwner( + ctx context.Context, ownerType string, ownerIDs ...string, +) ([]string, error) { + ids := make([]string, 0, len(ownerIDs)) + for _, id := range ownerIDs { + if strings.TrimSpace(id) != "" { + ids = append(ids, id) + } + } + if strings.TrimSpace(ownerType) == "" || len(ids) == 0 { + return nil, nil + } + handles, err := s.repo.ListHandlesByOwner(ctx, ownerType, ids, []string{ + types.ResourceRelationAttachment, + types.ResourceRelationExtractedImage, + }) + if err != nil { + return nil, err + } + refs := make([]string, 0, len(handles)) + seen := make(map[string]struct{}, len(handles)) + for _, handle := range handles { + ref := types.BuildResourcePath(handle) + if _, exists := seen[ref]; exists { + continue + } + seen[ref] = struct{}{} + refs = append(refs, ref) + } + return refs, nil +} + func (s *resourceCatalog) MarkDeleted(ctx context.Context, reference string) error { resource, err := s.Resolve(ctx, reference) if err != nil { diff --git a/internal/application/service/resource_test.go b/internal/application/service/resource_test.go index 084abe4a..7b991b37 100644 --- a/internal/application/service/resource_test.go +++ b/internal/application/service/resource_test.go @@ -123,6 +123,36 @@ func TestResourceCatalogReleaseUnknownReference(t *testing.T) { require.Error(t, err, "an owner is required to release a claim") } +func TestResourceCatalogListReferencesByOwner(t *testing.T) { + catalog, _ := newResourceCatalogForTest(t) + ctx := context.Background() + first, err := catalog.Register(ctx, 7, "local://7/exports/a.png", interfaces.ResourceRegistration{}) + require.NoError(t, err) + second, err := catalog.Register(ctx, 7, "local://7/exports/b.png", interfaces.ResourceRegistration{}) + require.NoError(t, err) + require.NoError(t, catalog.Bind(ctx, first, types.ResourceOwnerKnowledge, "kn-1", types.ResourceRelationAttachment)) + require.NoError(t, catalog.Bind( + ctx, second, types.ResourceOwnerKnowledge, "kn-1", types.ResourceRelationExtractedImage)) + require.NoError(t, catalog.Bind(ctx, first, types.ResourceOwnerKnowledge, "kn-2", types.ResourceRelationAttachment)) + + source, err := catalog.Register(ctx, 7, "local://7/docs/source.pdf", interfaces.ResourceRegistration{}) + require.NoError(t, err) + require.NoError(t, catalog.Bind( + ctx, source, types.ResourceOwnerKnowledge, "kn-1", types.ResourceRelationSourceFile)) + + refs, err := catalog.ListReferencesByOwner(ctx, types.ResourceOwnerKnowledge, "kn-1") + require.NoError(t, err) + require.ElementsMatch(t, []string{first, second}, refs) + + refs, err = catalog.ListReferencesByOwner(ctx, types.ResourceOwnerKnowledge, "kn-1", "kn-2") + require.NoError(t, err) + require.ElementsMatch(t, []string{first, second}, refs) + + refs, err = catalog.ListReferencesByOwner(ctx, types.ResourceOwnerKnowledge) + require.NoError(t, err) + require.Empty(t, refs) +} + // Rendering one answer resolves the same image many times, and re-reading a // message history resolves it again on every call. Each resolution used to // insert a capability row; a live one must be reused instead. diff --git a/internal/router/router_files_test.go b/internal/router/router_files_test.go index f0341824..83cab5ca 100644 --- a/internal/router/router_files_test.go +++ b/internal/router/router_files_test.go @@ -99,6 +99,10 @@ func (s *stubResourceCatalog) Release(context.Context, string, string, string) ( panic("unexpected Release") } +func (s *stubResourceCatalog) ListReferencesByOwner(context.Context, string, ...string) ([]string, error) { + return nil, nil +} + func (s *stubResourceCatalog) MarkDeleted(context.Context, string) error { panic("unexpected MarkDeleted") } diff --git a/internal/types/interfaces/resource.go b/internal/types/interfaces/resource.go index d85cbcc3..262fd4d8 100644 --- a/internal/types/interfaces/resource.go +++ b/internal/types/interfaces/resource.go @@ -29,6 +29,7 @@ type ResourceRepository interface { CreateBinding(ctx context.Context, binding *types.ResourceBinding) error DeleteBinding(ctx context.Context, resourceID, ownerType, ownerID string) error CountBindings(ctx context.Context, resourceID string) (int64, error) + ListHandlesByOwner(ctx context.Context, ownerType string, ownerIDs, relations []string) ([]string, error) IsReferencedByKnowledgeBase( ctx context.Context, tenantID uint64, @@ -71,6 +72,17 @@ type ResourceCatalog interface { // catalog handle, or the count could not be read), which callers should // treat as "delete as before" rather than as "keep forever". Release(ctx context.Context, reference, ownerType, ownerID string) (remaining int64, err error) + // ListReferencesByOwner returns derived resource:// handles still claimed + // by any of the given owners (extracted images and markdown attachments). + // Source files are omitted: reparse/cleanup must keep the original + // document, which knowledge delete removes through FilePath. + // + // Knowledge-delete paths union this with ImageInfo URLs so markdown-only + // images are released even when multimodal never wrote ImageInfo. Cleanup + // before a re-index must not: it leaves the knowledge in place, and the + // handles it released could not be re-bound once DeleteFile marked them + // deleted. + ListReferencesByOwner(ctx context.Context, ownerType string, ownerIDs ...string) ([]string, error) MarkDeleted(ctx context.Context, reference string) error CreateAccessGrant(ctx context.Context, reference string, ttl time.Duration) (string, error) ResolveAccessGrant(ctx context.Context, token string) (*types.StoredResource, error)