Skip to content

fix(dataset): release segment attachments correctly when documents are deleted - #42642

Open
JessYanCoding wants to merge 3 commits into
langgenius:mainfrom
JessYanCoding:fix/clean-document-attachments
Open

JessYanCoding wants to merge 3 commits into
langgenius:mainfrom
JessYanCoding:fix/clean-document-attachments

Conversation

@JessYanCoding

@JessYanCoding JessYanCoding commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #42641.

Deleting a knowledge-base document mishandled its segments' attachments, in both the single-delete path (clean_document_task) and the batch path (batch_clean_document_task):

  1. The attachment vectors were never removed. They are written under doc_id == UploadFile.id by Vector.create_multimodal, while every node id clean_document_indexes derives comes from segments, summaries or child chunks. They outlived the document permanently, kept consuming top-k slots, and RetrievalService.get_segment_attachment_infos dropped them silently because no row backed them any more.
  2. An attachment another document still referenced was destroyed. SegmentAttachmentBinding.attachment_id carries no uniqueness constraint, so one UploadFile can be bound to segments of several documents, and both tasks deleted the row and blob for every binding the deleted document held. Both also ordered the UploadFile delete before the binding delete.

The fix

Both tasks now call one new function, release_document_attachments in services/knowledge/indexing/adapters/cleanup.py, which:

  • discovers attachments through their bindings (document_id IN (...)), not through segments, so a failed release is picked up by a later run even after the segments are gone;
  • decides two scopes separately — the vector lives in this dataset's collection and is deleted once no other binding in this dataset remains; the UploadFile row and blob are shared and go only once no binding anywhere remains;
  • locks each attachment (segment_attachment_release_lock_{id}, acquired in sorted id order) while its remaining references are counted and released, and commits the binding deletion before releasing the lock, so concurrent deletions of documents sharing an attachment cannot each see the other's binding and both keep it;
  • deletes vectors before bindings, so if the vector deletion fails the bindings are still there for the next attempt.

A Redis lock rather than SELECT ... FOR UPDATE, because the vector deletion in between is external I/O, which #41729 keeps outside database transactions. Attachments are processed 100 at a time to bound both the number of locks held and the size of each IN clause.

The previous revision of this PR added an extra_node_ids parameter to clean_document_indexes; that is reverted, since the orphan decision now has to happen under the lock.

Out of scope: delete_segment_from_index_task and document_indexing_update_task release attachments through their own path and do not take this lock.

Tests

13 new tests; production code is +136/-49.

Each review point has a targeted mutation, and each is caught by exactly the test written for it:

Mutation Caught by
count references before taking the lock test_references_are_counted_while_the_attachment_lock_is_held
decide vector orphans with the global scope test_attachment_bound_only_in_another_dataset_drops_this_datasets_vector_but_keeps_the_file
delete bindings before vectors test_failed_vector_deletion_keeps_bindings_for_a_retry
acquire locks in reverse order test_each_attachment_is_locked_in_sorted_order
discover attachments only while their segment still exists 10 tests, incl. both task-level retry tests
count the document's own bindings as remaining 9 tests

The lock test is deterministic rather than threaded: the lock's __enter__ commits a competing release, which is exactly the window a count taken before the lock would miss.

Verification

On a4f949f:

  • pytest api/tests/unit_tests/tasks api/tests/unit_tests/services/knowledge — 763 passed (750 on main, +13)
  • pytest api/tests/unit_tests — 21961 passed. The 33 failures are missing optional VDB plugin packages in my local environment plus test_zip64_extensible_data_is_not_part_of_central_directory; a clean checkout reproduces the same 33 with 21948 passed.
  • ruff format --check / ruff check — clean
  • lint-imports — 59 contracts kept, 0 broken
  • pyrefly check on the changed production files — 0 diagnostics
  • pyrefly --config=tests/unit_tests/pyrefly.toml — 0 diagnostics on the new test file; identical counts before and after on the two modified ones
  • check_no_new_getattr.py / check_no_new_controller_sqlalchemy.py — both clean
  • api/uv.lock unchanged

Not verified

The lock and vector boundaries are mocked; I could not exercise real Redis contention or a real vector backend locally.

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.
  • I ran make lint && make type-check (backend) and vp staged (frontend) to appease the lint gods

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 71.92% 71.94% +0.02%
Strict coverage 71.58% 71.60% +0.02%
Typed symbols 58,123 58,196 +73
Untyped symbols 22,801 22,802 +1
Modules 3744 3745 +1

@codecov

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.77%. Comparing base (2f20c7d) to head (a98bdaf).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #42642      +/-   ##
==========================================
- Coverage   88.78%   88.77%   -0.02%     
==========================================
  Files        5322     5225      -97     
  Lines      329792   327150    -2642     
  Branches    66060    65487     -573     
==========================================
- Hits       292802   290417    -2385     
+ Misses      31749    31494     -255     
+ Partials     5241     5239       -2     
Flag Coverage Δ
api 88.42% <100.00%> (-0.09%) ⬇️
cli ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ghfind-review ghfind-review Bot added review: high ghfind author score; see https://ghfind.com and removed review: high ghfind author score; see https://ghfind.com labels Sep 22, 2026
@JessYanCoding
JessYanCoding force-pushed the fix/clean-document-attachments branch from 731a812 to 72abd6c Compare September 29, 2026 14:10
@github-actions github-actions Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Sep 29, 2026

@41tair 41tair left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

And we suggest writing code comments in English.

Comment thread api/tasks/batch_clean_document_task.py Resolved
Comment thread api/tasks/clean_document_task.py Resolved
Comment thread api/tasks/batch_clean_document_task.py Resolved
JessYanCoding and others added 2 commits October 10, 2026 18:00
…e deleted

Rewritten on top of langgenius#41729, which replaced the inline `index_processor.clean(...)`
block in both document-deletion tasks with `clean_document_indexes(document_ids=...)`.
The new adapter derives its node ids from DocumentSegment / DocumentSegmentSummary /
ChildChunk only, so it cannot see segment attachments, and the previous approach of
appending orphan attachment ids to `index_node_ids` no longer has anywhere to go.

Two defects survived the refactor unchanged:

1. Attachment vectors are never removed. They are written under
   `doc_id == UploadFile.id` by `Vector.create_multimodal`, while the node ids the
   cleanup derives come from segments, summaries and child chunks. They therefore
   outlive the document permanently, keep consuming top-k slots and quietly degrade
   recall, and `RetrievalService.get_segment_attachment_infos` drops them silently
   because no row backs them any more.

2. An attachment another document still references is destroyed.
   `SegmentAttachmentBinding.attachment_id` carries no uniqueness constraint, so the
   same `UploadFile` may be bound to segments of several documents. Both tasks deleted
   the row and its blob for every binding the deleted document held. Both also ordered
   the `UploadFile` delete before the binding delete, so the surviving bindings could
   not have been consulted even in principle.

`clean_document_indexes` grows a keyword-only `extra_node_ids` parameter with a default,
so `clean_notion_document_task` is unaffected. Those ids join the vector deletion only:
`body_node_ids` still drives the Jieba keyword index, which never held attachment
vectors. Deciding which attachments are genuinely orphaned stays with the caller,
because that answer depends on bindings outside the documents being cleaned.

Both tasks now compute the orphan set up front, pass it as `extra_node_ids`, delete
bindings before attachment rows, and only delete attachments nothing else references.
In `batch_clean_document_task` the binding deletion moves out of the per-batch loop in
Step 5 into its own Step 3.5 with its own try/except.

Verification on a4f949f (origin/main with langgenius#41729 merged):

- `pytest api/tests/unit_tests/tasks` - 333 passed (327 on main, so +6)
- `pytest api/tests/unit_tests/services/knowledge/test_document_index_cleanup.py` -
  17 passed (14 on main, so +3)
- `pytest api/tests/unit_tests` - 21957 passed. The 33 failures are missing optional
  VDB plugin packages plus `test_zip64_extensible_data_is_not_part_of_central_directory`;
  a clean checkout of the same commit reproduces exactly the same 33 with 21948 passed.
- reverting only the three production files with the tests kept - 7 failed, 5 passed
- `ruff format --check` / `ruff check` - clean
- `lint-imports` - 59 contracts kept, 0 broken
- `pyrefly check` on the changed production files - 0 diagnostics
- `pyrefly --config=tests/unit_tests/pyrefly.toml` on the changed test files - identical
  diagnostic counts before and after, so no new strict-mode debt
- `check_no_new_getattr.py` and `check_no_new_controller_sqlalchemy.py` - both clean
- `api/uv.lock` unchanged

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…tryably

Addresses review on langgenius#42642. Both document-deletion tasks now call one new
function, `release_document_attachments` in
services/knowledge/indexing/adapters/cleanup.py, instead of handling
attachments inline:

- Attachments are discovered through their bindings (`document_id IN ...`)
  rather than through segments, so a release that failed is picked up by a
  later run even after the segments have been deleted.
- Two scopes are decided separately. The vector lives in this dataset's
  collection and is deleted once no other binding in this dataset remains;
  the UploadFile row and blob are shared and go only once no binding
  anywhere remains.
- Each attachment is locked (acquired in sorted id order) while its
  remaining references are counted and released, and the binding deletion
  commits before the lock is released, so concurrent deletions of documents
  sharing an attachment cannot each see the other's binding and both keep it.
- Vectors are deleted before bindings, so a failed vector deletion leaves the
  bindings in place for the next attempt.

A Redis lock is used rather than SELECT ... FOR UPDATE because the vector
deletion in between is external I/O, which langgenius#41729 keeps outside database
transactions. The `extra_node_ids` parameter the previous revision added to
`clean_document_indexes` is reverted, since the orphan decision now has to be
made under the lock. All code comments are in English.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@JessYanCoding
JessYanCoding force-pushed the fix/clean-document-attachments branch from 72abd6c to 4259508 Compare October 10, 2026 10:05
@JessYanCoding

Copy link
Copy Markdown
Contributor Author

Switched all code comments to English.

@JessYanCoding
JessYanCoding requested a review from 41tair October 10, 2026 10:19
Comment on lines +198 to +199
if high_quality and vector_orphan_ids:
Vector(dataset, session=None, vector_type=vector_type).delete_by_ids(vector_orphan_ids)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please scope vector deletion to the current dataset. Qdrant shares collections and filters only by attachment ID, so this can delete another dataset’s surviving vector.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — confirmed. QdrantVector.delete_by_ids filters on metadata.doc_id only, while delete and search_* also filter on group_id; Relyt and TiDB-on-Qdrant behave the same way. Segment node ids are unique per dataset, so this never mattered before, but attachment vectors share doc_id == UploadFile.id across datasets.

I can see two ways to fix it:
(a) add the group_id condition to delete_by_ids in those three providers — strictly narrower for every existing caller, since segment node ids never cross datasets; or
(b) leave the providers alone and only delete the attachment vector when no other dataset sharing this collection still binds the attachment — but that leaves this dataset's now-unreferenced point behind in shared collections.

(a) looks more correct to me, but it touches three provider packages. Which would you prefer? I'll address the per-batch storage cleanup in the meantime.

Comment on lines +215 to +217
if file_orphan_ids:
session.execute(delete(UploadFile).where(UploadFile.id.in_(file_orphan_ids)))
return storage_keys

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please preserve storage keys from committed batches when a later batch fails. Their bindings and file rows are already deleted, so retries cannot discover the remaining blobs. Return results per batch or persist pending cleanup.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Each batch now deletes its blobs through a delete_file callback as soon as that batch commits, instead of the keys being returned at the end, so a later batch failing can no longer strand them. test_committed_batches_delete_their_files_even_when_a_later_batch_fails runs two single-attachment batches with the second one failing. A blob that cannot be deleted is logged and skipped, as elsewhere in document cleanup.

Addresses review on langgenius#42642. `release_document_attachments` returned the
storage keys of every batch at the end, so a later batch failing discarded
the keys of batches that had already committed. Their bindings and
UploadFile rows were gone by then, so no retry could rediscover those blobs.

The function now takes a `delete_file` callback and deletes each batch's
blobs right after that batch commits. A blob that cannot be deleted is
logged and skipped, as elsewhere in document cleanup. Passing the callback
in keeps the adapter free of a storage dependency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review: high ghfind author score; see https://ghfind.com size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deleting a document orphans its segment-attachment vectors and destroys attachments other documents still reference

2 participants