Skip to content

fix: optimize knowledge compilation LLM behavior and PageIndex ordering - #17270

Merged
wangq8 merged 6 commits into
infiniflow:mainfrom
buua436:b117
Jul 23, 2026
Merged

wangq8 merged 6 commits into
infiniflow:mainfrom
buua436:b117

Conversation

@buua436

@buua436 buua436 commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

This PR disables model reasoning during knowledge compilation to reduce unnecessary generation overhead.

It also ensures PageIndex entities are ordered according to the document chunk order, instead of relying on optional position metadata.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 23, 2026
@buua436
buua436 requested review from KevinHuSh and wangq8 July 23, 2026 02:26
@dosubot dosubot Bot added 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jul 23, 2026
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: be1fa403-939d-4a0e-acb5-463d1227b70a

📥 Commits

Reviewing files that changed from the base of the PR and between 67ebb19 and 58b99da.

📒 Files selected for processing (4)
  • api/apps/restful_apis/chunk_api.py
  • rag/advanced_rag/knowlege_compile/dataset_nav.py
  • rag/advanced_rag/knowlege_compile/raptor.py
  • rag/advanced_rag/knowlege_compile/structure.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • rag/advanced_rag/knowlege_compile/dataset_nav.py
  • api/apps/restful_apis/chunk_api.py
  • rag/advanced_rag/knowlege_compile/structure.py

📝 Walkthrough

Walkthrough

The changes add model-aware LLM generation configuration across knowledge compilation workflows, normalize structure type aliases, constrain PageIndex batching, order PageIndex response entities by document chunks, and fix single-string group ID handling.

Changes

Knowledge compilation and PageIndex behavior

Layer / File(s) Summary
Model-aware generation configuration
rag/advanced_rag/knowlege_compile/_common.py
Adds model-specific reasoning controls and applies them to ambiguous-pair disambiguation.
Generation configuration propagation
rag/advanced_rag/knowlege_compile/dataset_nav.py, rag/advanced_rag/knowlege_compile/raptor.py, rag/advanced_rag/knowlege_compile/structure.py, rag/advanced_rag/knowlege_compile/wiki.py
Routes dataset, RAPTOR, structure, and wiki LLM calls through the shared configuration helper.
Structure aliases and PageIndex batching
rag/advanced_rag/knowlege_compile/structure.py
Normalizes graph-related structure aliases and caps PageIndex chunk batches at one.
PageIndex entity ordering
api/apps/restful_apis/chunk_api.py
Orders PageIndex entities according to document chunk order, retaining the existing order when ordering fails.
Template group input normalization
rag/advanced_rag/knowlege_compile/runner.py
Treats a single string group ID as one group rather than iterating over its characters.

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

Suggested reviewers: kevinhush

Poem

I’m a rabbit with configs in tow,
Making each model’s reasoning flow.
Chunks line up neat, aliases agree,
Group IDs hop as one, happily.
“PageIndex is tidy!” I cheer with glee.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 72.00% 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 is concise and accurately summarizes the two main changes: knowledge compilation LLM behavior and PageIndex ordering.
Description check ✅ Passed The description covers the problem and the bug-fix type, which satisfies the template’s summary intent despite using a different heading.
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: 3

🧹 Nitpick comments (2)
rag/advanced_rag/knowlege_compile/_common.py (1)

51-73: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the new helper private and observable.

knowledge_compile_gen_conf is internal-only; all callers already alias it as _knowledge_compile_gen_conf. Rename the definition/imports to the private form and add a debug-level log for the selected model-control branch so the new reasoning behavior is diagnosable.

As per coding guidelines, **/*.py: Add logging for new flows; **/*: Reduce public surface area by making helpers private or internal when possible.

