Repository navigation
Let DELETE /datasets to a dedicated thread to avoid blocking other APIs - #17796
Conversation
📝 WalkthroughWalkthroughDataset deletion cleanup now runs in a worker thread. The asynchronous ChangesDataset deletion execution
Estimated code review effort: 2 (Simple) | ~10 minutes Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 3
🧹 Nitpick comments (1)
api/apps/services/dataset_api_service.py (1)
147-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse explicit optional types for
ids.
ids: list = Nonehides the element type and violates Ruff RUF013. Uselist[str] | Nonein both signatures.Proposed fix
-def _delete_datasets_sync(tenant_id: str, ids: list = None, delete_all: bool = False): +def _delete_datasets_sync(tenant_id: str, ids: list[str] | None = None, delete_all: bool = False): ... -async def delete_datasets(tenant_id: str, ids: list = None, delete_all: bool = False): +async def delete_datasets(tenant_id: str, ids: list[str] | None = None, delete_all: bool = False):Also applies to: 224-224
🤖 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` at line 147, Update both _delete_datasets_sync signatures to annotate ids as list[str] | None instead of the untyped list defaulting to None, preserving the existing default and behavior.Sources: Coding guidelines, Linters/SAST tools
🤖 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/services/dataset_api_service.py`:
- Around line 224-225: Update delete_datasets to log structured dispatch,
completion, and failure events around the _delete_datasets_sync worker-thread
call, including elapsed duration and deletion result counts. Use the module’s
existing logger and avoid raw tenant_id or dataset identifiers unless permitted
by the logging policy; preserve the coroutine’s current return and exception
behavior.
- Around line 224-225: Update delete_datasets and _delete_datasets_sync to
prevent concurrent deletion requests for the same dataset from racing. Add
per-dataset serialization around the asyncio.to_thread call, or make the
deletion and linked cleanup operations safely idempotent across retries, while
preserving concurrent deletion for different datasets.
- Around line 224-225: Update delete_datasets to submit _delete_datasets_sync to
a service-owned bounded executor or queue instead of asyncio.to_thread’s default
executor. Reuse the existing executor infrastructure if available, and preserve
the current arguments and async result behavior while isolating long-running
dataset deletions from unrelated offloaded work.
---
Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Line 147: Update both _delete_datasets_sync signatures to annotate ids as
list[str] | None instead of the untyped list defaulting to None, preserving the
existing default and behavior.
🪄 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 Plus
Run ID: 4fb50f9b-6c78-4ff2-90e3-c1e901c5e1e7
📒 Files selected for processing (1)
api/apps/services/dataset_api_service.py
| async def delete_datasets(tenant_id: str, ids: list = None, delete_all: bool = False): | ||
| return await asyncio.to_thread(_delete_datasets_sync, tenant_id, ids, delete_all) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Add logging for the new worker-thread flow.
The new coroutine dispatches deletion work without logging dispatch, completion, or failure. Add structured logs with duration and result counts. Avoid raw tenant or dataset identifiers unless logging policy permits.
As per coding guidelines, **/*.py: Add logging for new flows.
🧰 Tools
🪛 Ruff (0.16.0)
[warning] 224-224: PEP 484 prohibits implicit Optional
Convert to T | None
(RUF013)
🤖 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 224 - 225, Update
delete_datasets to log structured dispatch, completion, and failure events
around the _delete_datasets_sync worker-thread call, including elapsed duration
and deletion result counts. Use the module’s existing logger and avoid raw
tenant_id or dataset identifiers unless permitted by the logging policy;
preserve the coroutine’s current return and exception behavior.
Source: Coding guidelines
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 8 --glob '*.py' \
'delete_datasets|_delete_datasets_sync|db\.atomic|atomic\(|threading\.Lock|asyncio\.Lock|delete_by_id|remove_document|delete_idx' \
api || trueRepository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== dataset service relevant section =="
sed -n '130,226p' api/apps/services/dataset_api_service.py | cat -n
echo "== delete_documents/remove_document definitions =="
rg -n --glob '*.py' 'def remove_document|class DocumentService|def delete_by_id|filter_delete|delete_by_document_id|def delete_by_ids' api | sed -n '1,220p'
echo "== dataset_api route section =="
sed -n '170,218p' api/apps/restful_apis/dataset_api.py | cat -n
echo "== focused lock/transaction references near delete_dataset helpers =="
rg -n --glob '*.py' 'with DB\.atomic|db\.atomic|atomic\(|asyncio\.Lock|threading\.Lock|delete_datasets|_delete_datasets_sync|remove_document|delete_idx' api/db api/apps/services/dataset_api_service.py api/apps/restful_apis/dataset_api.py rag/settings.py rag/nlp/search.py 2>/dev/null || true
echo "== parse delete_datasets call flow summary =="
python3 - <<'PY'
import ast, pathlib
p=pathlib.Path('api/apps/restful_apis/dataset_api.py')
tree=ast.parse(p.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == 'delete_dataset':
print("delete_dataset lines", node.lineno, node.end_lineno)
print(ast.get_source_segment(p.read_text(), node.body))
PYRepository: infiniflow/ragflow
Length of output: 13673
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== read-only behavioral summary of delete_datasets cleanup operations =="
python3 - <<'PY'
from pathlib import Path
import ast
files = {
"src": Path("api/apps/services/dataset_api_service.py"),
"service_doc": Path("api/db/services/document_service.py"),
"service_file": Path("api/db/services/file_service.py"),
"service_file2doc": Path("api/db/services/file2document_service.py"),
"service_kb": Path("api/db/services/knowledgebase_service.py"),
}
for name, p in files.items():
src = p.read_text()
tree = ast.parse(src)
print(f"\n## {p}")
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name in {
"_delete_datasets_sync",
"remove_document",
"filter_delete",
"delete_by_id",
"delete_by_document_id",
"delete_by_ids_or_file_ids",
}:
start = node.lineno
end = node.end_lineno
lines = src.splitlines()
header = f"{node.name} [{start}-{end}]"
has_atomic_db = any(
"DB.atomic()" in line or "db.atomic()" in line or "atomic(" in line
for line in lines[start-1:end]
)
print(header, "atomic_db=", has_atomic_db)
for i, line in enumerate(lines[start-1:end], start):
if any(tok in line for tok in ("DocumentService.query", "DocumentService.remove_document", "FileService.filter_delete", "File2DocumentService.get", "File2DocumentService.delete_by_document_id", "settings.docStoreConn.delete_idx", "KnowledgebaseService.delete_by_id", "with DB.atomic()", "db.atomic()", "filter_delete", "delete_by_document_id", "delete_by_id", "delete_idx")):
print(f"{i}: {line}")
PY
echo "== delete_by_document_id implementation =="
sed -n '55,85p' api/db/services/file2document_service.py | cat -n
echo "== KnowledgebaseService.delete_by_id implementation candidates =="
rg -n --glob '*.py' 'class KnowledgebaseService|def delete_by_id' api/db api/apps/services | sed -n '1,220p'Repository: infiniflow/ragflow
Length of output: 3283
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== FileService.delete_by_id and CommonService.delete_by_id =="
sed -n '680,705p' api/db/services/file_service.py | cat -n
sed -n '305,335p' api/db/services/common_service.py | cat -n
echo "== remove_document full implementation =="
sed -n '458,567p' api/db/services/document_service.py | cat -n
echo "== KnowledgebaseService methods =="
sed -n '45,85p' api/db/services/knowledgebase_service.py | cat -n
echo "== common delete/filter implementations in common_service =="
sed -n '225,348p' api/db/services/common_service.py | cat -nRepository: infiniflow/ragflow
Length of output: 15953
Serialize or make dataset deletion idempotent before asyncio.to_thread.
delete_datasets now yields while _delete_datasets_sync runs concurrently for the same dataset. The caller path does not hold a per-dataset lock, and the linked cleanup calls only get isolated DB.atomic() scopes, not a serialization/transaction boundary. If two requests target the same dataset, add a per-dataset lock or make retry/de-staging cleanup idempotent.
🧰 Tools
🪛 Ruff (0.16.0)
[warning] 224-224: PEP 484 prohibits implicit Optional
Convert to T | None
(RUF013)
🤖 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 224 - 225, Update
delete_datasets and _delete_datasets_sync to prevent concurrent deletion
requests for the same dataset from racing. Add per-dataset serialization around
the asyncio.to_thread call, or make the deletion and linked cleanup operations
safely idempotent across retries, while preserving concurrent deletion for
different datasets.
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 5 --glob '*.py' \
'asyncio\.to_thread|run_in_executor|set_default_executor|ThreadPoolExecutor' \
api || trueRepository: infiniflow/ragflow
Length of output: 18848
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== files =="
wc -l api/apps/services/dataset_api_service.py api/apps/restful_apis/file2document_api.py api/apps/services/dataset_api.py 2>/dev/null || true
echo "== dataset_service relevant =="
sed -n '1,80p;210,232p' api/apps/services/dataset_api_service.py 2>/dev/null || true
echo "== file2document relevant =="
sed -n '170,195p' api/apps/restful_apis/file2document_api.py 2>/dev/null || true
echo "== Python asyncio.to_thread executor probe =="
python3 - <<'PY'
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def probe(loop):
def current_thread():
return type(asyncio.get_running_loop().default_executor), current_thread
result = await loop.run_in_executor(None, current_thread)
return result
loop = asyncio.new_event_loop()
try:
try:
def current_thread():
return type(asyncio.get_running_loop().default_executor), current_thread
fut = asyncio.to_thread(current_thread, loop=loop)
print("run_in_executor(None)=<future>")
try:
asyncio.get_running_loop().add_done_callback(lambda f: None)
except RuntimeError:
print("no_running_loop_no_callback", end="")
except Exception as exc:
print(f"asyncio.to_thread(loop=loop)={type(exc).__name__}: {exc}")
try:
fut = asyncio.create_task(asyncio.to_thread(current_thread))
print("to_thread_current_loop=<task>")
except Exception as exc:
print(f"asyncio.create_task(asyncio.to_thread())={type(exc).__name__}: {exc}")
finally:
try:
loop.run_until_complete(probe(loop))
finally:
loop.close()
print("executor=ThreadPoolExecutor")
finally:
loop.close()
PY
echo "== executor-related occurrences in api =="
rg -n --glob '*.py' 'loop\.run_in_executor|get_running_loop\(\)\.run_in_executor|asyncio\.to_thread|set_default_executor|ThreadPoolExecutor\(' api || trueRepository: infiniflow/ragflow
Length of output: 6593
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== files =="
wc -l api/apps/services/dataset_api_service.py api/apps/restful_apis/file2document_api.py api/apps/services/dataset_api.py 2>/dev/null || true
echo "== dataset_service relevant =="
sed -n '1,80p;210,232p' api/apps/services/dataset_api_service.py 2>/dev/null || true
echo "== file2document relevant =="
sed -n '170,195p' api/apps/restful_apis/file2document_api.py 2>/dev/null || true
echo "== Python asyncio.to_thread executor probe =="
python3 - <<'PY'
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def probe(loop):
def current_thread():
return type(asyncio.get_running_loop().default_executor), current_thread
result = await loop.run_in_executor(None, current_thread)
return result
loop = asyncio.new_event_loop()
try:
try:
def current_thread():
return type(asyncio.get_running_loop().default_executor), current_thread
fut = asyncio.to_thread(current_thread, loop=loop)
print("run_in_executor(None)=<future>")
try:
asyncio.get_running_loop().add_done_callback(lambda f: None)
except RuntimeError:
print("no_running_loop_no_callback", end="")
except Exception as exc:
print(f"asyncio.to_thread(loop=loop)={type(exc).__name__}: {exc}")
try:
fut = asyncio.create_task(asyncio.to_thread(current_thread))
print("to_thread_current_loop=<task>")
except Exception as exc:
print(f"asyncio.create_task(asyncio.to_thread())={type(exc).__name__}: {exc}")
finally:
try:
loop.run_until_complete(probe(loop))
finally:
loop.close()
print("executor=ThreadPoolExecutor")
finally:
loop.close()
PY
echo "== executor-related occurrences in api =="
rg -n --glob '*.py' 'loop\.run_in_executor|get_running_loop\(\)\.run_in_executor|asyncio\.to_thread|set_default_executor|ThreadPoolEncoder\(' api || trueRepository: infiniflow/ragflow
Length of output: 6593
Use a bounded executor for long dataset deletions if isolation matters.
delete_datasets schedules _delete_datasets_sync on the default executor, which is also used by other offloaded API work. If this deletion can run long, route it through a bounded service-owned executor/queue so it does not compete with unrelated background threads.
🧰 Tools
🪛 Ruff (0.16.0)
[warning] 224-224: PEP 484 prohibits implicit Optional
Convert to T | None
(RUF013)
🤖 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 224 - 225, Update
delete_datasets to submit _delete_datasets_sync to a service-owned bounded
executor or queue instead of asyncio.to_thread’s default executor. Reuse the
existing executor infrastructure if available, and preserve the current
arguments and async result behavior while isolating long-running dataset
deletions from unrelated offloaded work.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17796 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
No description provided.