Repository navigation
fix(task_executor): fix Langfuse flush/shutdown deadlock that freezes document parsing - #16502
Conversation
|
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:
📝 WalkthroughWalkthroughUpdates queue-length calculations to cap Redis lag with a DB-backed pending count, clears ChangesQueue Length Accuracy, Cancellation Cleanup, and LLM Close Fix
Estimated code review effort: 3 (Moderate) | ~20 minutes Suggested labels: 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: 2
🧹 Nitpick comments (3)
api/db/services/tenant_llm_service.py (1)
562-567: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the callable check to satisfy Ruff B009.
callable(getattr(self.mdl, "close"))triggers RuffB009(getattrwith a constant attribute). Since the project lints withruff check, prefer direct attribute access.hasattralready guards existence, so thegetattrcall is also redundant.♻️ Proposed simplification
- if self.mdl and hasattr(self.mdl, "close") and callable(getattr(self.mdl, "close")): + if self.mdl and callable(getattr(self.mdl, "close", None)):🤖 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/tenant_llm_service.py` around lines 562 - 567, The close-path in LLM4Tenant.close uses a redundant getattr-based callable check that triggers Ruff B009; simplify the model shutdown guard by relying on the existing hasattr check and direct attribute access on self.mdl.close. Update the logic around the self.mdl close handling so it still safely calls close() when present, but avoids getattr(..., "close") entirely and keeps the existing warning path intact.Sources: Coding guidelines, Linters/SAST tools
api/apps/restful_apis/task_api.py (1)
96-96: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog the document-state cleanup when clearing
progress_msg.This adds a new cancellation side effect on the document row, but the specific reset is not logged. Including
task_idanddoc_idin a small log here would make this flow debuggable when users report stale queue text. As per coding guidelines, "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/task_api.py` at line 96, The document-state cleanup in the cancellation flow is missing a log when `DocumentService.update_by_id` clears `progress_msg` and resets progress. Add a small log in the surrounding cancellation path that includes both `task_id` and `doc_id` before or after this update so the `TaskStatus.CANCEL` flow is traceable when stale queue text is reported.Source: Coding guidelines
api/apps/restful_apis/document_api.py (1)
1418-1420: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a cancellation-cleanup log here.
These new
progress_msgresets are silent today, which makes stale queue-text reports harder to trace back to a specific cancellation path ordoc_id. A smalllogging.info/logging.debugat each reset point would cover the new flow. As per coding guidelines, "Add logging for new flows".Also applies to: 1650-1650
🤖 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` around lines 1418 - 1420, The new progress_msg resets are currently silent, so add a small logging.info or logging.debug at each cancellation-cleanup reset point to make the flow traceable by doc_id and cancellation path. Update the code paths in document_api around the progress_msg clearing logic so the log records when stale queue text is dropped and which document triggered it, keeping the message concise and consistent at both reset locations.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/db/services/document_service.py`:
- Around line 986-990: The pending-cap logic in document_service should be
priority-aware rather than relying on only get_queue_length(priority), because
it can report stale lag from one priority even when get_pending_task_count()
across all priorities shows no real DB backlog. Update the queue-ahead
calculation in the progress_msg path to derive the cap from the actual pending
DB work for the current priority and fall back to 0 when that priority has no
live pending tasks, and make the same adjustment in the other matching block
around the later progress reporting logic. Use the existing get_queue_length,
get_pending_task_count, and own_queued_by_priority symbols to keep the behavior
consistent.
In `@test/unit_test/api/db/services/test_get_queue_length.py`:
- Around line 16-36: The cv2 fallback in _install_cv2_stub_if_unavailable() is
swallowing all exceptions silently, which Ruff flags and which hides unexpected
failures. Narrow the exception handling to the expected import failure for cv2,
and when the stub path is taken, emit a log message explaining that the cv2 stub
is being installed instead of using a bare pass. Keep the change localized to
the test helper and preserve the existing import-stub behavior.
---
Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1418-1420: The new progress_msg resets are currently silent, so
add a small logging.info or logging.debug at each cancellation-cleanup reset
point to make the flow traceable by doc_id and cancellation path. Update the
code paths in document_api around the progress_msg clearing logic so the log
records when stale queue text is dropped and which document triggered it,
keeping the message concise and consistent at both reset locations.
In `@api/apps/restful_apis/task_api.py`:
- Line 96: The document-state cleanup in the cancellation flow is missing a log
when `DocumentService.update_by_id` clears `progress_msg` and resets progress.
Add a small log in the surrounding cancellation path that includes both
`task_id` and `doc_id` before or after this update so the `TaskStatus.CANCEL`
flow is traceable when stale queue text is reported.
In `@api/db/services/tenant_llm_service.py`:
- Around line 562-567: The close-path in LLM4Tenant.close uses a redundant
getattr-based callable check that triggers Ruff B009; simplify the model
shutdown guard by relying on the existing hasattr check and direct attribute
access on self.mdl.close. Update the logic around the self.mdl close handling so
it still safely calls close() when present, but avoids getattr(..., "close")
entirely and keeps the existing warning path intact.
🪄 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: 2fa33b89-98a6-4f72-929c-2446a34f3e2c
📒 Files selected for processing (5)
api/apps/restful_apis/document_api.pyapi/apps/restful_apis/task_api.pyapi/db/services/document_service.pyapi/db/services/tenant_llm_service.pytest/unit_test/api/db/services/test_get_queue_length.py
- get_pending_task_count(priority): make the DB backlog cap priority-specific and cache per priority, so a stale lag on one priority queue no longer prevents the figure from self-healing to 0 when that priority has no real pending work. get_queue_length now passes its priority through. - tenant_llm_service.close(): drop the redundant getattr-based callable check (Ruff B009) in favour of callable(getattr(self.mdl, "close", None)). - test_get_queue_length: catch ImportError (not bare Exception) in the cv2 stub helper and log it (Ruff S110/BLE001); update tests for the per-priority cache. - Add debug logs on the cancel/stop progress_msg cleanup paths for traceability. Co-authored-by: Cursor <[email protected]>
|
Addressed the CodeRabbit review feedback in 3be9a04:
|
There was a problem hiding this comment.
Pull request overview
This PR addresses a task-executor freeze during large document parsing by removing unsafe Langfuse flush/shutdown calls from per-task cleanup, and improves the “tasks ahead in the queue” UI message so it self-heals after cancels/stops and excludes the current document’s own queued work.
Changes:
- Prevent executor deadlock by making
LLM4Tenant.close()drop the Langfuse reference without flushing/shutting down the shared client. - Make queue-length reporting “honest” by capping Redis stream lag with a DB-derived pending-task count and subtracting the document’s own queued tasks from the displayed “ahead” value.
- Clear stale
progress_msgon cancel/stop paths; add unit tests for the queue-length logic.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
api/db/services/tenant_llm_service.py |
Removes Langfuse flush/shutdown from per-task cleanup to prevent event-loop deadlock; improves model close logging. |
api/db/services/document_service.py |
Adds DB-backed pending count + TTL cache, caps Redis lag, adjusts “ahead” calculation to exclude the current doc’s queued tasks. |
api/apps/restful_apis/task_api.py |
Clears document progress_msg when cancelling a task to avoid stale queue text. |
api/apps/restful_apis/document_api.py |
Clears progress_msg when canceling/stopping parsing so the UI message resets. |
test/unit_test/api/db/services/test_get_queue_length.py |
Adds unit tests for queue-length capping/caching behavior (with cv2 stubbing for test envs). |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/document_service.py`:
- Around line 1152-1154: The document count filter in the queue-length query is
excluding nullable Document.run values because it only checks for not-cancelled
runs. Update the condition in the document service query to treat NULL run
values as non-cancelled, matching the other document query logic by using
Document.run.is_null(True) alongside the existing TaskStatus.CANCEL comparison,
while keeping the rest of the status/progress filters unchanged.
🪄 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: 4ee6d002-cc38-47fd-bf0a-1e7b8913d475
📒 Files selected for processing (2)
api/db/services/document_service.pytest/unit_test/api/db/services/test_get_queue_length.py
🚧 Files skipped from review as they are similar to previous changes (1)
- test/unit_test/api/db/services/test_get_queue_length.py
42801e2 to
9e544d9
Compare
…ield
Agent runs (and any LLM-issuing flow) can now propagate the originating
session_id / user_id to upstream providers via the OpenAI-standard `user`
request field, which OpenAI / OpenRouter include in the request body. This
lets upstream activity (e.g. OpenRouter logs/analytics) be correlated back to
the chat session that produced it.
- common/llm_request_context.py: new ContextVar holding the per-request
{session_id, user_id}, with set/reset helpers and current_llm_user()
(prefers session_id, falls back to user_id)
- agent/canvas.py: Canvas.run() installs the request context for the duration
of the run and resets it in a finally (no cross-call leakage); the body is
delegated to _run_impl()
- rag/llm/chat_model.py: LiteLLMBase._construct_completion_args sets the `user`
field from the active request context (caller-supplied `user` still wins)
- api/db/services/canvas_service.py: forward session_id into the run kwargs
Co-authored-by: Cursor <[email protected]>
- canvas: copy the current context into the sync-component thread pool so the LLM request context (user forwarding) reaches LiteLLM calls made from sync components, not just async ones - llm_request_context: add debug log on install and a warning on the reset fallback, logging only presence flags (never raw session_id/user_id) - chat_model: honor an explicit caller-supplied `user` by key presence instead of truthiness, so `user=""` (suppression) is preserved Co-authored-by: Cursor <[email protected]>
…ezes parsing LLM4Tenant.close() (run once per task, synchronously, on the task executor's asyncio event-loop thread via LLMBundle.__exit__) called langfuse.flush() and langfuse.shutdown(). Both are unsafe there: - flush() blocks on an unbounded queue.join() in the underlying OpenTelemetry span processor and never returns if the exporter cannot drain. - shutdown() permanently tears down the process-wide Langfuse / OpenTelemetry tracer provider that every LLMBundle shares; after the first task shuts it down, every subsequent flush() blocks forever. Because close() runs on the event loop, one stuck flush() freezes the entire task executor: a few tasks finish, then all worker threads park on a lock and no document ever finishes parsing or gets picked up. Confirmed with py-spy: the MainThread was stuck in langfuse flush -> queue.join while every other thread was idle. Drop the Langfuse reference in close() without flushing/shutting down the shared client. Langfuse exports spans from its own background processor and flushes at process exit, so traces are still delivered. Co-authored-by: Cursor <[email protected]>
…ling The user-facing queue length came straight from the Redis stream consumer-group lag, which counts every undelivered message (including ones whose tasks were already cancelled/stopped, and a document's own not-yet-started page tasks). So a single big PDF (split into ~127 page tasks) reported "127 tasks are ahead in the queue..." for itself, and the figure could appear to grow on every cancel+restart (127 -> 254 ...) because stale messages are never removed. - get_queue_length() now caps the raw Redis lag by the number of tasks that are genuinely still waiting in the database (Task.progress == 0 on an actively-running document), with a short monotonic TTL cache to avoid a COUNT per document on every progress-sync cycle. Falls back to the raw lag when the DB count is unavailable. - _sync_progress subtracts the document's own queued tasks for the matching priority queue, so the message reflects how many OTHER tasks are ahead. - Clear the stale "N tasks are ahead in the queue..." progress message when a parse is stopped/cancelled (single-doc run, bulk stop and per-task stop). - Add unit tests for the queue-length capping/fallback behaviour. Co-authored-by: Cursor <[email protected]>
- get_pending_task_count(priority): make the DB backlog cap priority-specific and cache per priority, so a stale lag on one priority queue no longer prevents the figure from self-healing to 0 when that priority has no real pending work. get_queue_length now passes its priority through. - tenant_llm_service.close(): drop the redundant getattr-based callable check (Ruff B009) in favour of callable(getattr(self.mdl, "close", None)). - test_get_queue_length: catch ImportError (not bare Exception) in the cv2 stub helper and log it (Ruff S110/BLE001); update tests for the per-priority cache. - Add debug logs on the cancel/stop progress_msg cleanup paths for traceability. Co-authored-by: Cursor <[email protected]>
- get_pending_task_count: don't require the document to be RUNNING with progress in [0,1). Special tasks (graphrag/raptor/mindmap) are queued via begin2parse(keep_progress=True) while the document's own progress may already be 1, so the old filter undercounted them and could drop the cap to 0 while Redis lag was still non-zero. Now only cancelled (run == CANCEL), failed (progress < 0) and soft-deleted (status != VALID) documents are excluded. - get_queue_length: short-circuit to 0 when Redis lag <= 0 so the DB COUNT/JOIN is skipped in the common (empty-queue) case during the progress-sync loop. - test cv2 stub: also catch OSError (missing shared libs), not only ImportError, so the test module still imports in environments where cv2 fails to load. Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Adds unit tests for the new provider `user` forwarding introduced by this PR, addressing the review note about missing coverage: - current_llm_user(): session_id preferred over user_id, falls back to user_id, returns None with no/empty context, and truncates to 128 chars. - set/reset lifecycle: reset restores the previous context and a stale token falls back safely instead of raising. - LiteLLMBase._construct_completion_args: the context user is applied only when the caller omits `user`; an explicit caller `user` overrides the context, and a caller-supplied empty string suppresses forwarding (key-presence, not truthiness). Co-authored-by: Cursor <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
ContextVar.reset() raises RuntimeError ("has already been used once") when
called with a token that was already consumed, and ValueError when the token
was created in a different context. The stale-token fallback only caught
ValueError, so the second reset in the run lifecycle (e.g. an async generator
closed from a different context on client disconnect, or a double reset) could
raise on Python 3.13 instead of falling back to clearing the value.
Catch both ValueError and RuntimeError so reset_llm_request_context never
leaks an exception regardless of how the token was invalidated.
Co-authored-by: Cursor <[email protected]>
a856803 to
c4a15e9
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16502 +/- ##
=======================================
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:
|
Lynn-Inf
left a comment
There was a problem hiding this comment.
Thanks for the PR. A few comments:
-
Use
_session_idand_user_idas defaults inagent/canvas.py:446-447instead of null to keepllm_request_contextclean. -
In
task_api.py:92, I noticed you're settingprogress_msgto an empty string. Could you explain the reasoning behind this change? -
Changes to
LLM4Tenantmay affecttask_executor— I'll ask @xugangqiang to evaluate that part.
1. IssueI had already opened PR #16429 for this change. However, when creating PR #16502, I accidentally based it on the previous branch, so the PRs became stacked. I explained the background and the reasoning in more detail in #16429. In short, Langfuse uses 2. IssueThis change is related to the Stop Parsing behavior. When a parsing task became stuck and the user clicked Stop Parsing, the details page continued to display the message:
Even though the parsing process had already been terminated, this message remained visible, which was misleading because it no longer reflected the actual state of the task. I initially created PR #16499 to address only this UI/message issue. Later, I concluded that it made more sense to solve both the parsing lock-up issue and the misleading status message together. Therefore, I closed #16499 and consolidated everything into PR #16502. 3. IssueRegarding "Changes to LLM4Tenant may affect task_executor", that's a reasonable concern. However, I have been running this version for several days in my own environment without encountering any issues related to |
|
I'd also like to provide some additional context regarding issue 1. I'm using RAGFlow as the AI backend for my own multi-tenant platform. Ideally, I would create a separate RAGFlow user for every tenant because it provides better isolation. However, that approach is not practical for my use case. Each user in my platform needs access to the same set of agents, search configurations, and shared datasets, while also having their own private datasets. At the moment, there isn't a built-in mechanism to define reusable agent templates or automatically provision a new RAGFlow user with a predefined configuration. In my scenario, whenever a new user registers, my backend would have to:
Besides adding considerable operational complexity, the dataset invitation flow is not suitable for an automated SaaS onboarding process, since I cannot expect every newly registered user to manually accept invitations. Because of these limitations, I currently manage all requests through a single RAGFlow account and distinguish users at the application layer by attaching custom metadata to every request. For this reason, propagating identifiers such as |
|
Thanks for the context.
|
wangq8
left a comment
There was a problem hiding this comment.
Review of PR #16502
Overall: Looks good. The PR is well-structured, addresses a real production deadlock with solid root-cause analysis (confirmed via py-spy), and includes comprehensive unit tests. 511 additions / 29 deletions across 10 files is a reasonable size for this fix.
1. Root cause fix (Langfuse flush/shutdown deadlock) — Excellent
The diagnosis is spot-on: flush() blocks on an unbounded queue.join() inside the OpenTelemetry span processor, and shutdown() permanently tears down the process-wide tracer provider. Doing either on the event-loop thread of the task executor is the kind of bug that would be incredibly painful to debug without py-spy — well caught.
The fix (just dropping the reference without flushing/shutting down) is correct. Langfuse exports from its own background processor and flushes at process exit, so traces are still delivered.
Bonus: The docstring in close() is thorough, explaining not just what changed but why — that is exactly the level of documentation this kind of fix deserves. The improved logging (warning with exc_info instead of silent pass) is also a nice upgrade.
2. Queue-length capping — Good
Capping Redis stream lag (group_info["lag"]) with the genuine DB pending task count is the right approach. A few observations:
- TTL cache (3s) — reasonable balance between accuracy and avoiding a COUNT/JOIN per document per cycle.
- Per-priority cache keying — correctly prevents one priority queue with stale lag from polluting another.
_sync_progresssubtraction — excluding the document's own queued tasks from "ahead" is the right semantic fix. Themax(0, ...)guard handles the edge case correctly.
Minor observation: _PENDING_TASK_COUNT_CACHE is module-level mutable state accessed from potentially multiple task-executor threads. For a TTL-based cache this doesn't need strict locking (stale reads self-heal within 3s), but worth noting if anyone ever extends the cache lifespan.
3. Progress message cleanup — Good
Clearing progress_msg on cancel/stop paths is the correct UI fix. The logging added (per CodeRabbit suggestion) at each cleanup point makes the flow traceable.
4. LLM request context propagation — Good
New common/llm_request_context.py is clean:
- ContextVar pattern with proper
set/resetlifecycle and stale-token fallback. - Session ID preferred over user ID, 128-char truncation, debug logging avoids raw identifiers.
- The
"user" not in completion_argscheck correctly preserves caller-supplieduser(including empty string to suppress forwarding).
The canvas.py change that copies contextvars before run_in_executor is necessary because context variables don't propagate across threads — glad to see this was handled rather than just setting the ContextVar and hoping for the best.
5. Test coverage — Good
test_get_queue_length.py— 6 test cases covering: DB cap, self-heal to zero, lag-as-bound, DB fallback, missing group info, null lag. Good coverage of edge cases.test_llm_request_context.py— 9 test cases covering: no context, session preference, user fallback, empty IDs, truncation, reset lifecycle, stale token resilience, andcompletion_argsuser-field precedence. Thorough.
Both test files include proper fixture isolation and the cv2 stub is well-handled.
6. Minor nits (non-blocking)
- Module namespace pollution approach in
get_queue_length: The module-level_PENDING_TASK_COUNT_CACHEand TTL constant work fine, but if this pattern grows, consider wrapping in a small class with classmethods for self-contained cache management. canvas.pycontext variable copy: The old codelambda: ctx.run(partial(...))was unnecessarily nested; the new version usingpartial(call_ctx.run, bound_call)is cleaner. Good cleanup.
Summary
| Area | Verdict |
|---|---|
| Deadlock fix | Correct and well-explained |
| Queue length honesty | Well-reasoned with appropriate caching |
| Progress msg cleanup | Sound |
| LLM context propagation | Clean implementation |
| Tests | Thorough |
| Docs/comments | Excellent |
This is a solid PR that fixes a real, painful bug. The only open concern from the RAGFlow team (Lynn-Inf's point about LLM4Tenant changes potentially affecting task_executor) should get a second pair of eyes from xugangqiang, but the change itself is logically sound.
Approve from a code-quality standpoint.
…marker - canvas.py: reuse the already-derived _session_id/_user_id for set_llm_request_context instead of reading kwargs again (Lynn-Inf) - task_api.py / document_api.py: append a 'Task stopped by user.' marker to progress_msg on cancel/stop instead of resetting it to empty, so the parse history is preserved and the stopped state is clear (Lynn-Inf)
Summary
Parsing large documents (e.g. a 1500-page PDF) eventually freezes the whole task executor: a few page tasks finish, then every document stays stuck and newly queued documents never start. Stopping and re-parsing does not help and the UI shows an ever-growing
N tasks are ahead in the queue...(e.g.127 -> 254 ...).This PR fixes the actual freeze (a Langfuse flush/shutdown deadlock) and makes the queue figure honest. It does not change how documents are split, so large PDFs keep parsing in full.
1. Root cause of the freeze (the real bug)
LLM4Tenant.close()runs once per task, synchronously, on the task executor's asyncio event-loop thread (viaLLMBundle.__exit__). It called:Both are unsafe there:
flush()blocks on an unboundedqueue.join()in the underlying OpenTelemetry span processor and never returns if the exporter cannot drain.shutdown()permanently tears down the process-wide Langfuse / OpenTelemetry tracer provider that everyLLMBundleshares. After the first task shuts it down, every subsequentflush()blocks forever.Because this runs on the event loop, one stuck
flush()freezes the entire executor. Captured live withpy-spyon a stuck executor — theMainThread(event loop) was parked here while all other threads were idle:Fix: drop the Langfuse reference in
close()without flushing/shutting down the shared client. Langfuse exports spans from its own background processor and flushes at process exit, so traces are still delivered.2. Honest, self-healing queue length
The
N tasks are ahead in the queue...text came straight from the Redis stream consumer-grouplag, which counts every undelivered message — including messages whose tasks were already cancelled/stopped, and a document's own not-yet-started page tasks. So a single big PDF reported its own 127 page tasks as "ahead", and the number could appear to grow on every cancel+restart because stale messages are never removed from the stream.get_queue_length()now caps the raw Redislagby the number of tasks genuinely still waiting in the database (Task.progress == 0on an actively-running document), with a short monotonic TTL cache to avoid aCOUNTper document each progress cycle. Falls back to the rawlagwhen the DB count is unavailable._sync_progresssubtracts the document's own queued tasks for the matching priority queue, so the figure reflects how many other tasks are ahead (addresses CodeRabbit's priority-scoping note from fix(parsing): self-heal 'tasks are ahead in the queue' so stopped parses don't hang #16499).N tasks are ahead in the queue...message is cleared when a parse is stopped/cancelled (single-doc run, bulk stop, per-task stop).Supersedes
Replaces #16499 (queue-length-only fix); this PR contains those changes plus the deadlock fix as a single change set.