🤖 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/advanced_rag/knowlege_compile/_common.py` around lines 51 - 73, Rename
knowledge_compile_gen_conf to _knowledge_compile_gen_conf consistently in its
definition and imports, preserving all existing callers. Add a debug-level log
within the helper that identifies the selected model-control branch and relevant
model name, including the DeepSeek, Qwen, and default reasoning-control paths.

Source: Coding guidelines

rag/advanced_rag/knowlege_compile/structure.py (1)

736-741: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log the PageIndex single-chunk mode.

This silently changes PageIndex request fan-out and latency by forcing batch_size_cap=1. Add a debug/info log with the normalized template kind, chunk count, and resulting batch count so operators can diagnose the new flow.

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 `@rag/advanced_rag/knowlege_compile/structure.py` around lines 736 - 741, Add a
debug or info log around the _build_chunk_batches call when PageIndex
single-chunk mode is selected, including the normalized template kind, input
chunk count, and resulting packed_batches count. Reuse the existing module
logger and preserve the current batch_size_cap behavior.

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/apps/restful_apis/chunk_api.py`:
- Around line 812-829: The chunk-order lookup around settings.retriever.search
currently caps results at 10,000, so larger documents produce incomplete
ordering. Update this retrieval to paginate or cursor through all ordered chunk
IDs, accumulating every result before populating chunk_order; preserve the
existing document, dataset, sorting, and compile_kwd filters.

In `@rag/advanced_rag/knowlege_compile/raptor.py`:
- Around line 220-222: Update the RAPTOR generation flow around the cache
lookup, async_chat call, and cache storage to compute
knowledge_compile_gen_conf(self._llm_model, gen_conf) once as
effective_gen_conf. Use effective_gen_conf consistently for cache reads, the
async_chat generation call, and writes, preserving the existing cache behavior
otherwise.

In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 88-89: Update the function containing the group_ids normalization
to document and annotate group_ids as accepting either a string or a list of
strings, while preserving the conversion of scalar strings to a one-item list.
Add a debug log for the scalar-input path without including any group identifier
values.

---

Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/_common.py`:
- Around line 51-73: Rename knowledge_compile_gen_conf to
_knowledge_compile_gen_conf consistently in its definition and imports,
preserving all existing callers. Add a debug-level log within the helper that
identifies the selected model-control branch and relevant model name, including
the DeepSeek, Qwen, and default reasoning-control paths.

In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 736-741: Add a debug or info log around the _build_chunk_batches
call when PageIndex single-chunk mode is selected, including the normalized
template kind, input chunk count, and resulting packed_batches count. Reuse the
existing module logger and preserve the current batch_size_cap behavior.
🪄 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 Plus

Run ID: 45987fb0-8afa-4e8e-8234-6c83769ef19f

📥 Commits

Reviewing files that changed from the base of the PR and between a5aa948 and b953c62.

📒 Files selected for processing (7)
  • api/apps/restful_apis/chunk_api.py
  • rag/advanced_rag/knowlege_compile/_common.py
  • rag/advanced_rag/knowlege_compile/dataset_nav.py
  • rag/advanced_rag/knowlege_compile/raptor.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/advanced_rag/knowlege_compile/wiki.py

Comment on lines +812 to +829
chunk_res = await settings.retriever.search(
{
"doc_ids": [document_id],
"page": 1,
"size": 10000,
"question": "",
"sort": True,
"must_not": {"exists": "compile_kwd"},
},
index_name,
[dataset_id],
emb_mdl=None,
highlight=True,
)
for index, chunk_id in enumerate(chunk_res.ids or []):
chunk_id = str(chunk_id)
if chunk_id:
chunk_order[chunk_id] = index

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Load all document chunk IDs before sorting PageIndex entities.

This retrieves only the first 10,000 chunks. For larger documents, entities linked to later chunks are treated as unmatched and sorted to the end, rather than by document order. Paginate/cursor through the complete ordered result set (or use an ordered chunk-ID query without this cap) before building chunk_order.

🤖 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/chunk_api.py` around lines 812 - 829, The chunk-order
lookup around settings.retriever.search currently caps results at 10,000, so
larger documents produce incomplete ordering. Update this retrieval to paginate
or cursor through all ordered chunk IDs, accumulating every result before
populating chunk_order; preserve the existing document, dataset, sorting, and
compile_kwd filters.

Comment on lines +220 to +222
response = await self._llm_model.async_chat(
system, history, knowledge_compile_gen_conf(self._llm_model, gen_conf)
)

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 | 🟠 Major | ⚡ Quick win

Key RAPTOR cache entries by the effective generation configuration.

Line [213] looks up the cache with raw gen_conf, while Line [220] sends the transformed config and Line [226] stores under raw gen_conf. Existing cache entries can therefore bypass the new reasoning-disable setting. Compute effective_gen_conf once and use it for cache lookup, async_chat, and cache storage.

Proposed fix
+        effective_gen_conf = knowledge_compile_gen_conf(self._llm_model, gen_conf)
-        cached = await thread_pool_exec(get_llm_cache, self._llm_model.llm_name, system, history, gen_conf)
+        cached = await thread_pool_exec(
+            get_llm_cache, self._llm_model.llm_name, system, history, effective_gen_conf
+        )

         response = await self._llm_model.async_chat(
-            system, history, knowledge_compile_gen_conf(self._llm_model, gen_conf)
+            system, history, effective_gen_conf
         )

-        await thread_pool_exec(set_llm_cache, self._llm_model.llm_name, system, response, history, gen_conf)
+        await thread_pool_exec(
+            set_llm_cache, self._llm_model.llm_name, system, response, history, effective_gen_conf
+        )
📝 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
response = await self._llm_model.async_chat(
system, history, knowledge_compile_gen_conf(self._llm_model, gen_conf)
)
effective_gen_conf = knowledge_compile_gen_conf(self._llm_model, gen_conf)
response = await self._llm_model.async_chat(
system, history, effective_gen_conf
)
🤖 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/advanced_rag/knowlege_compile/raptor.py` around lines 220 - 222, Update
the RAPTOR generation flow around the cache lookup, async_chat call, and cache
storage to compute knowledge_compile_gen_conf(self._llm_model, gen_conf) once as
effective_gen_conf. Use effective_gen_conf consistently for cache reads, the
async_chat generation call, and writes, preserving the existing cache behavior
otherwise.

Comment on lines +88 to +89
if isinstance(group_ids, str):
group_ids = [group_ids]

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Document and log the new scalar-input path.

This branch widens group_ids from list-only input to str | list[str], but the docstring does not reflect that contract and the new flow has no logging. Update the annotation/docstring and add a debug log without exposing group identifiers.

🤖 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/advanced_rag/knowlege_compile/runner.py` around lines 88 - 89, Update the
function containing the group_ids normalization to document and annotate
group_ids as accepting either a string or a list of strings, while preserving
the conversion of scalar strings to a one-item list. Add a debug log for the
scalar-input path without including any group identifier values.

Source: Coding guidelines

@buua436
buua436 marked this pull request as draft July 23, 2026 02:38
@buua436
buua436 marked this pull request as ready for review July 23, 2026 02:38
@yingfeng yingfeng added the ci Continue Integration label Jul 23, 2026

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

Good PR addressing two important issues. Here is my review:

Reasoning control for knowledge compilation (knowledge_compile_gen_conf)

This is the right approach — knowledge compilation is extraction/summarization, not creative generation, so disabling reasoning saves both tokens and latency.

Suggestions:

  • The model name check "deepseek-v4" in model_name is a bit broad — it matches any model variant like deepseek-v4-pro. Consider whether this is intentional (all deepseek-v4* models use the same thinking API) or if a more precise match is warranted. For now it is fine.
  • Consider adding a brief module-level comment explaining why reasoning is disabled (token savings, latency, extraction tasks don not benefit from reasoning).

PageIndex ordering (chunk_api.py)

The approach of querying ES for the natural chunk order is sound.

Suggestions:

  • The size: 10000 is reasonable but consider adding a comment documenting the limit and its implications for very large documents.
  • The exception handler silently continues — this is correct for this use case but ensure the log message is clear enough for debugging if ordering goes wrong.
  • The entity_position sort using (min(chunk_indexes), fallback) for tiebreaking is clean.

Structure aliases (_STRUCT_TYPE_ALIASES)

Good QoL improvement allowing "graph" and "knowledge_graph" as aliases for "hypergraph".

batch_size_cap=1 for page_index

Each chunk processed individually for page_index extraction — correct, since page index entities should be per-chunk.

runner.py string-to-list fix

Simple defensive fix, LGTM.

Overall: Well-structured PR with clean separation of concerns. No regressions identified. The changes are consistent across all compilation paths (structure, wiki, dataset_nav, raptor). Approving with the minor documentation suggestions above.

@codecov

codecov Bot commented Jul 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (d19a036) to head (58b99da).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #17270      +/-   ##
==========================================
- Coverage   94.56%   90.65%   -3.91%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      650      -28     
- Misses         25       39      +14     
- Partials       14       28      +14     

☔ 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 e3e2d0a into infiniflow:main Jul 23, 2026
3 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 🌈 python Pull requests that update Python code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants