Repository navigation
fix(dataset): release segment attachments correctly when documents are deleted - #42642
JessYanCoding wants to merge 3 commits into
Conversation
Pyrefly Type Coverage
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
731a812 to
72abd6c
Compare
41tair
left a comment
There was a problem hiding this comment.
And we suggest writing code comments in English.
…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]>
72abd6c to
4259508
Compare
|
Switched all code comments to English. |
| if high_quality and vector_orphan_ids: | ||
| Vector(dataset, session=None, vector_type=vector_type).delete_by_ids(vector_orphan_ids) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| if file_orphan_ids: | ||
| session.execute(delete(UploadFile).where(UploadFile.id.in_(file_orphan_ids))) | ||
| return storage_keys |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
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):doc_id == UploadFile.idbyVector.create_multimodal, while every node idclean_document_indexesderives comes from segments, summaries or child chunks. They outlived the document permanently, kept consuming top-k slots, andRetrievalService.get_segment_attachment_infosdropped them silently because no row backed them any more.SegmentAttachmentBinding.attachment_idcarries no uniqueness constraint, so oneUploadFilecan 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 theUploadFiledelete before the binding delete.The fix
Both tasks now call one new function,
release_document_attachmentsinservices/knowledge/indexing/adapters/cleanup.py, which:document_id IN (...)), not through segments, so a failed release is picked up by a later run even after the segments are gone;UploadFilerow and blob are shared and go only once no binding anywhere remains;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;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 eachINclause.The previous revision of this PR added an
extra_node_idsparameter toclean_document_indexes; that is reverted, since the orphan decision now has to happen under the lock.Out of scope:
delete_segment_from_index_taskanddocument_indexing_update_taskrelease 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:
test_references_are_counted_while_the_attachment_lock_is_heldtest_attachment_bound_only_in_another_dataset_drops_this_datasets_vector_but_keeps_the_filetest_failed_vector_deletion_keeps_bindings_for_a_retrytest_each_attachment_is_locked_in_sorted_orderThe 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 onmain, +13)pytest api/tests/unit_tests— 21961 passed. The 33 failures are missing optional VDB plugin packages in my local environment plustest_zip64_extensible_data_is_not_part_of_central_directory; a clean checkout reproduces the same 33 with 21948 passed.ruff format --check/ruff check— cleanlint-imports— 59 contracts kept, 0 brokenpyrefly checkon the changed production files — 0 diagnosticspyrefly --config=tests/unit_tests/pyrefly.toml— 0 diagnostics on the new test file; identical counts before and after on the two modified onescheck_no_new_getattr.py/check_no_new_controller_sqlalchemy.py— both cleanapi/uv.lockunchangedNot verified
The lock and vector boundaries are mocked; I could not exercise real Redis contention or a real vector backend locally.
Checklist
make lint && make type-check(backend) andvp staged(frontend) to appease the lint gods🤖 Generated with Claude Code