Skip to content

fix(parsing): self-heal 'tasks are ahead in the queue' so stopped parses don't hang - #16499

Closed
ondery wants to merge 4 commits into
infiniflow:mainfrom
ondery:fix/parse-queue-length-self-heal
Closed

ondery wants to merge 4 commits into
infiniflow:mainfrom
ondery:fix/parse-queue-length-self-heal

Conversation

@ondery

@ondery ondery commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Summary

When parsing documents (especially large files), users keep seeing a stale N tasks are ahead in the queue... message (e.g. 34 tasks are ahead in the queue...) and parsing appears to hang forever, even after every parse job has been stopped.

Root cause

get_queue_length() returned the raw Redis stream consumer-group lag:

def get_queue_length(priority, suffix="common"):
    group_info = REDIS_CONN.queue_info(settings.get_svr_queue_name(priority, suffix), SVR_CONSUMER_GROUP_NAME)
    if not group_info:
        return 0
    return int(group_info.get("lag", 0) or 0)

lag counts every undelivered message in the stream, including messages whose tasks were already cancelled/stopped. Stopping a parse only sets the DB run=CANCEL and the Redis {task_id}-cancel flag — it does not remove the already-queued messages from the stream. Those messages only stop counting toward lag once a task executor happens to read and ack them. While an executor is busy on a large file (or after a crash/restart), the cancelled messages stay in lag, so the figure never returns to 0 and the document looks stuck in an infinite queue.

Additionally, _sync_progress skips documents with run=CANCEL, so the last N tasks are ahead in the queue... text stays frozen on a stopped document.

Changes

  • Self-healing queue length: 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 a document whose run == RUNNING and progress in [0, 1)). The value drops back to reality the instant work is cancelled or finishes. A short in-process cache (3 s) avoids issuing a COUNT per document on every progress-sync cycle.
  • Safe fallback: if the DB count can't be determined, it falls back to the previous raw-lag behaviour.
  • Clear stale message on stop: the N tasks are ahead in the queue... progress message is cleared when a document parse is stopped/cancelled (single-document run, bulk stop, and per-task stop paths).
  • Tests: added unit tests covering the capping, self-heal-to-zero, lag-smaller-than-pending, DB-unavailable fallback, missing-group and null-lag cases.

Test plan

  • python -m py_compile on all changed files
  • uv run pytest test/unit_test/api/db/services/test_get_queue_length.py
  • Manual: queue several large-file parses, stop them, confirm the queue count returns to 0 and documents no longer show a frozen N tasks are ahead in the queue...

…ses don't hang

The user-facing queue length came straight from the Redis stream consumer-group
lag, which counts every undelivered message including those whose tasks were
already cancelled/stopped. Such messages only leave the lag once a task executor
happens to read them, so after stopping parses the figure could stay inflated
(e.g. "34 tasks are ahead in the queue...") indefinitely and parsing appeared to
hang forever.

- Cap the reported queue length by the number of tasks that are genuinely still
  waiting in the database (progress == 0 on an actively-running document), so it
  self-heals the moment work is cancelled or completes. A short in-process cache
  avoids a COUNT query per document on every progress cycle.
- Fall back to the raw Redis lag when the DB count cannot be determined.
- Clear the stale "N tasks are ahead in the queue..." progress message when a
  document parse is stopped/cancelled.
- Add unit tests for the queue-length capping/fallback behaviour.
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Clears progress_msg on document cancel/stop paths. Adds cached pending-task counting and caps Redis queue lag with that count. Adds unit tests for the queue-length and pending-count behavior.

Queue Message Cleanup and Lag Capping

Layer / File(s) Summary
Clear progress_msg on cancel/stop
api/apps/restful_apis/document_api.py, api/apps/restful_apis/task_api.py
Three cancel/stop paths now write progress_msg: "" when setting documents to CANCEL.
Pending count and lag capping
api/db/services/document_service.py
Adds get_pending_task_count() with a monotonic TTL cache and updates get_queue_length() to cap Redis lag with the database pending count when available.
Queue length tests
test/unit_test/api/db/services/test_get_queue_length.py
New pytest module covers lag capping, fallback behavior, missing lag handling, DB error handling, and cache reuse.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • infiniflow/ragflow#15789: Also updates the document cancel/stop flow to reset progress-related fields when marking documents as CANCEL, overlapping the same control paths changed here.

Suggested labels

🐞 bug

🐇 A stale queue whisper faded away,
Progress went blank at cancel today.
Lag met the truth in a cached little count,
And tests kept the numbers in tidy amount.
Hop, hop—no more “ahead” in the line!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.17% 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 summarizes the main fix: stale queue messages causing stopped parses to appear hung.
Description check ✅ Passed The description includes the required summary plus useful root cause, changes, and test plan context.
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.

@ondery ondery changed the title fix(parsing): self-heal asks are ahead in the queue so stopped parses don't hang fix(parsing): self-heal 'tasks are ahead in the queue' so stopped parses don't hang Jun 30, 2026
ondery and others added 3 commits June 30, 2026 12:44
…the queue"

A document split into many tasks (e.g. a 1500-page PDF becomes ~127 page-range
tasks) reported "127 tasks are ahead in the queue..." for itself, because the
queue length included the document's own not-yet-started tasks. On every
cancel+restart the figure also appeared to grow (127 -> 254 ...) since the raw
Redis stream lag keeps undelivered messages from previous runs.

Subtract the document's own queued tasks (progress == 0) from the reported
queue length in _sync_progress, so the message reflects how many *other* tasks
are genuinely ahead of it. Combined with the lag/DB-backlog cap this keeps the
figure honest and self-healing.

Co-authored-by: Cursor <[email protected]>

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/db/services/document_service.py (1)

940-950: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Scope own_queued to the same priority used for get_queue_length().

Line 982 asks for one priority queue, but Line 949 counts every zero-progress task for the document. If a document has mixed-priority tasks, this can subtract tasks that were never in that queue and under-report queue_ahead.

Possible direction
-                own_queued = 0
+                own_queued_by_priority = {}
...
-                    if (t.progress or 0) == 0:
-                        own_queued += 1
+                    if (t.progress or 0) == 0:
+                        own_queued_by_priority[t.priority] = own_queued_by_priority.get(t.priority, 0) + 1
...
-                        queue_ahead = max(0, get_queue_length(priority) - own_queued)
+                        queue_ahead = max(0, get_queue_length(priority) - own_queued_by_priority.get(priority, 0))
...
-                    queue_ahead = max(0, get_queue_length(priority) - own_queued)
+                    queue_ahead = max(0, get_queue_length(priority) - own_queued_by_priority.get(priority, 0))

Also applies to: 982-986

🤖 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/document_service.py` around lines 940 - 950, The own_queued
count in DocumentService should be limited to the same priority queue used by
get_queue_length(), because the current loop in the document task scan counts
every zero-progress task regardless of priority and can skew queue_ahead. Update
the task iteration in the document_service logic to filter by the requested
priority before incrementing own_queued, using the same priority selection path
as get_queue_length() and the queue_ahead calculation around the referenced
block.
🧹 Nitpick comments (1)
api/db/services/document_service.py (1)

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

Log the pending-count fallback path.

When the DB count fails and returns None, add a warning before falling back to raw Redis lag so stale queue-message regressions are diagnosable.

Suggested addition
 except Exception:
+    logging.warning(
+        "Failed to count pending parse tasks; falling back to Redis queue lag",
+        exc_info=True,
+    )
     return None

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/db/services/document_service.py` around lines 1113 - 1151, The fallback
path from get_pending_task_count() to the raw Redis stream lag is currently
silent when the database count fails and returns None. Update the caller that
consumes get_pending_task_count() to emit a warning before using the fallback,
including enough context to diagnose stale queue-message regressions and
referencing the failed pending-count lookup. Keep the existing exception logging
in get_pending_task_count(), but add the new warning in the fallback flow so the
None-return path is observable.

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.

Outside diff comments:
In `@api/db/services/document_service.py`:
- Around line 940-950: The own_queued count in DocumentService should be limited
to the same priority queue used by get_queue_length(), because the current loop
in the document task scan counts every zero-progress task regardless of priority
and can skew queue_ahead. Update the task iteration in the document_service
logic to filter by the requested priority before incrementing own_queued, using
the same priority selection path as get_queue_length() and the queue_ahead
calculation around the referenced block.

---

Nitpick comments:
In `@api/db/services/document_service.py`:
- Around line 1113-1151: The fallback path from get_pending_task_count() to the
raw Redis stream lag is currently silent when the database count fails and
returns None. Update the caller that consumes get_pending_task_count() to emit a
warning before using the fallback, including enough context to diagnose stale
queue-message regressions and referencing the failed pending-count lookup. Keep
the existing exception logging in get_pending_task_count(), but add the new
warning in the fallback flow so the None-return path is observable.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 35aa1a1f-1b81-463f-9dde-1bd59548041f

📥 Commits

Reviewing files that changed from the base of the PR and between 96a5922 and 5a480a5.

📒 Files selected for processing (1)
  • api/db/services/document_service.py

@ondery

ondery commented Jun 30, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #16502, which contains these queue-length changes plus the fix for the underlying task-executor freeze (a Langfuse flush/shutdown deadlock on the event loop). Closing in favor of the single consolidated PR.

@ondery ondery closed this Jun 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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