Skip to content

Fix PageIndex is not working - #16704

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-PageIndex-is-not-working
Jul 7, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-PageIndex-is-not-working

Conversation

@wangq8

@wangq8 wangq8 commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

Follow on PR #16515

@wangq8 wangq8 added the ci Continue Integration label Jul 7, 2026
@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Jul 7, 2026
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added conditional asynchronous table-of-contents (TOC) extraction to standard chunking flow. When the parser is "naive" and TOC extraction is enabled in config, TOC generation runs in a background thread concurrently with chunking, then is awaited and its result inserted via post-processing.

Changes

Async TOC generation

Layer / File(s) Summary
Schedule and consume async TOC task
rag/svr/task_executor_refactor/task_handler.py
Creates a background thread task invoking _build_toc when parser is naive and TOC extraction is enabled, then awaits it via _process_toc_thread after indexing, recording the resulting toc_chunk in context and inserting it via post_processor.insert_toc_chunk.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
    participant TaskHandler
    participant BuildTOC as _build_toc (thread)
    participant PostProcessor

    TaskHandler->>TaskHandler: Check parser_id == "naive" and toc_extraction enabled
    TaskHandler->>BuildTOC: asyncio.to_thread(_build_toc, ctx, chunks, progress_cb)
    TaskHandler->>TaskHandler: Continue chunking/embedding
    TaskHandler->>BuildTOC: _process_toc_thread awaits toc_thread
    BuildTOC-->>TaskHandler: toc_chunk
    TaskHandler->>TaskHandler: Record toc_chunk in recording_context
    TaskHandler->>PostProcessor: insert_toc_chunk(toc_chunk)
Loading

Poem

A rabbit hops while threads compute,
A table of contents, quiet and cute 🐇
While chunks embed and dance about,
TOC sneaks in without a shout,
Then stitched in place when work is through—
Another burrow, tidy and new! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is too vague and only references a follow-on PR, without the required Summary or context. Add a Summary section that explains the issue, background, and what this PR changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is related to the change and identifies the user-facing fix, even if phrased a bit awkwardly.
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

Caution

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

⚠️ Outside diff range comments (2)
rag/svr/task_executor_refactor/task_handler.py (2)

593-613: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

toc_thread leaked on early-return paths.

If the task is canceled (line 603-606) or chunk insertion fails (line 610-613), the function returns before the toc_thread background task at line 622 is ever awaited or cancelled. The scheduled _build_toc thread keeps running orphaned, consuming a thread-pool slot, and any exception it raises becomes an unretrieved-task-exception warning instead of being handled.

🔧 Proposed fix: clean up toc_thread before early returns
         if ctx.has_canceled_func(task_id):
             abort_doc_chunking_counter(task_doc_id)
             ctx.progress_cb(-1, msg="Task has been canceled.")
+            await self._process_toc_thread(toc_thread)
             return

         insert_result = await chunk_service.insert_chunks(task_id, task_tenant_id, task_dataset_id, chunks)

         if not insert_result:
             ctx.recording_context.record("insertion_result", "failed")
             abort_doc_chunking_counter(task_doc_id)
+            await self._process_toc_thread(toc_thread)
             return
🤖 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 `@rag/svr/task_executor_refactor/task_handler.py` around lines 593 - 613, The
task handler leaves toc_thread running on early exits, so update the logic
around ctx.has_canceled_func and the insert_chunks failure branch to clean up
the scheduled task before returning. In task_handler.py, ensure _build_toc
started via asyncio.create_task(asyncio.to_thread(...)) is either awaited or
cancelled and drained when the task is canceled or insert_chunks returns false,
so the later cleanup path is not skipped and no orphaned background task
remains.

677-685: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

asyncio.to_thread cancellation is best-effort only — cancelling the wrapper task only stops awaiting _build_toc; the worker thread keeps running to completion. If that’s intended, document the trade-off; otherwise make the work cooperatively cancellable.

🤖 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 `@rag/svr/task_executor_refactor/task_handler.py` around lines 677 - 685, The
_process_toc_thread helper only cancels the asyncio wrapper and not the
underlying work, so clarify the intended behavior or make _build_toc
cooperatively cancellable. Update _process_toc_thread and the _build_toc call
path in TaskHandler so cancellation is either explicitly documented as
best-effort or propagated via a cancellation-aware mechanism that lets the
thread stop early.
🧹 Nitpick comments (1)
rag/svr/task_executor_refactor/task_handler.py (1)

593-596: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No logging for the new async TOC scheduling/consumption flow.

Scheduling (line 593-596) and consuming (line 622-626) the background TOC task have no logging.info/logging.warning at the handler level, unlike other flows in this file (e.g., Line 555, Line 590-591). Add a log line when the task is scheduled and when the TOC chunk is inserted or skipped, to aid debugging of this async path.

As per coding guidelines, **/*.py: "Add logging for new flows".

Also applies to: 622-626

🤖 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 `@rag/svr/task_executor_refactor/task_handler.py` around lines 593 - 596, The
new async TOC flow in task_handler lacks handler-level logging, so add logging
around both the scheduling and consumption steps. In the TOC scheduling block
inside the task handler, emit a logging.info when asyncio.create_task is used
for _build_toc; then in the code that awaits or consumes toc_thread, log whether
the TOC chunk was inserted or skipped with logging.info or logging.warning. Use
the existing task handler flow around self._build_toc, toc_thread, and the TOC
insertion logic so the messages are easy to trace alongside the other logged
branches in this file.

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 `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 622-626: The TOC step is currently allowed to fail the whole
chunking run, even after chunk embedding/insertion has succeeded. Update
_process_toc_thread (and the related toc_thread handling in
_run_standard_chunking / the 677-686 path) so TOC extraction is best-effort:
catch exceptions from _build_toc / run_toc_from_text, log or record the failure,
and return without propagating the error so abort_doc_chunking_counter is not
triggered for an otherwise successful task.

---

Outside diff comments:
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 593-613: The task handler leaves toc_thread running on early
exits, so update the logic around ctx.has_canceled_func and the insert_chunks
failure branch to clean up the scheduled task before returning. In
task_handler.py, ensure _build_toc started via
asyncio.create_task(asyncio.to_thread(...)) is either awaited or cancelled and
drained when the task is canceled or insert_chunks returns false, so the later
cleanup path is not skipped and no orphaned background task remains.
- Around line 677-685: The _process_toc_thread helper only cancels the asyncio
wrapper and not the underlying work, so clarify the intended behavior or make
_build_toc cooperatively cancellable. Update _process_toc_thread and the
_build_toc call path in TaskHandler so cancellation is either explicitly
documented as best-effort or propagated via a cancellation-aware mechanism that
lets the thread stop early.

---

Nitpick comments:
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 593-596: The new async TOC flow in task_handler lacks
handler-level logging, so add logging around both the scheduling and consumption
steps. In the TOC scheduling block inside the task handler, emit a logging.info
when asyncio.create_task is used for _build_toc; then in the code that awaits or
consumes toc_thread, log whether the TOC chunk was inserted or skipped with
logging.info or logging.warning. Use the existing task handler flow around
self._build_toc, toc_thread, and the TOC insertion logic so the messages are
easy to trace alongside the other logged branches in this file.
🪄 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: 8c2af502-451d-48e0-bc46-2071fba29ca5

📥 Commits

Reviewing files that changed from the base of the PR and between f8f049e and e70cfae.

📒 Files selected for processing (1)
  • rag/svr/task_executor_refactor/task_handler.py

Comment on lines +622 to +626
toc_chunk = await self._process_toc_thread(toc_thread)
if toc_chunk:
ctx.recording_context.record("toc_chunk", [toc_chunk])
await post_processor.insert_toc_chunk(toc_chunk, chunk_service)

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

TOC generation failure aborts an already-successful chunking task.

_process_toc_thread has no except clause, so any exception raised inside _build_toc (e.g., an LLM error from run_toc_from_text) propagates out of await toc_thread and up through _run_standard_chunking, which treats it as a full task failure (calling abort_doc_chunking_counter and re-raising) even though chunks were already embedded and inserted successfully at line 608-614. TOC extraction should be best-effort and not able to fail an otherwise-successful indexing run.

🛡️ Proposed fix: isolate TOC failures
     async def _process_toc_thread(self, toc_thread):
         try:
             if toc_thread:
                 return await toc_thread
             else:
                 return None
+        except Exception:
+            logging.exception("TOC generation failed; continuing without TOC chunk")
+            return None
         finally:
             if toc_thread is not None and not toc_thread.done():
                 toc_thread.cancel()

Also applies to: 677-686

🤖 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 `@rag/svr/task_executor_refactor/task_handler.py` around lines 622 - 626, The
TOC step is currently allowed to fail the whole chunking run, even after chunk
embedding/insertion has succeeded. Update _process_toc_thread (and the related
toc_thread handling in _run_standard_chunking / the 677-686 path) so TOC
extraction is best-effort: catch exceptions from _build_toc / run_toc_from_text,
log or record the failure, and return without propagating the error so
abort_doc_chunking_counter is not triggered for an otherwise successful task.

@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 (9eba452) to head (e70cfae).
⚠️ Report is 11 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16704   +/-   ##
=======================================
  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 merged commit 705754e into infiniflow:main Jul 7, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant