Skip to content

Fix: Let delete dataset/document to a dedicated thread to avoid blocking othe APIs - #17800

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

wangq8 merged 4 commits into
infiniflow:mainfrom
wangq8:bugfix/let-delete-document-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 size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 4, 2026
@coderabbitai

coderabbitai Bot commented Aug 4, 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 Plus

Run ID: b27529c4-e957-485f-b5e8-5a41d4db600e

📥 Commits

Reviewing files that changed from the base of the PR and between 8b86d40 and 87fd7da.

📒 Files selected for processing (1)
  • test/unit_test/api/apps/services/test_dataset_api_service_list_datasets.py

📝 Walkthrough

Walkthrough

The change adds a shared bounded executor for long-running synchronous tasks. Dataset and document deletion now use this executor. Context variables and existing deletion behavior remain unchanged.

Changes

Long-running deletion execution

Layer / File(s) Summary
Shared long-running executor
common/misc_utils.py
Adds a bounded shared ThreadPoolExecutor and thread_pool_exec_long_time, which propagates ContextVars and avoids per-call shutdown waits.
Deletion API wiring
api/apps/services/dataset_api_service.py, api/apps/restful_apis/document_api.py, test/unit_test/api/apps/services/test_dataset_api_service_list_datasets.py
Dataset deletion uses an async wrapper around synchronous deletion work. Document deletion uses the same long-running executor. The dataset service test stub includes the new executor symbol.

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

Possibly related PRs

Poem

A rabbit sends work to a bounded queue,
With context carried safely through.
Dataset and document tasks now run,
While workers hop until they are done.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request has no description and omits the required Summary section and background context. Add a Summary section that explains the blocking problem, the dedicated thread-pool solution, and its effect on dataset and document deletion.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the change to move dataset and document deletion to dedicated threads to prevent API blocking.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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: 1

🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)

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

Add logging for the new offload flow.

Log the deletion dispatch and completion with a document count and elapsed time. Log partial deletion errors before returning them. Do not log document contents or full document ID lists.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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/restful_apis/document_api.py` at line 1207, Update the deletion flow
around FileService.delete_docs to log dispatch and completion with the document
count and elapsed time, without logging document contents or full ID lists.
Before returning any partial deletion errors, emit a log containing the error
details, while preserving the existing return behavior.

Source: Coding guidelines

🤖 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/restful_apis/document_api.py`:
- Line 1207: Update the document deletion flow around FileService.delete_docs to
submit work through a dedicated bounded executor instead of asyncio.to_thread’s
default executor. Create or reuse the executor for document cleanup, invoke it
via the event loop’s run_in_executor, and preserve the existing doc_ids and
tenant_id arguments and error handling.

---

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Line 1207: Update the deletion flow around FileService.delete_docs to log
dispatch and completion with the document count and elapsed time, without
logging document contents or full ID lists. Before returning any partial
deletion errors, emit a log containing the error details, while preserving the
existing return 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: 72752765-7832-41c0-b717-9198b250cfdf

📥 Commits

Reviewing files that changed from the base of the PR and between 7e67b71 and df972df.

📒 Files selected for processing (1)
  • api/apps/restful_apis/document_api.py

Comment thread api/apps/restful_apis/document_api.py Resolved
@wangq8 wangq8 added ci Continue Integration and removed ci Continue Integration labels Aug 4, 2026
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Aug 4, 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.

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

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

Fix implicit Optional type hints.

ids: list = None at both Line 146 and Line 223 uses an implicit Optional. PEP 484 requires an explicit Optional[list] or list | None. Ruff flags this as RUF013 in both locations.

🔧 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 | 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 | None = None, delete_all: bool = False):

Also applies to: 223-223

🤖 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 146, Update the ids
parameter annotations in both _delete_datasets_sync and the corresponding
function at the second occurrence to explicitly allow None, using Optional[list]
or list | None while preserving their existing defaults and behavior.

Source: Linters/SAST tools

common/misc_utils.py (2)

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

Add logging to the new long-running-executor flow.

thread_pool_exec_long_time is a new flow with no logging. Add a log line when a task is submitted (function name, queue state) and when it fails, so operators can diagnose slow or stuck long-running deletions in production. This also applies to the call sites in api/apps/services/dataset_api_service.py (delete_datasets) and api/apps/restful_apis/document_api.py (delete_documents), which route through this helper without adding their own logging either.

As per coding guidelines, "Add logging for new flows" for **/*.py.

♻️ Proposed logging addition
 async def thread_pool_exec_long_time(func, *args, **kwargs):
     """..."""
     loop = asyncio.get_running_loop()
     ctx = contextvars.copy_context()
+    logging.info("thread_pool_exec_long_time: submitting %s", getattr(func, "__name__", func))
     if kwargs:
         inner = functools.partial(func, *args, **kwargs)
-        return await loop.run_in_executor(_LONG_TIME_THREAD_POOL_EXECUTOR, ctx.run, inner)
-    return await loop.run_in_executor(_LONG_TIME_THREAD_POOL_EXECUTOR, ctx.run, func, *args)
+        try:
+            return await loop.run_in_executor(_LONG_TIME_THREAD_POOL_EXECUTOR, ctx.run, inner)
+        except Exception:
+            logging.exception("thread_pool_exec_long_time: %s failed", getattr(func, "__name__", func))
+            raise
+    try:
+        return await loop.run_in_executor(_LONG_TIME_THREAD_POOL_EXECUTOR, ctx.run, func, *args)
+    except Exception:
+        logging.exception("thread_pool_exec_long_time: %s failed", getattr(func, "__name__", func))
+        raise
🤖 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 `@common/misc_utils.py` around lines 263 - 290, Update
thread_pool_exec_long_time to log each submission with the callable name and
current long-task executor queue state, then log failures with the callable
context and exception before propagating them. Ensure the delete_datasets and
delete_documents call sites retain sufficient operation-specific context through
this helper so long-running deletion submissions and failures are diagnosable.

Source: Coding guidelines


33-33: 🚀 Performance & Scalability | 🔵 Trivial

Note the queuing behavior of a single-worker bounded pool.

_LONG_TIME_THREAD_POOL_EXECUTOR defaults to one worker. All dataset and document deletions across the process now serialize through this single thread, and ThreadPoolExecutor's internal work queue is unbounded, so submitted deletions queue indefinitely with no backpressure or depth limit.

Confirm this is the intended production behavior. If multiple large tenants delete concurrently, later requests wait behind earlier ones with no visibility into how long the wait will be.

🤖 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 `@common/misc_utils.py` at line 33, Review the production behavior of
_LONG_TIME_THREAD_POOL_EXECUTOR: avoid an unintended single-worker, unbounded
queue by choosing an appropriate default worker count and adding bounded
submission/backpressure or another explicit queue-depth strategy. Preserve
configurable worker settings while ensuring concurrent tenant deletions cannot
accumulate indefinitely without visibility.
🤖 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`:
- Line 146: Update the ids parameter annotations in both _delete_datasets_sync
and the corresponding function at the second occurrence to explicitly allow
None, using Optional[list] or list | None while preserving their existing
defaults and behavior.

In `@common/misc_utils.py`:
- Around line 263-290: Update thread_pool_exec_long_time to log each submission
with the callable name and current long-task executor queue state, then log
failures with the callable context and exception before propagating them. Ensure
the delete_datasets and delete_documents call sites retain sufficient
operation-specific context through this helper so long-running deletion
submissions and failures are diagnosable.
- Line 33: Review the production behavior of _LONG_TIME_THREAD_POOL_EXECUTOR:
avoid an unintended single-worker, unbounded queue by choosing an appropriate
default worker count and adding bounded submission/backpressure or another
explicit queue-depth strategy. Preserve configurable worker settings while
ensuring concurrent tenant deletions cannot accumulate indefinitely without
visibility.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 087d5884-3650-40c9-a7b3-c09061f50e06

📥 Commits

Reviewing files that changed from the base of the PR and between df972df and 8b86d40.

📒 Files selected for processing (3)
  • api/apps/restful_apis/document_api.py
  • api/apps/services/dataset_api_service.py
  • common/misc_utils.py

@wangq8 wangq8 changed the title Fix: Let delete document to a dedicated thread to avoid blocking othe APIs Fix: Let delete dataset/document to a dedicated thread to avoid blocking othe APIs Aug 4, 2026
@wangq8 wangq8 added ci Continue Integration and removed ci Continue Integration labels Aug 4, 2026

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review: Fix: Let delete dataset/document to a dedicated thread to avoid blocking other APIs

Summary

This PR introduces a new thread_pool_exec_long_time helper that uses a module-level singleton ThreadPoolExecutor instead of a temporary per-call executor. The problem it solves: thread_pool_exec uses with ThreadPoolExecutor(...) which calls shutdown(wait=True) on exit — when a client disconnects or the request times out during a long-running delete, request cancellation unwinds the coroutine back through the with block, which blocks waiting for the worker to finish. This effectively locks the Quart request task even though we no longer need the result.

What Changed

File Change
common/misc_utils.py New thread_pool_exec_long_time function with module-level _LONG_TIME_THREAD_POOL_EXECUTOR (bounded pool, default max_workers=1)
api/apps/restful_apis/document_api.py delete_documents: thread_pool_exec → thread_pool_exec_long_time
api/apps/services/dataset_api_service.py delete_datasets: asyncio.to_thread → thread_pool_exec_long_time; removes unused import asyncio
test/.../test_dataset_api_service_list_datasets.py Mocks the new thread_pool_exec_long_time

Analysis

✅ Root cause is correctly identified. The with ThreadPoolExecutor pattern in thread_pool_exec creates a shutdown(wait=True) trap on request cancellation — exactly the scenario described.

✅ Solution is sound. Using a process-level singleton executor means request cancellation cannot trigger executor shutdown. The running sync callable continues in the background, but the Quart request task is released to serve other requests. This is the right trade-off for fire-and-forget-ish delete operations where the side effects matter more than the return value.

✅ Bounded pool (default max_workers=1) prevents resource exhaustion. Multiple concurrent deletes will queue instead of spawning unbounded threads. Users can increase capacity via LONG_TIME_THREAD_POOL_WORKERS env var if needed.

✅ ContextVars are properly copied. The new function copies contextvars into the worker thread, matching thread_pool_exec behavior (important for tracing/per-request state).

✅ asyncio import removal is safe. Verified: the only usage in dataset_api_service.py was asyncio.to_thread(...), which is now replaced. No other references to asyncio in that file.

✅ Test mock added. The unit test properly mocks thread_pool_exec_long_time alongside the existing thread_pool_exec mock.

⚠️ Callers won't see the result on disconnect. When the client disconnects during a long delete, the await is cancelled but the sync function keeps running in the pool — the caller never gets the return value. This is fine for mutations (deletion side effects happen regardless), but means the API response is lost. Not a bug, just a behavioral note.

⚠️ Module-level executor has no explicit shutdown. Python's atexit handles cleanup, but if the module is reloaded (e.g., in test suites or hot-reload setups), the old executor threads could leak. This is unlikely in production but worth noting. Consider adding an atexit.register(...) or a shutdown() function for tests if needed in the future.

Verdict

LGTM ✅ — well-reasoned fix with clear docstring, proper context propagation, and correctly scoped to the two call sites that need it. The trade-offs (lost response on disconnect, module-level executor lifecycle) are reasonable for this use case.

@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 (7e67b71) to head (87fd7da).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17800   +/-   ##
=======================================
  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 merged commit f707cca into infiniflow:main Aug 4, 2026
3 checks passed
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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant