Skip to content

fix: use id and kb_id when deleting dataset metadata - #20880

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
aniketkrs:fix/dataset-delete-metadata-keys
Oct 16, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
aniketkrs:fix/dataset-delete-metadata-keys

Conversation

@aniketkrs

Copy link
Copy Markdown
Contributor

Fixes #20779

User impact: deleting a dataset removes its chunks but silently leaves rows in the dataset metadata index. The dead document metadata keeps appearing in metadata value lists and filters after the dataset is gone.

Technical cause: deleteDatasetEngineData calls DeleteMetadata with {"doc_id": docIDs}, but metadata rows are keyed by id and kb_id. The engine query builder only gives kb_id and id list treatment; doc_id falls into the default branch which builds a single-value term query for a slice, which Elasticsearch rejects. The error is only logged as a warning, so the failure is silent. The sibling DeleteDocumentAllMetadata correctly passes {"id", "kb_id"}.

Fix: pass {"id": docIDs, "kb_id": kb.ID} to DeleteMetadata, matching the sibling caller. The DeleteChunks call is untouched because chunk rows are genuinely keyed by doc_id.

DeleteMetadata keys metadata rows by id/kb_id, not doc_id.
Passing doc_id built an invalid single-value term query for a
slice, so the delete silently failed and metadata rows were
orphaned on dataset deletion.
Copilot AI balanced review requested due to automatic review settings October 13, 2026 06:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: edc660d8-dd83-4d26-8564-6199578ef8ca
📥 Commits

Reviewing files that changed from the base of the PR and between 6e83a7c and 2a0cd65.

📒 Files selected for processing: 2
  • internal/service/dataset/crud.go
  • internal/service/dataset/crud_delete_metadata_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📝 Walkthrough

Dataset deletion now targets engine metadata by dataset ID (kb_id) instead of document IDs. A regression test checks the deletion condition and tenant, and confirms that the condition excludes id and doc_id.

Changes: Dataset metadata cleanup

Layer / File(s) Summary
Metadata deletion filter
internal/service/dataset/crud.go, internal/service/dataset/crud_delete_metadata_test.go
Metadata deletion uses the dataset’s kb_id. The regression test checks the condition and tenant, and confirms that the condition does not include id or doc_id.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~5 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: jinhai-cn

Merge Risk: ⚪ Minimal · up to 2a0cd

The metadata deletion condition addresses the reported cleanup failure. No identified issue needs resolution before merging.

Pre-merge checks: Passed 5
Passed Passed checks: 5 passed
Check name Status Explanation
Title check Passed The title is related to the metadata deletion fix and identifies the relevant id and kb_id fields, although it is not fully accurate because the implemented change uses kb_id only.
Description check Passed The description clearly explains the user impact, technical cause, scope, and fix. It provides the required background and implementation details, although it does not use the template's "### Summary"…
Linked Issues check Passed Issue #20779 requires dataset deletion to remove document metadata rows. deleteDatasetEngineData now calls DeleteMetadata with {"kb_id": kb.ID}. This selects all metadata rows for the dataset, i…
Out of Scope Changes check Passed The pull request changes only the metadata condition in internal/service/dataset/crud.go and adds a focused regression test. Both changes directly support issue #20779. Chunk deletion and warning-on…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks the dataset key,
And tests which rows the call will see.
No doc_id bounds the sweep,
The tenant is recorded deep.
The metadata rows now clear.

Comment @coderabbitai help to get the list of available commands.

@qinling0210 qinling0210 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add the regression test

The diff is a single hunk in one file with no test, even though #20779's testing section describes a TestDeleteDatasetEngineDataDeletesMetadataByDataset that fails before the change.

Nothing in the package currently exercises this function: crud_delete_test.go builds its service via testDatasetUpdateService (internal/service/dataset/update_test.go:1050-1058), which leaves docEngine nil, so deleteDatasetEngineData early-returns and the condition is never passed to the engine. Since the failure modes here are engine-specific and silent (ES 400, Infinity unknown column, Vastbase 0 rows with no error), an assertion on the recorded condition is the only cheap guard we have.

A pure unit test needs no DB or storage — the package already has fakeChatDocEngine in internal/service/dataset/fake_doc_engine_test.go to embed:

type recordingMetadataEngine struct {
	fakeChatDocEngine
	cond   map[string]interface{}
	tenant string
}

func (e *recordingMetadataEngine) DeleteMetadata(_ context.Context, cond map[string]interface{}, tenantID string) (int64, error) {
	e.cond, e.tenant = cond, tenantID
	return 0, nil
}

func TestDeleteDatasetEngineDataDeletesMetadataByDataset(t *testing.T) {
	eng := &recordingMetadataEngine{}
	svc := &DatasetService{docEngine: eng}
	svc.deleteDatasetEngineData(t.Context(), &entity.Knowledgebase{ID: "kb-1", TenantID: "tenant-1"}, []string{"doc-1", "doc-2"})

	if got := eng.cond["kb_id"]; got != "kb-1" {
		t.Fatalf("metadata condition kb_id = %v, want kb-1", got)
	}
	if got, ok := eng.cond["id"]; !ok || !reflect.DeepEqual(got, []string{"doc-1", "doc-2"}) {
		t.Fatalf("metadata condition id = %v", eng.cond["id"])
	}
	if _, ok := eng.cond["doc_id"]; ok {
		t.Fatalf("metadata condition still uses doc_id: %v", eng.cond)
	}
}

(Update the id assertion to kb_id if you take the Comment 1 suggestion.)

If you keep the id-list form, an additional engine-level test on buildMetadataQueryFromCondition pinning that a slice under a non-list key becomes a term with an array value would cover the trap that caused this bug.

Comment thread internal/service/dataset/crud.go Outdated
common.Logger.Warn(fmt.Sprintf("deleteDataset: failed to delete chunks for kb %s: %v", kb.ID, err))
}
if _, err := d.docEngine.DeleteMetadata(ctx, map[string]interface{}{"doc_id": docIDs}, kb.TenantID); err != nil {
if _, err := d.docEngine.DeleteMetadata(ctx, map[string]interface{}{"id": docIDs, "kb_id": kb.ID}, kb.TenantID); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: filter by kb_id alone

Verified the row shape on all five engines: metadata rows are {id = document id, kb_id = dataset id, meta_fields} (conf/doc_meta_es_mapping.json, conf/doc_meta_infinity_mapping.json, UpdateMetadata in each engine), so doc_id was indeed the wrong key and this fix works for the reported repro. One follow-up though: this call site is the only one that passes a whole dataset's id list (the sibling DeleteDocumentAllMetadata passes a single document), and that list is unbounded:

  • deleteDataset loads documents with an unpaged Where("kb_id = ?") (crud.go:399-402), so docIDs can be tens of thousands. ES's default index.max_terms_count is 65536 — a dataset above that still gets a 400 and leaks rows silently, in exactly the way this PR is fixing.
  • It cannot clean rows whose document row is already gone (the RemoveDocumentKeepFile case in RemoveDocumentKeepFile deletes the document row but not its chunk data or metadata record #20659), while kb_id can.
  • The tenant-deletion path already chunks deletes at 1000 for this reason (internal/admin/user_delete.go:363-382).

kb_id is stored and indexed on every engine (ES mapping is keyword; OceanBase/Infinity/Vastbase create secondary indexes on it; serenedb accepts it via recognizedFilterKey), so a single-clause condition is valid everywhere and removes the list handling from the picture entirely:

Suggested change
if _, err := d.docEngine.DeleteMetadata(ctx, map[string]interface{}{"id": docIDs, "kb_id": kb.ID}, kb.TenantID); err != nil {
if _, err := d.docEngine.DeleteMetadata(ctx, map[string]interface{}{"kb_id": kb.ID}, kb.TenantID); err != nil {

If you go this way, the len(docIDs) == 0 guards (crud.go:436-438 and the early return at crud.go:737-739) become unnecessary for metadata; replacing the early return with if d.docEngine == nil { return } and guarding only the DeleteChunks call would also clean up datasets that still hold orphan rows but have no document rows left.

@aniketkrs

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review! I took the kb_id-alone suggestion: the delete call now passes only {"kb_id": kb.ID}, so the dataset's metadata rows are selected regardless of how many documents it holds, and orphaned rows from already-deleted documents are cleaned up too.

I double checked the single-value kb_id condition in buildMetadataQueryFromCondition (the case "kb_id": branch sends non-list values to a term query), which matches the row shape {id = document id, kb_id = dataset id} you verified on all engines.

Also added TestDeleteDatasetEngineDataDeletesMetadataByDataset (internal/service/dataset/crud_delete_metadata_test.go) using a recording engine over fakeChatDocEngine. It pins the metadata condition to kb_id = the dataset id and asserts no id/doc_id keys are present. No DB needed.

Ready for re-review whenever you get a moment.

@qinling0210 qinling0210 added the ci Continue Integration label Oct 14, 2026
@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator

Read through the final diff (head 2a0cd65) against main. Looks right to me.

  • The ES buildMetadataQueryFromCondition handles kb_id as a scalar term, and DeleteMetadata runs delete-by-query on the per-tenant metadata index, so {"kb_id": kb.ID} removes every row of the dataset, including rows whose document is already gone. The old doc_id key had no case in that builder, which is why the slice ended up in a single-value term query.
  • Dropping the id list is a good call, since a big dataset would hit index.max_terms_count on the terms query.
  • The regression test pins the condition (kb_id set, no id, no doc_id, tenant passed through), which is the behavior that was broken.

One note: I could not run go test ./internal/service/dataset/ here. The package did not build within my sandbox's memory, so this is a read-through review and not a test run. Worth confirming on CI. I also only checked the ES path, not the Infinity/OceanBase/SereneDB DeleteMetadata implementations against a bare kb_id condition, though the sibling DeleteDocumentAllMetadata already passes kb_id to them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Go: deleting a dataset leaves its document metadata rows in ragflow_doc_meta_<tenant>

5 participants