Skip to content

fix(api): guard document rename when linked file row is missing - #15536

Merged
yingfeng merged 1 commit into
infiniflow:mainfrom
bohdansolovie:fix/document-rename-orphan-file2document
Jun 3, 2026
Merged

yingfeng merged 1 commit into
infiniflow:mainfrom
bohdansolovie:fix/document-rename-orphan-file2document

Conversation

@bohdansolovie

@bohdansolovie bohdansolovie commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #15534 — update_document_name_only() crashes with AttributeError when File2Document exists but the linked File row was deleted.

update_document_name_only() in document_api_service.py called FileService.get_by_id() when a File2Document row existed, then accessed file.id without checking the lookup result. An orphan File2Document link (file deleted, mapping left behind) caused document rename via PATCH /api/v1/datasets/{dataset_id}/documents/{document_id} to return HTTP 500.

This PR mirrors guards used in file2document_api.py and file_api_service.py: skip the optional file rename when the file is missing, and still update the document record and search index.

Changes

  • api/apps/services/document_api_service.py — check e and file before FileService.update_by_id
  • test/unit_test/api/apps/services/test_update_document_name_only.py — regression tests (orphan link + happy path)

Test plan

  • pytest test/unit_test/api/apps/services/test_update_document_name_only.py -v
  • Manual: PATCH document name when File2Document points to a non-existent file_id → 200, document/index renamed, no 500

update_document_name_only() accessed file.id without checking
FileService.get_by_id() when File2Document pointed at a deleted file.
Skip the optional file rename and still update the document index.
Fixes infiniflow#15534
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 2, 2026
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR fixes a crash in document rename when a File2Document row points to a deleted file. The service method now guards the file update with a null-check, and comprehensive regression tests validate both the skip-when-missing and update-when-present code paths.

Changes

Document Rename Orphan Link Guard

Layer / File(s) Summary
Conditional file update guard
api/apps/services/document_api_service.py
In update_document_name_only, file rename is now conditional: FileService.update_by_id is only called if both the preceding get_by_id lookup succeeds (truthy e) and the file object is present, avoiding AttributeError when the linked file record was deleted.
Test module setup and stubs
test/unit_test/api/apps/services/test_update_document_name_only.py
Test infrastructure imports dependencies, registers @pytest.mark.p2, and provides _stub() and _load_update_document_name_only_module() helpers to mock all dependent services and dynamically load the target module in isolation.
Regression test cases
test/unit_test/api/apps/services/test_update_document_name_only.py
Two test cases: test_update_document_name_only_skips_missing_linked_file asserts the function skips file update when file lookup returns (False, None); test_update_document_name_only_updates_linked_file_when_present asserts file update is called with the correct id and payload when file lookup returns a linked file.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested labels

🧪 test, 🐖api

Suggested reviewers

  • JinHai-CN
  • asiroliu
  • yongtenglei

Poem

🐰 A file once linked, now lost to time,
No crash today—just logic prime!
Guard the guard, test the way,
Orphan links fade away! 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a guard to prevent crashes when a linked file row is missing during document rename.
Description check ✅ Passed The description follows the template with clear sections including problem statement, type of change, specific changes, and test plan.
Linked Issues check ✅ Passed The PR fully addresses issue #15534: it prevents AttributeError by checking e and file before FileService.update_by_id, allows document rename to succeed despite missing linked file, skips optional file rename when file is absent, and includes regression tests covering both the orphan-link scenario and normal path.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the issue: modifications to document_api_service.py for the guard condition and corresponding regression tests in test_update_document_name_only.py.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

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

🧹 Nitpick comments (1)
api/apps/services/document_api_service.py (1)

41-43: 💤 Low value

Guard correctly prevents the orphan-link crash; consider logging the skip.

The if e and file: guard fixes the AttributeError as intended. Since this introduces a new silent branch (skipping the file rename when the File2Document mapping points to a deleted File), a log line here would aid future debugging of orphan links. logging is already imported.

♻️ Optional: log when the linked file is missing
         e, file = FileService.get_by_id(informs[0].file_id)
         if e and file:
             FileService.update_by_id(file.id, {"name": req_doc_name})
+        else:
+            logging.warning(
+                "Skipping file rename for document %s: linked file %s not found (orphan File2Document link).",
+                document_id,
+                informs[0].file_id,
+            )

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/services/document_api_service.py` around lines 41 - 43, The guard
added around FileService.get_by_id (checking e and file) prevents an
AttributeError but silently skips renaming when the File2Document link is
orphaned; add a logging call to record this path. Inside the branch where you
currently do nothing (the else of "if e and file:"), emit a log (using the
existing logging import) that includes the document id or informs[0].file_id and
req_doc_name to indicate the missing File and that the rename was skipped; keep
the successful path unchanged where FileService.update_by_id(file.id, {"name":
req_doc_name}) is called.
🤖 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.

Nitpick comments:
In `@api/apps/services/document_api_service.py`:
- Around line 41-43: The guard added around FileService.get_by_id (checking e
and file) prevents an AttributeError but silently skips renaming when the
File2Document link is orphaned; add a logging call to record this path. Inside
the branch where you currently do nothing (the else of "if e and file:"), emit a
log (using the existing logging import) that includes the document id or
informs[0].file_id and req_doc_name to indicate the missing File and that the
rename was skipped; keep the successful path unchanged where
FileService.update_by_id(file.id, {"name": req_doc_name}) is called.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8f8ac2e2-7997-4786-b663-7311f59a1881

📥 Commits

Reviewing files that changed from the base of the PR and between 9799f33 and b566e57.

📒 Files selected for processing (2)
  • api/apps/services/document_api_service.py
  • test/unit_test/api/apps/services/test_update_document_name_only.py

@bohdansolovie

Copy link
Copy Markdown
Contributor Author

@yingfeng
Could you please review?

@bohdansolovie

Copy link
Copy Markdown
Contributor Author

@wangq8 , @Haruko386 , @JinHai-CN @yingfeng @xugangqiang
Please review this PR

@xugangqiang xugangqiang added the ci Continue Integration label Jun 3, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 3, 2026 06:51
@xugangqiang
xugangqiang marked this pull request as ready for review June 3, 2026 06:51
@codecov

codecov Bot commented Jun 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (9799f33) to head (b566e57).
⚠️ Report is 10 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15536      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ View full report in Codecov by Sentry.
📢 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.

@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

@yingfeng
yingfeng merged commit ae316b3 into infiniflow:main Jun 3, 2026
1 check passed
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:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: PATCH document rename crashes when File2Document points to a deleted file

3 participants