Skip to content

Let DELETE /datasets to a dedicated thread to avoid blocking other APIs - #17796

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/let-delete-datasets-to-a-dedicated-thread-avoid-blocking-other-APIs
Aug 4, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/let-delete-datasets-to-a-dedicated-thread-avoid-blocking-other-APIs

Conversation

@wangq8

@wangq8 wangq8 commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

No description provided.

@wangq8 wangq8 added the ci Continue Integration label Aug 4, 2026
@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Aug 4, 2026
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Dataset deletion cleanup now runs in a worker thread. The asynchronous delete_datasets entry point preserves its arguments and return value while avoiding direct blocking work on the event loop.

Changes

Dataset deletion execution

Layer / File(s) Summary
Worker-thread deletion wrapper
api/apps/services/dataset_api_service.py
The synchronous _delete_datasets_sync helper retains dataset, document, file, and index cleanup. The public delete_datasets coroutine runs this helper with asyncio.to_thread.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: euvre

Poem

A rabbit hops through threads so light,
Deletion leaves the loop in flight.
Cleanup runs where workers tread,
While async paths stay clear ahead.
Carrots cheer the tidy flow!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning No pull request description was provided, so the required Summary section and background context are missing. Add a Summary section that explains moving DELETE /datasets work to a dedicated thread and why this prevents event-loop blocking.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes moving DELETE /datasets work to a dedicated thread to prevent blocking other APIs.
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.

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

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

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

Use explicit optional types for ids.

ids: list = None hides the element type and violates Ruff RUF013. Use list[str] | None in 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

📥 Commits

Reviewing files that changed from the base of the PR and between 64041e8 and 1ea7a8a.

📒 Files selected for processing (1)
  • api/apps/services/dataset_api_service.py

Comment on lines +224 to +225
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)

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.

📐 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 || true

Repository: 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))
PY

Repository: 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 -n

Repository: 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 || true

Repository: 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 || true

Repository: 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 || true

Repository: 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

codecov Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (79a57d2) to head (1ea7a8a).
⚠️ Report is 19 commits behind head on main.

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.
📢 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 added ci Continue Integration and removed ci Continue Integration labels Aug 4, 2026
@wangq8
wangq8 merged commit 7e67b71 into infiniflow:main Aug 4, 2026
7 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant