Repository navigation
fix: preserve existing links when bulk linking files to knowledge bases - #16587
Conversation
The link-to-datasets worker used to delete all existing file-to-document links before inserting the new ones, which caused multi-select "link to knowledge base" to overwrite previous links. Change the worker to only create documents for knowledge bases that are not already linked to the file, leaving existing links untouched.
📝 WalkthroughWalkthroughThe ChangesFile-to-Document Link Preservation
Estimated code review effort: 2 (Simple) | ~10 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/apps/restful_apis/file2document_api.py (1)
48-78: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftGuard the file/kb link path with an atomic idempotency check.
existing_kb_idsis read before any insert, so two concurrent requests can both create a newDocumentandFile2Documentrow for the same file/kb pair. A unique constraint on(file_id, document_id)does not prevent this because each request generates a differentdocument_id; serialize this section or add a DB-level uniqueness rule that covers the file/kb mapping.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/file2document_api.py` around lines 48 - 78, The file-to-document linking flow in File2DocumentService/File2DocumentService.insert is vulnerable to duplicate document creation because existing_kb_ids is checked before any writes, so concurrent requests can both pass the check and create separate Document and File2Document records for the same file/kb pair. Fix this by making the link path atomic in file2document_api.py, either by serializing the read-and-insert sequence or by enforcing a database uniqueness constraint on the file/kb mapping that is checked before DocumentService.insert and File2DocumentService.insert.
🧹 Nitpick comments (2)
api/apps/restful_apis/file2document_api.py (2)
50-53: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueOptional: avoid per-document N+1 lookups.
DocumentService.get_by_idis called once per existing link inside the loop. For files linked to many KBs this is an N+1 pattern; a single batched fetch of the documents by id (then mapping tokb_id) would reduce round-trips.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/file2document_api.py` around lines 50 - 53, The loop in file2document_api.py is doing an N+1 lookup by calling DocumentService.get_by_id for each doc_id in existing_links; replace this per-item fetch with a batched document retrieval and then build the existing_kb_ids set from the returned documents’ kb_id values. Keep the logic in the same flow where existing_links is processed, but use a bulk fetch helper or equivalent in DocumentService so the code only makes one round-trip for all doc_ids.
36-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd logging to the new preservation flow.
The
_convert_filesworker now runs new link-preservation logic (skipping already-linked KBs, inserting new docs) with no logging, unlike the well-instrumentedconvert()caller. Add structured logs for the skip/insert decisions and per-file outcome to aid debugging, especially since this runs in a background executor where failures are otherwise silent.As per coding guidelines: "Add logging for new flows".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/file2document_api.py` around lines 36 - 78, The new link-preservation flow in `_convert_files` is currently silent, so add structured logging around the key decisions and outcomes. Use the existing `logger` style from `convert()` to log when a file is processed, when `existing_kb_ids` causes a KB to be skipped, when a new `DocumentService.insert` and `File2DocumentService.insert` succeed, and when a file ends with no new links created. Keep the logs attached to the `_convert_files` worker path so background-executor failures and skip decisions are visible during debugging.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/apps/restful_apis/file2document_api.py`:
- Line 43: The loop variable in the file-to-document flow is named id, which
shadows the Python builtin and will fail ruff A001. Rename the loop variable in
the relevant file-to-document function and update every reference in that scope,
especially in the logic that processes each file id and any later uses in the
same function, so ruff check passes cleanly.
---
Outside diff comments:
In `@api/apps/restful_apis/file2document_api.py`:
- Around line 48-78: The file-to-document linking flow in
File2DocumentService/File2DocumentService.insert is vulnerable to duplicate
document creation because existing_kb_ids is checked before any writes, so
concurrent requests can both pass the check and create separate Document and
File2Document records for the same file/kb pair. Fix this by making the link
path atomic in file2document_api.py, either by serializing the read-and-insert
sequence or by enforcing a database uniqueness constraint on the file/kb mapping
that is checked before DocumentService.insert and File2DocumentService.insert.
---
Nitpick comments:
In `@api/apps/restful_apis/file2document_api.py`:
- Around line 50-53: The loop in file2document_api.py is doing an N+1 lookup by
calling DocumentService.get_by_id for each doc_id in existing_links; replace
this per-item fetch with a batched document retrieval and then build the
existing_kb_ids set from the returned documents’ kb_id values. Keep the logic in
the same flow where existing_links is processed, but use a bulk fetch helper or
equivalent in DocumentService so the code only makes one round-trip for all
doc_ids.
- Around line 36-78: The new link-preservation flow in `_convert_files` is
currently silent, so add structured logging around the key decisions and
outcomes. Use the existing `logger` style from `convert()` to log when a file is
processed, when `existing_kb_ids` causes a KB to be skipped, when a new
`DocumentService.insert` and `File2DocumentService.insert` succeed, and when a
file ends with no new links created. Keep the logs attached to the
`_convert_files` worker path so background-executor failures and skip decisions
are visible during debugging.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c6cc8814-867a-4003-8ee6-e37ec0a5e1e8
📒 Files selected for processing (1)
api/apps/restful_apis/file2document_api.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16587 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
This PR fixes a bug in the file manager where selecting multiple files and choosing "Link to knowledge base" would overwrite any knowledge-base links that those files already had.
Root cause: The
POST /api/v1/files/link-to-datasetsendpoint called a_convert_filesworker that first deleted all existingFile2Documentrecords for each file and then recreated documents only for the newly selected knowledge bases. As a result, previously linked knowledge bases were silently removed.Fix:
_convert_filesnow preserves existing links. For each file, it checks which knowledge bases are already linked and only creates new documents /File2Documententries for the knowledge bases that are not already present. Existing links remain untouched, so multi-select "link to knowledge base" correctly appends to the current set of links instead of replacing them.Affected file:
api/apps/restful_apis/file2document_api.py