Repository navigation
fix: prevent duplicate 'skills' and '.knowledgebase' folders caused by race conditions - #16568
Conversation
…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.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 Walkthrough📝 Walkthrough🚥 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: 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 liftNon-deterministic "keep first" can let concurrent dedup passes delete both surviving copies.
cls.query(...)(Line 283) delegates toCommonService.query→Model.query, which only appliesORDER BYwhenreverseis 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 keeprec1/deleterec2while process B keepsrec2/deleterec1— 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) andinit_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 ininit_skills_folderandinit_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 valueLogging mechanism differs from the service layer.
This file uses stdlib
log.Printf, whileinternal/service/file.go's newinitSkillsFolderusescommon.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 winDedup logic duplicated between service and DAO layers.
initSkillsFolderre-implements the query→dedup→create pattern already established ininternal/dao/file.go'sInitDatasetDocs, but via genericQuery/Delete/Insertcalls in the service layer instead of a cohesive DAO method. Consider adding a DAO-levelInitFolder/InitSkillsFoldermethod mirroringInitDatasetDocsso 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 winConsider 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, andinit_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
📒 Files selected for processing (3)
api/db/services/file_service.pyinternal/dao/file.gointernal/service/file.go
…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
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/db/services/file_service.py (1)
283-296: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winMake 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 inDB.atomic()and add an explicitorder_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
📒 Files selected for processing (1)
api/db/services/file_service.py
…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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…tID to Query - Python: use cls.model.select().where() instead of cls.query() in new_a_file_from_kb so .order_by() works (cls.query returns a list) - Go: pass tenantID to fileDAO.Query() which now requires 3 args
Signed-off-by: noob <[email protected]>
Summary
When performing move operations in the file management page, duplicate
skillsand.knowledgebasefolders 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_folderandinit_knowledgebase_docsevery 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 (viainvalidateQueries) while the move dialog'sAsyncTreeSelectalso loads folder data. Multiple concurrent requests simultaneously detect the folder as 'not existing' and create duplicates. TheFiletable'sname+parent_idhas 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):
api/db/services/file_service.pynew_a_file_from_kb,init_skills_folder,init_knowledgebase_docs— added dedup logicinternal/dao/file.goInitDatasetDocs,newAFileFromDataset— added dedup logicinternal/service/file.goinitSkillsFoldermethod (with dedup) +SkillsFolderNameconstant + call inListFiles