Skip to content

fix(task_executor): fix Langfuse flush/shutdown deadlock that freezes document parsing - #16502

Merged
wangq8 merged 21 commits into
infiniflow:mainfrom
ondery:fix/task-executor-langfuse-flush-deadlock
Jul 7, 2026
Merged

wangq8 merged 21 commits into
infiniflow:mainfrom
ondery:fix/task-executor-langfuse-flush-deadlock

Conversation

@ondery

@ondery ondery commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

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 (via LLMBundle.__exit__). It called:

self.langfuse.flush()
if hasattr(self.langfuse, 'shutdown'):
    self.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 this runs on the event loop, one stuck flush() freezes the entire executor. Captured live with py-spy on a stuck executor — the MainThread (event loop) was parked here while all other threads were idle:

join (queue.py:105)
flush (.../opentelemetry .../resource_manager.py:445)
flush (langfuse/.../client.py:2116)
close (api/db/services/tenant_llm_service.py:545)
close (api/db/services/llm_service.py:49)
__exit__ (api/db/services/llm_service.py:57)
handle (task_handler.py:144)
...
handle_task (task_executor.py:1713)

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-group lag, 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 Redis lag by the number of tasks 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 each progress 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 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).
  • The stale 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.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Updates queue-length calculations to cap Redis lag with a DB-backed pending count, clears progress_msg during cancellation flows, changes LLM4Tenant.close() cleanup, and adds unit tests for the queue logic.

Changes

Queue Length Accuracy, Cancellation Cleanup, and LLM Close Fix

Layer / File(s) Summary
Queue length and progress math
api/db/services/document_service.py
Adds cached pending-task counting, caps queue length with pending backlog, and subtracts each document’s own queued tasks from progress messages.
Clear progress_msg on cancellation
api/apps/restful_apis/document_api.py, api/apps/restful_apis/task_api.py
Sets progress_msg: "" in document cancellation updates for ingest, stop-parsing, and task-cancel flows.
LLM4Tenant.close() cleanup
api/db/services/tenant_llm_service.py
Removes langfuse.flush()/shutdown(), drops the langfuse reference directly, and logs model-close failures with warnings.
Queue logic tests
test/unit_test/api/db/services/test_get_queue_length.py
Adds tests for queue-length bounds, pending-count fallback, cache TTL behavior, and per-priority cache keying.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested labels: 🌈 python

Poem

🐇 I hopped through the queue in light,
Counted tasks till they felt just right.
When cancels land, the msg goes clear,
And tests keep the new path sincere.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.63% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main Langfuse deadlock fix affecting document parsing.
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.
Description check ✅ Passed The PR description includes the required Summary section and provides sufficient background and purpose for reviewers.

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

🧹 Nitpick comments (3)
api/db/services/tenant_llm_service.py (1)

562-567: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplify the callable check to satisfy Ruff B009.

callable(getattr(self.mdl, "close")) triggers Ruff B009 (getattr with a constant attribute). Since the project lints with ruff check, prefer direct attribute access. hasattr already guards existence, so the getattr call 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 win

Log 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_id and doc_id in 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 win

Add a cancellation-cleanup log here.

These new progress_msg resets are silent today, which makes stale queue-text reports harder to trace back to a specific cancellation path or doc_id. A small logging.info/logging.debug at 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3633d08 and 5165d0a.

📒 Files selected for processing (5)
  • api/apps/restful_apis/document_api.py
  • api/apps/restful_apis/task_api.py
  • api/db/services/document_service.py
  • api/db/services/tenant_llm_service.py
  • test/unit_test/api/db/services/test_get_queue_length.py

Comment thread api/db/services/document_service.py Resolved
ondery added a commit to ondery/ragflow that referenced this pull request Jun 30, 2026
- 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]>
@ondery

ondery commented Jun 30, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit review feedback in 3be9a04:

  • Priority-specific DB cap (major): get_pending_task_count(priority) now filters by Task.priority and caches per priority; get_queue_length passes its priority through. A stale lag on one priority queue no longer blocks self-healing to 0 when that priority has no real pending work.
  • Ruff B009 (tenant_llm_service.close): replaced callable(getattr(self.mdl, "close")) with callable(getattr(self.mdl, "close", None)).
  • Ruff S110/BLE001 (test helper): the cv2 stub now catches ImportError and logs instead of a bare except Exception: pass; tests updated for the per-priority cache (plus a new per-priority cache test).
  • Logging for new flows: added logging.debug at the cancel/stop progress_msg cleanup points (doc_id / task_id).

Copilot AI review requested due to automatic review settings July 1, 2026 06:30

Copilot AI 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.

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_msg on 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).

