Repository navigation
Fix: Let delete dataset/document to a dedicated thread to avoid blocking othe APIs - #17800
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThe 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. ChangesLong-running deletion execution
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
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: 1
🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)
1207-1207: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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
📒 Files selected for processing (1)
api/apps/restful_apis/document_api.py
…read-avoid-blocking-other-APIs
There was a problem hiding this comment.
🧹 Nitpick comments (3)
api/apps/services/dataset_api_service.py (1)
146-146: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFix implicit Optional type hints.
ids: list = Noneat both Line 146 and Line 223 uses an implicitOptional. PEP 484 requires an explicitOptional[list]orlist | 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 winAdd logging to the new long-running-executor flow.
thread_pool_exec_long_timeis 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 inapi/apps/services/dataset_api_service.py(delete_datasets) andapi/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 | 🔵 TrivialNote the queuing behavior of a single-worker bounded pool.
_LONG_TIME_THREAD_POOL_EXECUTORdefaults to one worker. All dataset and document deletions across the process now serialize through this single thread, andThreadPoolExecutor'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
📒 Files selected for processing (3)
api/apps/restful_apis/document_api.pyapi/apps/services/dataset_api_service.pycommon/misc_utils.py
wangq8
left a comment
There was a problem hiding this comment.
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.
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.
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
No description provided.