Skip to content

fix: preserve existing links when bulk linking files to knowledge bases - #16587

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
euvre:fix-file-link-overwrite
Jul 3, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
euvre:fix-file-link-overwrite

Conversation

@euvre

@euvre euvre commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

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-datasets endpoint called a _convert_files worker that first deleted all existing File2Document records 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_files now preserves existing links. For each file, it checks which knowledge bases are already linked and only creates new documents / File2Document entries 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

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.
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 3, 2026
@euvre euvre added the ci Continue Integration label Jul 3, 2026
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The _convert_files worker in file2document_api.py was modified to preserve existing file-to-document links rather than deleting and recreating them. It now checks currently linked knowledge base IDs per file and skips insertion for kb_ids already linked, while continuing early for missing file records.

Changes

File-to-Document Link Preservation

Layer / File(s) Summary
Preserve existing links in _convert_files
api/apps/restful_apis/file2document_api.py
Worker now collects currently linked document IDs and derived KB IDs per file, skips insertion for kb_ids already linked, and continues early when a file record is missing, instead of deleting and recreating links.

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

Poem

A rabbit hopped through code so neat,
No more deleting, just links complete,
Old bonds preserved, no need to sever,
KB and file, linked together forever,
Hop hop hooray, this fix is clever! 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main fix: preserving existing links during bulk linking to knowledge bases.
Description check ✅ Passed The description includes the required summary and enough background, root cause, and fix detail for reviewers.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

@coderabbitai coderabbitai Bot 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.

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 lift

Guard the file/kb link path with an atomic idempotency check. existing_kb_ids is read before any insert, so two concurrent requests can both create a new Document and File2Document row for the same file/kb pair. A unique constraint on (file_id, document_id) does not prevent this because each request generates a different document_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 value

Optional: avoid per-document N+1 lookups.

DocumentService.get_by_id is 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 to kb_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 win

Add logging to the new preservation flow.

The _convert_files worker now runs new link-preservation logic (skipping already-linked KBs, inserting new docs) with no logging, unlike the well-instrumented convert() 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9182296 and 687e138.

📒 Files selected for processing (1)
  • api/apps/restful_apis/file2document_api.py

@codecov

codecov Bot commented Jul 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (9182296) to head (687e138).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants