Skip to content

fix(api): guard dataset delete when File2Document row is missing - #15533

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
bohdansolovie:fix/delete-dataset-missing-file2document
Jun 11, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
bohdansolovie:fix/delete-dataset-missing-file2document

Conversation

@bohdansolovie

Copy link
Copy Markdown
Contributor

Summary

Fixes #15532 — delete_datasets() crashes with IndexError when a document has no File2Document row.
delete_datasets() in dataset_api_service.py called File2DocumentService.get_by_document_id() and immediately accessed f2d[0].file_id without checking whether the lookup returned any rows. Documents created via API ingestion or connector sync may exist without a linked file record, causing dataset deletion to abort with HTTP 500.
This PR mirrors the existing guard already used in file_service.py and document_api_service.py.

Test plan

  • pytest test/unit_test/api/apps/services/test_delete_datasets.py -v
  • Empty f2d lookup completes without crash
  • Linked file still deleted when File2Document row exists
  • Manual: delete dataset with API-created documents (no file link) succeeds

delete_datasets() accessed f2d[0].file_id without checking for an empty
lookup result, crashing on API/connector documents with no file link.
Mirror the existing if f2d guard from file_service.py.
Fixes infiniflow#15532
@dosubot dosubot Bot added size:S This PR changes 10-29 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 27f2799e-9483-4ca4-bc33-8c99aef26d7d

📥 Commits

Reviewing files that changed from the base of the PR and between d0720da and 2d042af.

📒 Files selected for processing (1)
  • api/apps/services/dataset_api_service.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/services/dataset_api_service.py

📝 Walkthrough

Walkthrough

The PR guards File deletion inside delete_datasets() by checking File2DocumentService.get_by_document_id(...) before using its results, and adds unit tests covering both the no-mapping and mapping-present deletion paths.

Changes

Dataset deletion robustness

Layer / File(s) Summary
File deletion guard in delete_datasets
api/apps/services/dataset_api_service.py
The delete_datasets() function adds a conditional check before accessing f2d[0].file_id; file deletion only proceeds if File2DocumentService.get_by_document_id(doc.id) returns a non-empty result.
Test infrastructure and coverage for delete_datasets
test/unit_test/api/apps/services/test_delete_datasets.py
New test module with helper utilities (_stub, _load_delete_datasets_module) and two async tests: one confirming deletion succeeds when no File2Document row exists, the other verifying the file deletion path is exercised when a File2Document row is present.

Sequence Diagram(s)

sequenceDiagram
  participant DeleteDatasets
  participant File2DocumentService
  participant FileService
  participant DocumentService
  DeleteDatasets->>File2DocumentService: get_by_document_id(doc.id)
  File2DocumentService-->>DeleteDatasets: [] or [File2Document]
  alt mapping exists
    DeleteDatasets->>FileService: filter_delete(... File.id == f2d[0].file_id)
  else no mapping
    DeleteDatasets->>DeleteDatasets: log warning and skip file deletion
  end
  DeleteDatasets->>DocumentService: delete_by_document_id(doc.id)
  DeleteDatasets-->>Client: return (ok, result)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

size:XS

Poem

"I nibbled a bug, then hopped in delight,
No IndexError now when files take flight.
Guards in place, tests snug and neat,
Deletions hum along with a rhythmic beat. 🐰✨"

🚥 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 clearly and specifically summarizes the main fix: adding a guard for missing File2Document rows during dataset deletion.
Description check ✅ Passed The description addresses the PR template by explaining the problem (IndexError crash), the fix (guard conditional), and provides a test plan, though the Type of change checkbox is not marked.
Linked Issues check ✅ Passed The code changes directly address all requirements from #15532: preventing IndexError when File2Document row is missing, skipping file deletion when f2d is empty, and aligning with existing guard patterns.
Out of Scope Changes check ✅ Passed All changes are narrowly focused on the core issue: conditional guard logic in delete_datasets and comprehensive unit tests for the fixed behavior.

✏️ 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/dataset_api_service.py (1)

147-154: ⚡ Quick win

Consider adding logging when skipping file deletion.

The guard correctly prevents the IndexError, but per coding guidelines for api/**/*.py files, new conditional flows should include logging. When f2d is empty and file deletion is skipped, logging this event would help with debugging and observability.

📋 Suggested logging addition
 f2d = File2DocumentService.get_by_document_id(doc.id)
 if f2d:
     FileService.filter_delete(
         [
             File.source_type == FileSource.KNOWLEDGEBASE,
             File.id == f2d[0].file_id,
         ]
     )
+else:
+    logging.debug("Skipping linked file deletion for document %s (no File2Document mapping)", doc.id)
 File2DocumentService.delete_by_document_id(doc.id)

As per coding guidelines: "Add logging for new flows" for api/**/*.py files.

🤖 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/dataset_api_service.py` around lines 147 - 154, The branch
that skips file deletion when f2d is empty lacks observability; update the
conditional around
FileService.filter_delete/File2DocumentService.delete_by_document_id to log a
concise debug/info message when f2d is falsy (e.g., "No File2Document found for
document {doc.id}, skipping file delete") so callers can trace this flow; use
the existing logger in this module (or create one named logger) and include
doc.id and the FileSource.KNOWLEDGEBASE context in the log entry for clarity.
🤖 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/dataset_api_service.py`:
- Around line 147-154: The branch that skips file deletion when f2d is empty
lacks observability; update the conditional around
FileService.filter_delete/File2DocumentService.delete_by_document_id to log a
concise debug/info message when f2d is falsy (e.g., "No File2Document found for
document {doc.id}, skipping file delete") so callers can trace this flow; use
the existing logger in this module (or create one named logger) and include
doc.id and the FileSource.KNOWLEDGEBASE context in the log entry for clarity.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d6f16e98-f45a-4c45-ae64-37f6436a92d1

📥 Commits

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

📒 Files selected for processing (2)
  • api/apps/services/dataset_api_service.py
  • test/unit_test/api/apps/services/test_delete_datasets.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

…lete

Address review feedback: document cleanup proceeds without linked file
delete, with a warning for observability when the mapping row is absent.
@xugangqiang xugangqiang added the ci Continue Integration label Jun 4, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 4, 2026 03:18
@xugangqiang
xugangqiang marked this pull request as ready for review June 4, 2026 03:18
@codecov

codecov Bot commented Jun 4, 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 (2d042af).
⚠️ Report is 26 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15533      +/-   ##
==========================================
- 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 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.

@wangq8
wangq8 merged commit 47fb462 into infiniflow:main Jun 11, 2026
2 checks passed
dripsmvcp added a commit to dripsmvcp/ragflow that referenced this pull request Jun 12, 2026
…nfiniflow#15715)

Resolve conflicts: drop the duplicate File2DocumentDAO.Create (main added an identical method in infiniflow#15533) and union fakeDocumentService's upload* and metadata* test fields. Build, vet, gofmt and the service/handler/dao/router tests (incl. the upload-linkage regression tests) pass.
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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: delete_datasets() crashes with IndexError when document has no File2Document row

3 participants