Comment thread api/db/services/document_service.py Resolved
Comment thread api/db/services/document_service.py Resolved

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 254f63e and 931d542.

📒 Files selected for processing (2)
  • api/db/services/document_service.py
  • test/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

Comment thread api/db/services/document_service.py Resolved

Copilot AI 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.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 2, 2026
@ondery
ondery force-pushed the fix/task-executor-langfuse-flush-deadlock branch 2 times, most recently from 42801e2 to 9e544d9 Compare July 3, 2026 11:55
ondery and others added 10 commits July 7, 2026 10:09
…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]>
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]>
@yingfeng
yingfeng force-pushed the fix/task-executor-langfuse-flush-deadlock branch from a856803 to c4a15e9 Compare July 7, 2026 02:13
@dosubot dosubot Bot removed the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 7, 2026
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 7, 2026
@yingfeng yingfeng added the ci Continue Integration label Jul 7, 2026
@yingfeng
yingfeng marked this pull request as draft July 7, 2026 02:13
@yingfeng
yingfeng marked this pull request as ready for review July 7, 2026 02:13
@wangq8 wangq8 self-assigned this Jul 7, 2026
@wangq8
wangq8 requested a review from Lynn-Inf July 7, 2026 02:17
@wangq8 wangq8 removed their assignment Jul 7, 2026
@codecov

codecov Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (705754e) to head (dd71c91).
⚠️ Report is 1 commits behind head on main.

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.
📢 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 requested a review from xugangqiang July 7, 2026 02:43

@Lynn-Inf Lynn-Inf 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.

Thanks for the PR. A few comments:

  1. Use _session_id and _user_id as defaults in agent/canvas.py:446-447 instead of null to keep llm_request_context clean.

  2. In task_api.py:92, I noticed you're setting progress_msg to an empty string. Could you explain the reasoning behind this change?

  3. Changes to LLM4Tenant may affect task_executor — I'll ask @xugangqiang to evaluate that part.

@ondery

ondery commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the PR. A few comments:

  1. Use _session_id and _user_id as defaults in agent/canvas.py:446-447 instead of null to keep llm_request_context clean.
  2. In task_api.py:92, I noticed you're setting progress_msg to an empty string. Could you explain the reasoning behind this change?
  3. Changes to LLM4Tenant may affect task_executor — I'll ask @xugangqiang to evaluate that part.

1. Issue

I 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 user_id and session_id for tracing and user-level analytics. OpenRouter also surfaces these fields in its Logs page, allowing requests to be correlated with individual users and sessions. I couldn't find any other reliable way to propagate this information through the current architecture. Without these identifiers, it becomes nearly impossible to distinguish requests in a multi-user (multi-tenant) environment.


2. Issue

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

"N tasks are ahead in the queue..."

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. Issue

Regarding "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 task_executor. Of course, there may still be edge cases that I haven't covered, but based on my current testing, I haven't observed any regressions caused by these changes.

@ondery

ondery commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

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:

  • Create a new RAGFlow user.
  • Recreate all required agents from an existing template.
  • Replicate the necessary configuration.
  • Invite the user to every shared dataset and wait for those invitations to be accepted.

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 user_id and session_id to integrations like Langfuse and OpenRouter is essential. These identifiers allow me to correlate requests, traces, logs, and usage with the actual end user, which is critical in a multi-tenant environment.

@Lynn-Inf

Lynn-Inf commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Thanks for the context.

  1. For multi‑tenant scenarios, consider using the Team feature — invite users as members to avoid re‑creating agents/configs, and keep private datasets isolated.

  2. For the misleading queue message, a better fix might be to append a "cancelled" log to progress_msg instead of resetting it. This preserves the history and clearly indicates the task was stopped.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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_progress subtraction — excluding the document's own queued tasks from "ahead" is the right semantic fix. The max(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/reset lifecycle and stale-token fallback.
  • Session ID preferred over user ID, 128-char truncation, debug logging avoids raw identifiers.
  • The "user" not in completion_args check correctly preserves caller-supplied user (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, and completion_args user-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_CACHE and TTL constant work fine, but if this pattern grows, consider wrapping in a small class with classmethods for self-contained cache management.
  • canvas.py context variable copy: The old code lambda: ctx.run(partial(...)) was unnecessarily nested; the new version using partial(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.

Comment thread agent/canvas.py Resolved
Comment thread api/apps/restful_apis/task_api.py Resolved
ondery added 3 commits July 7, 2026 12:27
…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)
@wangq8
wangq8 merged commit 28a41ed into infiniflow:main Jul 7, 2026
3 checks passed
@ondery
ondery deleted the fix/task-executor-langfuse-flush-deadlock branch July 7, 2026 11:21
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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants