Skip to content

fix(parser): propagate cancellation while waiting for vision figure futures - #17014

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
iwasaki1112:fix/vision-figure-parser-cancellation
Sep 2, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
iwasaki1112:fix/vision-figure-parser-cancellation

Conversation

@iwasaki1112

Copy link
Copy Markdown
Contributor

What

vision_figure_parser_docx_wrapper_naive and VisionFigureParser.__call__ submit every figure's vision-LLM call to a ThreadPoolExecutor and then block on as_completed() until all of them finish, without ever calling callback() in between. Task cancellation is only observed at callback() call sites — it checks a Redis flag and raises TaskCanceledException — so cancelling a dataflow run while it's inside one of these loops has no visible effect until every submitted vision call finishes or hits its own timeout (minutes, on a slow/busy vision backend).

The three call sites that wrap VisionFigureParser (vision_figure_parser_docx_wrapper, vision_figure_parser_pdf_wrapper, vision_figure_parser_figure_xlsx_wrapper) also catch TaskCanceledException inside their generic except Exception as e: handler, which logs a "visual model error" and continues — i.e. a cancellation would be silently turned into a logged error instead of stopping the pipeline.

Fix

  • Replace the unbounded as_completed() wait with wait(..., timeout=1.0, return_when=FIRST_COMPLETED), polling once a second so a cancellation is observed while other figures are still in flight, rather than only after the whole batch drains.
  • On TaskCanceledException (or any other exception), cancel every future that hasn't started running yet, and unwind the executor without waiting for stragglers; on normal completion, shut it down normally.
  • Re-raise TaskCanceledException explicitly in the three wrapper functions instead of letting the broad except Exception absorb it.
  • Guard against an explicit callback=None (kwargs.get("callback", default) only substitutes the default when the key is absent, not when its value is None).

What this does not fix

concurrent.futures has no API to forcibly abort a future that's already running — a vision call whose HTTP request is in flight will run to completion (or its own @timeout(30, 3)) regardless of this change. This fix stops new vision calls from starting once a cancellation is observed; it does not abort ones already sent to the backend.

Testing

Verified against a live RAGFlow + Ollama deployment, cancelling a dataflow test run on a PDF with several figures still pending:

  • Before: the Cancel button had no observable effect — the backend kept logging vision requests to Ollama for 3+ minutes with no cancellation message in the task log.
  • After: the task log showed Task ... has been canceled (checked roughly once a second, matching the new poll interval) and TaskCanceledException / handle_task canceled within about a minute of pressing Cancel — bounded by the already-in-flight requests' own timeout, not by this change.

No automated test is included; this is concurrency/cancellation behavior that's awkward to assert deterministically without a real (or heavily mocked) backend and a real ThreadPoolExecutor. Open to suggestions on how the maintainers would want this covered.

vision_figure_parser_docx_wrapper_naive and VisionFigureParser.__call__
submitted every figure's vision-LLM call to a ThreadPoolExecutor and
then blocked on as_completed() until all of them finished, without
ever invoking callback() in between. Cancellation is only observed
where callback() is called (it checks a Redis flag and raises
TaskCanceledException), so pressing "Cancel" on a running dataflow
test had no effect until every submitted vision call finished or
timed out - several minutes on a busy/slow vision backend.

Three sibling wrappers (vision_figure_parser_docx_wrapper,
vision_figure_parser_pdf_wrapper, vision_figure_parser_figure_xlsx_wrapper)
also swallowed TaskCanceledException into their generic
"except Exception as e" handler that logs a visual-model error and
continues, which would have silently turned a user cancellation into
a logged error and let the pipeline continue.

Fix:
- Replace the unbounded as_completed() wait with wait() using a 1.0s
  timeout and return_when=FIRST_COMPLETED, polling once a second so a
  cancellation is observed promptly instead of only after the whole
  batch drains.
- On TaskCanceledException (or any other exception), cancel every
  future that hasn't started yet and unwind the local ThreadPoolExecutor
  without waiting for stragglers; on normal completion, shut it down
  normally.
- Re-raise TaskCanceledException explicitly in the three wrapper
  functions instead of letting the broad except clause absorb it.
- Guard against an explicit callback=None (kwargs.get with a default
  only substitutes the default when the key is absent, not when its
  value is None).

Note: futures that already started (their HTTP call to the vision
backend is in flight) cannot be forcibly aborted - concurrent.futures
has no API for that. This change stops new work from starting once a
cancellation is observed; already-in-flight requests still run to
completion or their own timeout.

Verified against a live RAGFlow + Ollama deployment: before this
change, cancelling a dataflow test run with several pending figures
left the backend logging vision requests for 3+ minutes with no
visible effect from the Cancel button. After this change, the same
scenario surfaced "Task ... has been canceled" and TaskCanceledException
in the task log and transitioned the task to canceled within about a
minute, bounded by the already-in-flight requests' own timeout.
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 16, 2026
@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Figure parser wrappers now re-raise task cancellations distinctly. DOCX and vision parsing use incremental completion handling, progress callbacks, and explicit cancellation of pending futures during errors.

Changes

Figure parser concurrency

Layer / File(s) Summary
Cancellation propagation in parser wrappers
deepdoc/parser/figure_parser.py
Execution imports use wait and FIRST_COMPLETED, while DOCX, XLSX, and PDF wrappers re-raise TaskCanceledException separately from generic failures.
Incremental parallel result processing
deepdoc/parser/figure_parser.py
Naive DOCX parsing and VisionFigureParser.__call__ process completed futures incrementally, invoke callbacks after progress, and cancel pending work on errors; falsy callbacks now use the default callback.

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

Suggested reviewers: euvre, wangq8

Poem

A rabbit watched the futures race,
Then gathered each in ordered place.
“If cancel comes hopping through,”
“We’ll stop the pending queue!”
Callbacks twinkle, tasks make haste.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: cancellation handling for vision figure futures.
Description check ✅ Passed The description clearly explains the problem, fix, limitations, and testing, though it uses different section headings than the template.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@deepdoc/parser/figure_parser.py`:
- Around line 306-307: Update the description assignment in the figure parsing
flow to keep self.descriptions[figure_num] as a list. When txt is present,
prepend it as a separate list element before the existing descriptions rather
than joining them into a string, preserving the schema and ensuring a delimiter
between the vision text and caption.
🪄 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: 1196ca62-10c4-4ff5-a8c8-4cdda807fbd9

📥 Commits

Reviewing files that changed from the base of the PR and between bd485db and 51bc113.

📒 Files selected for processing (1)
  • deepdoc/parser/figure_parser.py

Comment on lines +306 to +307
if txt:
self.descriptions[figure_num] = txt + "\n".join(self.descriptions[figure_num])

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.

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Preserve list type for figure descriptions to maintain schema contract.

Assigning a concatenated string to self.descriptions[figure_num] breaks the expected data schema where descriptions must be a list (enforced by assertions earlier in the file and strictly relied upon by filters like is_figure_item on line 123). If the description is transformed into a string, downstream consumers will fail to recognize or process the boosted figures correctly.

Additionally, the current string concatenation txt + "\n".join(...) lacks a delimiter, merging the vision output directly into the existing caption without spaces. Prepending the new text as an element to the list solves both issues.

🐛 Proposed fix to maintain the list structure
-                    if txt:
-                        self.descriptions[figure_num] = txt + "\n".join(self.descriptions[figure_num])
+                    if txt:
+                        self.descriptions[figure_num] = [txt] + self.descriptions[figure_num]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if txt:
self.descriptions[figure_num] = txt + "\n".join(self.descriptions[figure_num])
if txt:
self.descriptions[figure_num] = [txt] + self.descriptions[figure_num]
🤖 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 `@deepdoc/parser/figure_parser.py` around lines 306 - 307, Update the
description assignment in the figure parsing flow to keep
self.descriptions[figure_num] as a list. When txt is present, prepend it as a
separate list element before the existing descriptions rather than joining them
into a string, preserving the schema and ensuring a delimiter between the vision
text and caption.

@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM. @yuzhichang pls have a second eye check.

@yuzhichang yuzhichang added the ci Continue Integration label Sep 2, 2026
@codecov

codecov Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 39.04%. Comparing base (4518a58) to head (51bc113).
⚠️ Report is 1557 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##             main   #17014       +/-   ##
===========================================
- Coverage   93.16%   39.04%   -54.13%     
===========================================
  Files          10       54       +44     
  Lines         717    14947    +14230     
  Branches      118      118               
===========================================
+ Hits          668     5836     +5168     
- Misses         29     9085     +9056     
- Partials       20       26        +6     

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

@yuzhichang
yuzhichang merged commit b85efcf into infiniflow:main Sep 2, 2026
14 of 18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants