Skip to content

fix: prevent duplicate 'skills' and '.knowledgebase' folders caused by race conditions - #16568

Merged
wangq8 merged 14 commits into
infiniflow:mainfrom
euvre:fix/duplicate-skills-knowledgebase-folders
Jul 3, 2026
Merged

wangq8 merged 14 commits into
infiniflow:mainfrom
euvre:fix/duplicate-skills-knowledgebase-folders

Conversation

@euvre

@euvre euvre commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Summary

When performing move operations in the file management page, duplicate skills and .knowledgebase folders appear. This is caused by a TOCTOU (Time of Check to Time of Use) race condition.

Root cause: The file management page calls init_skills_folder and init_knowledgebase_docs every time the root folder is loaded. These functions used a non-atomic 'check-then-create' pattern. After a move operation, the frontend concurrently refreshes the file list (via invalidateQueries) while the move dialog's AsyncTreeSelect also loads folder data. Multiple concurrent requests simultaneously detect the folder as 'not existing' and create duplicates. The File table's name + parent_id has no unique constraint, so the database cannot prevent this.

Fix: Added self-healing deduplication to all folder initialization functions. Each function now queries all existing entries matching name + parent_id, removes any duplicates (keeping only the first), and returns early if one already exists.

Files changed (3 files, +106/-16):

File Changes
api/db/services/file_service.py new_a_file_from_kb, init_skills_folder, init_knowledgebase_docs — added dedup logic
internal/dao/file.go InitDatasetDocs, newAFileFromDataset — added dedup logic
internal/service/file.go New initSkillsFolder method (with dedup) + SkillsFolderName constant + call in ListFiles

…y race conditions

When the file management page loads the root folder, it calls init_skills_folder
and init_knowledgebase_docs on every request. These functions used a non-atomic
'check-then-create' pattern (TOCTOU). After a move operation, the frontend
concurrently refreshes the file list while the move dialog's tree select also
loads folder data, causing multiple requests to simultaneously detect the folder
as 'not existing' and create duplicates.

The fix adds self-healing deduplication to all folder initialization functions:
- Python: new_a_file_from_kb, init_skills_folder, init_knowledgebase_docs
- Go DAO: InitDatasetDocs, newAFileFromDataset
- Go Service: new initSkillsFolder method + SkillsFolderName constant

Each function now queries all existing entries, removes duplicates keeping only
the first, and returns early if one already exists.
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 2, 2026
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough
📝 Walkthrough
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: preventing duplicate skills and .knowledgebase folders from race conditions.
Description check ✅ Passed The description matches the template with a clear Summary, root cause, fix, and supporting file-impact details.
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.

@euvre euvre added the ci Continue Integration label Jul 2, 2026

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/db/services/file_service.py (1)

268-305: 🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy lift

Non-deterministic "keep first" can let concurrent dedup passes delete both surviving copies.

cls.query(...) (Line 283) delegates to CommonService.query → Model.query, which only applies ORDER BY when reverse is explicitly passed; here it isn't, so row order is unspecified. If two concurrent requests each run this dedup path while duplicates still exist and the DB returns rows in a different order to each caller, process A may keep rec1/delete rec2 while process B keeps rec2/delete rec1 — both rows end up deleted and the folder vanishes. This reintroduces the exact TOCTOU-style bug the PR is meant to close.

The same unordered-list pattern is repeated in init_skills_folder (Line 316-318) and init_knowledgebase_docs (Line 350-352) — fixing the ordering here should be applied consistently to all three.

🔒 Proposed fix: enforce deterministic ordering
-        existing = list(cls.query(tenant_id=tenant_id, parent_id=parent_id, name=name))
+        existing = list(cls.query(tenant_id=tenant_id, parent_id=parent_id, name=name, reverse=False, order_by="create_time"))

Apply the analogous change to the raw select() calls in init_skills_folder and init_knowledgebase_docs:

-        existing = list(cls.model.select().where(
-            (cls.model.name == SKILLS_FOLDER_NAME) & (cls.model.parent_id == root_id)
-        ))
+        existing = list(cls.model.select().where(
+            (cls.model.name == SKILLS_FOLDER_NAME) & (cls.model.parent_id == root_id)
+        ).order_by(cls.model.create_time.asc(), cls.model.id.asc()))
🤖 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/db/services/file_service.py` around lines 268 - 305, `new_a_file_from_kb`
currently keeps an arbitrary “first” row because `cls.query(...)` has no
deterministic ordering, which can cause concurrent dedup passes to delete all
copies. Update the lookup to use a stable sort key before choosing the survivor,
and apply the same fix in `init_skills_folder` and `init_knowledgebase_docs`
where the same unordered `select()`/query pattern is used. Make sure the
duplicate cleanup always keeps the same record across callers by referencing a
consistent unique field such as `id` or created timestamp.
🧹 Nitpick comments (3)
internal/dao/file.go (1)

20-20: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Logging mechanism differs from the service layer.

This file uses stdlib log.Printf, while internal/service/file.go's new initSkillsFolder uses common.Logger.Warn(...) for the analogous dedup warning. Consider standardizing on one logging facility across both layers for consistent log format/routing.

🤖 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 `@internal/dao/file.go` at line 20, The dedup warning in the file DAO currently
uses stdlib logging, while the analogous service-layer path uses
common.Logger.Warn for consistency. Update the warning in the relevant file
handling logic around the dedup check in file.go to use the same logging
facility and style as initSkillsFolder in internal/service/file.go, so both
layers emit consistent routed/formatted warnings.
internal/service/file.go (1)

166-198: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Dedup logic duplicated between service and DAO layers.

initSkillsFolder re-implements the query→dedup→create pattern already established in internal/dao/file.go's InitDatasetDocs, but via generic Query/Delete/Insert calls in the service layer instead of a cohesive DAO method. Consider adding a DAO-level InitFolder/InitSkillsFolder method mirroring InitDatasetDocs so the dedup algorithm lives in one place.

🤖 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 `@internal/service/file.go` around lines 166 - 198, The dedup-and-create flow
in initSkillsFolder is duplicated in the service layer instead of being owned by
the DAO. Move this logic into internal/dao/file.go by adding a dedicated
InitFolder/InitSkillsFolder method, similar to InitDatasetDocs, and have
FileService.initSkillsFolder call that DAO method instead of doing
Query/Delete/Insert directly. Keep the dedup behavior and folder creation logic
centralized behind the DAO interface so all callers use the same implementation.
api/db/services/file_service.py (1)

282-292: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider extracting the repeated dedup logic into a shared helper.

The "select existing → log warning if len>1 → delete all but first" pattern is duplicated across new_a_file_from_kb, init_skills_folder, and init_knowledgebase_docs. A small shared helper (e.g. cls._dedupe_keep_first(existing, label, parent_id)) would reduce duplication and centralize the ordering fix above so it isn't re-litigated per call site.

Also applies to: 310-327, 344-360

🤖 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/db/services/file_service.py` around lines 282 - 292, The
duplicate-cleanup flow in file creation is repeated in new_a_file_from_kb,
init_skills_folder, and init_knowledgebase_docs, so extract it into a shared
helper on FileService/cls such as a keep-first dedupe method. Move the “query
existing → warn if more than one → delete duplicates → return first” logic into
that helper, and have each call site use it so the ordering fix and duplicate
handling stay centralized and consistent.
🤖 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 `@internal/dao/file.go`:
- Around line 387-389: The duplicate cleanup in file.go ignores delete failures,
so handle the result of DB.Unscoped().Where(...).Delete(&entity.File{}) instead
of discarding it. Update the duplicate-removal logic in the loop over
existing[1:] to check the returned error (and any affected rows if needed), log
or propagate failures, and apply the same fix in the other duplicate cleanup
block referenced by the comment.
- Around line 383-390: The duplicate-folder cleanup in the root/KB dedup logic
is hard-deleting rows without preserving related data. In the dedup blocks that
iterate over existing duplicates and call
DB.Unscoped().Where(...).Delete(&entity.File{}), first move any child File
records with parent_id pointing at dup.ID to the kept folder ID, and also
transfer any file2document associations for the KB-folder case before deleting
dup. Keep the existing folder selection logic intact, but ensure all references
are reassigned in these cleanup paths so no children are orphaned.

In `@internal/service/file.go`:
- Around line 172-185: The duplicate-skills cleanup in initSkillsFolder
currently hard-deletes extra folders via s.fileDAO.Delete(dup.ID), which can
orphan any children that were added under a duplicate folder before dedup runs.
Update the cleanup logic to mirror the safer approach used in the DAO layer:
before deleting each duplicate, move or reparent its children to the surviving
skills folder (or another valid parent) and then delete the duplicate only after
its descendants are preserved. Use initSkillsFolder and the fileDAO.Delete path
as the key spots to adjust.
- Around line 180-182: The duplicate cleanup loop in file service logic is
ignoring failures from fileDAO.Delete, which can leave stale records behind
without any visibility. Update the duplicate-removal path around the
existing[1:] iteration to handle the returned error from fileDAO.Delete, and
make sure any delete failure is surfaced through logging or propagated so the
caller can detect it. Use the file service method containing the existing and
dup handling to locate the fix.

---

Outside diff comments:
In `@api/db/services/file_service.py`:
- Around line 268-305: `new_a_file_from_kb` currently keeps an arbitrary “first”
row because `cls.query(...)` has no deterministic ordering, which can cause
concurrent dedup passes to delete all copies. Update the lookup to use a stable
sort key before choosing the survivor, and apply the same fix in
`init_skills_folder` and `init_knowledgebase_docs` where the same unordered
`select()`/query pattern is used. Make sure the duplicate cleanup always keeps
the same record across callers by referencing a consistent unique field such as
`id` or created timestamp.

---

Nitpick comments:
In `@api/db/services/file_service.py`:
- Around line 282-292: The duplicate-cleanup flow in file creation is repeated
in new_a_file_from_kb, init_skills_folder, and init_knowledgebase_docs, so
extract it into a shared helper on FileService/cls such as a keep-first dedupe
method. Move the “query existing → warn if more than one → delete duplicates →
return first” logic into that helper, and have each call site use it so the
ordering fix and duplicate handling stay centralized and consistent.

In `@internal/dao/file.go`:
- Line 20: The dedup warning in the file DAO currently uses stdlib logging,
while the analogous service-layer path uses common.Logger.Warn for consistency.
Update the warning in the relevant file handling logic around the dedup check in
file.go to use the same logging facility and style as initSkillsFolder in
internal/service/file.go, so both layers emit consistent routed/formatted
warnings.

In `@internal/service/file.go`:
- Around line 166-198: The dedup-and-create flow in initSkillsFolder is
duplicated in the service layer instead of being owned by the DAO. Move this
logic into internal/dao/file.go by adding a dedicated
InitFolder/InitSkillsFolder method, similar to InitDatasetDocs, and have
FileService.initSkillsFolder call that DAO method instead of doing
Query/Delete/Insert directly. Keep the dedup behavior and folder creation logic
centralized behind the DAO interface so all callers use the same implementation.
🪄 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: a1a395f8-506a-4b45-86c3-d940014459c7

📥 Commits

Reviewing files that changed from the base of the PR and between c8cf0c9 and 878434e.

📒 Files selected for processing (3)
  • api/db/services/file_service.py
  • internal/dao/file.go
  • internal/service/file.go

Comment thread internal/dao/file.go Resolved
Comment thread internal/dao/file.go Resolved
Comment thread internal/service/file.go Resolved
Comment thread internal/service/file.go Resolved
euvre added 2 commits July 2, 2026 17:02
…elete errors

Address CodeRabbit review feedback on PR infiniflow#16568:
- Reparent child records to the kept folder before hard-deleting duplicates
  to prevent orphaned files/folders that may have accumulated under a
  duplicate folder between its creation and the next dedup pass
- Handle delete errors instead of silently ignoring them; log failures
  so stale duplicates can be diagnosed

Changes:
- Go DAO: add reparentAndDeleteFolder helper, use it in InitDatasetDocs
  and newAFileFromDataset
- Go Service: reparent children + handle errors in initSkillsFolder
- Python: reparent children in new_a_file_from_kb, init_skills_folder,
  and init_knowledgebase_docs

@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/db/services/file_service.py (1)

283-296: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make duplicate cleanup deterministic and atomic. existing[0] is chosen without a stable order, so concurrent runs can pick different keepers. Wrap the reparent/delete sequence in DB.atomic() and add an explicit order_by(...) in all three dedupe paths (api/db/services/file_service.py:283-296, 320-332, 356-368).

🤖 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/db/services/file_service.py` around lines 283 - 296, Make the duplicate
cleanup in FileService deterministic and atomic: the current dedupe logic in the
query-based cleanup paths chooses existing[0] without a stable ordering, so
concurrent runs can keep different records. Update the duplicate handling in the
FileService dedupe blocks to use an explicit order_by(...) before selecting the
keeper, and wrap the reparent/delete sequence in DB.atomic() so the cleanup is
performed as one transaction. Apply the same fix consistently across all three
duplicate cleanup paths in FileService.
🤖 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/db/services/file_service.py`:
- Line 320: The dedupe query in the file initialization path is missing tenant
scoping, so it only filters by name and parent_id. Update the existing lookup in
the file service initialization logic (the branch that uses SKILLS_FOLDER_NAME
and root_id, plus the other matching cleanup path) to include tenant_id
alongside parent_id and name, using the same tenant value passed into the
method. This keeps the behavior aligned with the File model contract and ensures
the cleanup/reparenting logic stays isolated to the requested tenant.

---

Outside diff comments:
In `@api/db/services/file_service.py`:
- Around line 283-296: Make the duplicate cleanup in FileService deterministic
and atomic: the current dedupe logic in the query-based cleanup paths chooses
existing[0] without a stable ordering, so concurrent runs can keep different
records. Update the duplicate handling in the FileService dedupe blocks to use
an explicit order_by(...) before selecting the keeper, and wrap the
reparent/delete sequence in DB.atomic() so the cleanup is performed as one
transaction. Apply the same fix consistently across all three duplicate cleanup
paths in FileService.
🪄 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: 067f1b54-5553-4f62-90c5-906bb8cc70f4

📥 Commits

Reviewing files that changed from the base of the PR and between 96ee259 and 379eef2.

📒 Files selected for processing (1)
  • api/db/services/file_service.py

Comment thread api/db/services/file_service.py Resolved
…tomic transactions

Address CodeRabbit review round 2 feedback on PR infiniflow#16568:
- Add explicit ORDER BY create_time ASC in all dedup queries so concurrent
  runs deterministically pick the same keeper (oldest record)
- Add tenant_id scoping to init_skills_folder and init_knowledgebase_docs
  queries to ensure dedup isolation per tenant
- Wrap reparent+delete sequence in DB.atomic() (Python) for transactional
  consistency
@codecov

codecov Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (c8cf0c9) to head (3670dad).
⚠️ Report is 24 commits behind head on main.

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

@wangq8
wangq8 merged commit 9182296 into infiniflow:main Jul 3, 2026
3 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants