Skip to content

feat: add LLM-guided semantic rechunking for knowledge compilation - #17546

Merged
wangq8 merged 7 commits into
infiniflow:mainfrom
buua436:b127
Jul 31, 2026
Merged

wangq8 merged 7 commits into
infiniflow:mainfrom
buua436:b127

Conversation

@buua436

@buua436 buua436 commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Knowledge compilation currently relies on parser chunk boundaries, which can split semantically related content and reduce extraction quality.

This PR adds LLM-guided semantic rechunking for pipeline compilation. The first template with rechunk=true determines the semantic boundaries, and subsequent templates reuse the generated chunks with rechunking disabled.

What changed?

  • Added semantic rechunking based on the knowledge compilation task.
  • Preserved structured parser records such as tables and images.
  • Added temporary positional chunk IDs for compact LLM responses.
  • Replaced original chunks with the formal semantic chunks after rechunking.
  • Ensured later templates consume the first template's rechunked output.
  • Kept Tree compilation on its existing path.
  • Added frontend configuration and localized descriptions for rechunking.
  • Added DeepSeek V4 reasoning and output-token configuration for knowledge compilation.

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Refactor (no functional change)

@buua436 buua436 added the ci Continue Integration label Jul 29, 2026
@buua436
buua436 marked this pull request as ready for review July 29, 2026 11:42
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. 🧰 typescript Pull requests that update Typescript code labels Jul 29, 2026
@buua436
buua436 requested a review from wangq8 July 29, 2026 11:42
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Rechunking is configurable for non-Tree compilation templates. The compiler normalizes parser output, stages rechunking, and preserves formal chunks through extraction and batching. DeepSeek token handling and knowledge-graph batch limits are also updated.

Changes

Rechunked knowledge compilation

Layer / File(s) Summary
Template rechunk configuration
web/src/interfaces/..., web/src/locales/*, web/src/pages/user-setting/compilation-templates/..., api/db/init_data/compilation_templates/*
Adds rechunk contracts, defaults, payload handling, localized labels, conditional controls, and built-in rules for non-Tree templates.
Compiler normalization and staged execution
rag/flow/compiler/compiler.py
Normalizes supported formats, splits and merges content, preserves atomic structures, assigns IDs after normalization, and stages templates around rechunking.
Hypergraph rechunk extraction
rag/advanced_rag/knowlege_compile/structure.py
Groups source chunks, creates UUID-backed chunks, remaps references, and propagates formal chunks through batch aggregation.
Compilation result handling and model parameters
rag/advanced_rag/knowlege_compile/runner.py, rag/llm/chat_model.py, rag/advanced_rag/knowlege_compile/_common.py, rag/svr/task_executor_refactor/chunk_post_processor.py
Aggregates rechunked results, applies knowledge-graph batching limits, updates DeepSeek token settings, and adjusts the helper import boundary.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant TemplateConfig
  participant Compiler
  participant StructureCompiler
  participant LLM
  participant Runner
  TemplateConfig->>Compiler: Submit rechunk configuration
  Compiler->>Compiler: Normalize and stage chunks
  Compiler->>StructureCompiler: Extract grouped chunks and relations
  StructureCompiler->>LLM: Request source-chunk grouping
  LLM-->>StructureCompiler: Return temporary groups and extraction data
  StructureCompiler-->>Compiler: Return formal chunks and compiled rows
  Compiler->>Runner: Aggregate rechunked chunks
  Runner->>Runner: Apply token-bounded batching
Loading

Possibly related PRs

Suggested reviewers: 6ba3i, eugenebackdev, kevinhush

Poem

A rabbit groups each chunk in line,
With UUIDs set in neat design.
Tokens bound the batching flow,
DeepSeek gets its limit too,
Formal chunks now align.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% 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 change: LLM-guided semantic rechunking for knowledge compilation.
Description check ✅ Passed The description explains the problem, implementation, scope, and change type, although it does not use the template's Summary 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.

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

Thanks for this PR! The LLM-guided semantic rechunking is a nice addition to knowledge compilation. I reviewed the full diff (~700 lines across 14 files) and have the following feedback:

Overall

Clean implementation with good separation of concerns. The chunk normalization pipeline (_normalize_upstream_chunks) handles multiple output formats well, and the _RechunkedDocs subclass is a neat way to thread rechunked data through the existing batching infrastructure without changing the signature of _struct_process_batch.

Issues

1. Undocumented knowledge_graph behavioral change (runner.py L493-495)

The special case for knowledge_graph templates was removed without mention in the PR description:

# removed:
if template_kinds[template_id] == "knowledge_graph":
    await _submit_one(incoming_batch, template_id, parser_cfg)
    continue

Previously, knowledge_graph templates bypassed the dynamic token-budget batching and submitted the full incoming batch directly. Now they go through the same buffering path as other templates. This changes batch boundaries for all knowledge_graph users and could affect extraction quality (e.g., entities that span chunk boundaries may be split across different LLM calls). Was this intentional? If yes, please document the rationale in the PR description. If no, this should be restored.

2. Empty source chunks in _formalize_rechunked_chunks (compiler.py)

When _formalize_rechunked_chunks finds no matching source chunk for any source_id in a rechunked group:

source = next((originals[source_id] for source_id in source_ids if source_id in originals), {})

source becomes an empty dict {}. The resulting formalized chunk will have id and text from the rechunk data, but will be missing fields like doc_type_kwd, positions, etc. Can this happen in practice? Consider adding a guard: if not source, either skip the group or log a warning.

3. _is_atomic_json_record pipe-character scan (compiler.py)

has_markdown_table = any("|" in lines[index] and Compiler._is_markdown_table_separator(lines[index + 1]) ...)

The "|" in lines[index] check is broad — any line containing a pipe character followed by a separator line will be treated as a table. The separator check mitigates false positives, but consider using a regex like r"^\s*\|" to only match lines that actually start a table row, which would be more precise.

4. DeepSeek max_tokens workaround (chat_model.py)

The workaround is correct — LiteLLM does not translate max_completion_tokens for DeepSeek, and the provider falls back to 8192. However, this silently overrides max_completion_tokens for all DeepSeek calls, not just knowledge compilation. The 65536 value set in _common.py is then carried through as max_tokens. Consider adding a brief inline comment explaining the chain (from _common.py → _clean_conf → DeepSeek API) so future maintainers understand why max_completion_tokens disappears from gen_conf for DeepSeek.

5. source_texts memory in _struct_extract_hypergraph (structure.py)

source_texts = {match.group(1).strip(): match.group(2).strip() for match in re.finditer(r"\[CHUNK_ID:\s*([^\]]+)\]\n(.*?)\n\[END_CHUNK\]", text, flags=re.DOTALL)}

This captures all chunk text into a dict (text is already in memory as combined_text, so no extra copies), but the regex .*? between [CHUNK_ID:] and [END_CHUNK] with re.DOTALL could match very large strings. For batches of large chunks, consider adding a comment noting this is bounded by DOC_STRUCTURE_COMPILE_BATCH_CHUNKS.

Nitpicks

  • The _PARSER_CANDIDATE_TOKEN_SIZE = 128 when rechunking is intentionally small to give the LLM fine-grained chunks to group. Worth a brief comment explaining this design choice.
  • Good that Tree templates continue on their existing path without rechunking interference.
  • The positional ID scheme (t1, t2, ...) is clever — much more compact for the LLM response than full hash IDs.

Frontend

  • SwitchFormField import: @/components/switch-fom-field — the "fom" typo is pre-existing in the codebase, not introduced here. No action needed.
  • Localization strings look correct for both en and zh.
  • The rechunk boolean is properly handled in isConfigMetaKey and transformTemplateToPayload.

No blocking issues — the knowledge_graph change in runner.py is the one thing I would clarify before merging.

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

🧹 Nitpick comments (3)
rag/advanced_rag/knowlege_compile/structure.py (2)

454-499: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No logging for the new rechunk grouping flow.

When the model returns unusable/partial chunks, every unclaimed source silently becomes its own singleton group (Lines 472-474) with no trace of how many groups the LLM proposed versus how many were synthesized. A single debug/info line (group count, unclaimed count) would make rechunk quality diagnosable in production. As per coding guidelines for **/*.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 454 - 499, Add a
debug or info log in the rechunk grouping flow around valid_groups and the
unclaimed-source fallback, reporting the number of model-proposed groups,
accepted groups, and synthesized singleton groups. Use the module’s existing
logger and preserve the current grouping behavior.

Source: Coding guidelines


529-536: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Hoist set(chunk_id_map.values()) out of the loop.

The allowed-id set is rebuilt for every edge and again for every candidate id.

♻️ Proposed refactor
     if rechunk:
+        allowed_ids = set(chunk_id_map.values())
         for edge in edges:
             raw_ids = edge.get("source_chunk_ids")
             if isinstance(raw_ids, str):
                 raw_ids = [raw_ids]
             if isinstance(raw_ids, list):
-                edge["source_chunk_ids"] = [item for item in raw_ids if isinstance(item, str) and item in set(chunk_id_map.values())]
+                edge["source_chunk_ids"] = [item for item in raw_ids if isinstance(item, str) and item in allowed_ids]
🤖 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 529 - 536, In
the rechunk branch, update the loop surrounding edge processing to build the
allowed source-ID set from chunk_id_map.values() once before iterating over
edges, then reuse that set when filtering each edge’s source_chunk_ids. Keep the
existing string normalization and filtering behavior unchanged.
rag/advanced_rag/knowlege_compile/_common.py (1)

59-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Hardcoded 65536 unconditionally overrides a caller-supplied limit.

Callers that already set max_completion_tokens/max_tokens for a specific compile step lose it here. Consider conf.setdefault("max_completion_tokens", DEEPSEEK_V4_MAX_COMPLETION_TOKENS) with a named module constant so the value is discoverable and caller intent wins.

🤖 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 59 - 60, Update
the deepseek-v4 branch in the configuration logic to preserve any
caller-supplied max_completion_tokens or max_tokens limit, using setdefault with
a named module-level DEEPSEEK_V4_MAX_COMPLETION_TOKENS constant for the default
value.
🤖 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/advanced_rag/knowlege_compile/runner.py`:
- Line 313: The aggregate record currently exposes full rechunked chunk text
through record and progress_cb; update the aggregation around agg_infos to keep
rechunked_chunks in a separate per-template map, exclude it from
reported/progress aggregates, and merge it only into the final returned result.

In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 835-837: Update the failure returns in the structure compilation
flow to always use the declared _RechunkedDocs type: in the batch extraction
exception path, return an empty _RechunkedDocs(), and in the embedding and
count-mismatch failure paths return
_RechunkedDocs(rechunked_chunks=formal_chunks) so computed groups are preserved.
- Around line 978-985: Update _flatten so rechunked_chunks are collected from
every non-None batch, including falsy _RechunkedDocs instances with no document
rows. Remove the truthiness guard around br, preserve out.extend only when rows
exist, and always extend formal_chunks from br.rechunked_chunks before returning
_RechunkedDocs.

In `@rag/flow/compiler/compiler.py`:
- Around line 584-590: The rechunking path in the compiler must not expose
positional t{index} IDs when formal_chunks is empty. Preserve the original
document-scoped hashed IDs in chunks, using positional aliases only for
compilation, or restore the hashes before set_output("chunks") when no formal
chunks are returned; keep the existing formal_chunks replacement behavior
unchanged.
- Around line 513-522: Unify the rechunk predicate used by should_rechunk and
first_rechunk_index so raptor.rechunk cannot select candidate-sized chunks
without a corresponding regrouping pass. Reuse _template_requests_rechunk for
staging, while excluding tree templates as required by the existing
unsupported-rechunk behavior, and preserve normal chunk sizing for templates
that will not be regrouped.
- Around line 252-276: Normalize every chunk to include a string "text" value
before it reaches downstream ID generation: in the metadata-only branch of the
records processing flow, set chunk["text"] to an empty string before appending.
Also update the output_format == "chunks" passthrough to coerce missing or
non-string text to an empty string, while preserving valid text and existing
metadata.

In `@rag/llm/chat_model.py`:
- Around line 1689-1702: In the DeepSeek handling around deepseek_max_tokens,
only translate an explicitly provided max_completion_tokens value into
max_tokens; remove the fallback to gen_conf["max_tokens"] so agent UI
configuration is not resurrected. Preserve filtering and cleanup, and validate
any translated value as an integer greater than zero before restoring it.

---

Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/_common.py`:
- Around line 59-60: Update the deepseek-v4 branch in the configuration logic to
preserve any caller-supplied max_completion_tokens or max_tokens limit, using
setdefault with a named module-level DEEPSEEK_V4_MAX_COMPLETION_TOKENS constant
for the default value.

In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 454-499: Add a debug or info log in the rechunk grouping flow
around valid_groups and the unclaimed-source fallback, reporting the number of
model-proposed groups, accepted groups, and synthesized singleton groups. Use
the module’s existing logger and preserve the current grouping behavior.
- Around line 529-536: In the rechunk branch, update the loop surrounding edge
processing to build the allowed source-ID set from chunk_id_map.values() once
before iterating over edges, then reuse that set when filtering each edge’s
source_chunk_ids. Keep the existing string normalization and filtering behavior
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 Plus

Run ID: e98372e2-19a8-482d-9e92-446c512e4d6b

📥 Commits

Reviewing files that changed from the base of the PR and between a586998 and 852de9f.

📒 Files selected for processing (14)
  • rag/advanced_rag/knowlege_compile/_common.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/flow/compiler/compiler.py
  • rag/llm/chat_model.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py
  • web/src/interfaces/database/compilation-template.ts
  • web/src/interfaces/request/compilation-template.ts
  • web/src/locales/en.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx
  • web/src/pages/user-setting/compilation-templates/create-next/utils.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/utils.ts
💤 Files with no reviewable changes (1)
  • rag/svr/task_executor_refactor/chunk_post_processor.py

Comment thread rag/flow/compiler/compiler.py Resolved
Comment thread rag/flow/compiler/compiler.py Resolved
Comment thread rag/flow/compiler/compiler.py Resolved
Comment thread rag/llm/chat_model.py Resolved
@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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

☔ 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 self-requested a review July 31, 2026 03:53

@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/advanced_rag/knowlege_compile/runner.py (1)

501-520: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Stage compilation around the rechunking template.

run_structure_compile_over_batches buffers every template from the same incoming_batch, but only the template whose parser_config.get("rechunk") is true returns rechunked_chunks. Later templates still run against the original chunks, and later templates can re-enable re-chunking because the runner does not inspect the ordering contract. Split execution at the rechunk boundary and feed generated chunks into later templates, or disable re-chunking after the first rechunking template.

🤖 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 501 - 520, Update
run_structure_compile_over_batches to honor the rechunking stage boundary:
identify the first template whose parser_config has rechunk enabled, process
templates through that boundary, replace the current input with its returned
rechunked_chunks, and feed those generated chunks to subsequent templates
without allowing re-chunking again. Ensure later templates no longer consume the
original incoming_batch or re-enable rechunking.
rag/flow/compiler/compiler.py (1)

163-189: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve fenced code blocks as atomic Markdown blocks.

_split_markdown_blocks only detects tables. A fenced code block enters the ordinary-text path and can be split by _slumber_candidates or naive_merge.

Parse fenced code blocks with tables. Mark them as atomic. Exclude them from text splitting and coarse merging.

🤖 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/flow/compiler/compiler.py` around lines 163 - 189, The
_split_markdown_blocks method must also detect fenced code blocks and emit them
as atomic blocks, alongside Markdown tables. Track fence opening and closing
delimiters while scanning lines, flush preceding ordinary text, preserve the
complete fenced block as a single atomic entry, and ensure downstream
_slumber_candidates and naive_merge exclude blocks marked atomic.
🧹 Nitpick comments (4)
rag/advanced_rag/knowlege_compile/runner.py (2)

635-645: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log the rechunking result.

This new flow emits progress_cb(...) messages but no structured application log for the rechunk result. Log the template ID, source chunk count, output chunk count, and compilation counters.

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/runner.py` around lines 635 - 645, Add a
structured application log in the rechunked_chunks branch alongside the existing
progress_cb call, including the template ID, source chunk count, output chunk
count, and compilation counters from agg. Use the module’s established logger
and preserve the existing progress and completion messages.

Source: Coding guidelines


438-442: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add structured logging for the new batching flow.

The new knowledge-graph budget calculation only affects progress behavior indirectly. Add a structured log with the template ID, model context length, and selected batch budget. This will help diagnose context-limit and extraction failures in production.

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/runner.py` around lines 438 - 442, Add
structured logging in the knowledge_graph branch of the batching budget
calculation, including template_id, the model context length (max_length), and
the selected batch budget. Log after computing the bounded result and preserve
the existing min/max calculation and return behavior.

Source: Coding guidelines

rag/flow/compiler/compiler.py (1)

606-641: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add structured logs for staged rechunk execution.

Log the selected first rechunk template, input chunk count, formal chunk count, and later-template count. Do not log chunk text.

This makes rechunk failures and empty formalization results diagnosable.

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/flow/compiler/compiler.py` around lines 606 - 641, Add structured logging
around the staged rechunk flow in _run_templates and its surrounding
first_rechunk_index branch: record the selected first rechunk template, input
chunk count, formal chunk count, and later-template count without including
chunk text. Ensure logs also cover empty formalization results, using the
module’s existing logging mechanism and preserving the current execution
behavior.

Source: Coding guidelines

web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx (1)

208-227: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared rechunk configuration fields.

Both flows now maintain identical rechunk UI logic. Extract one internal component that accepts the template index.

  • web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx#L208-L227: replace the local switch and rules field with the shared component.
  • web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx#L201-L220: replace the duplicate local switch and rules field with the shared component.

As per coding guidelines, "During review, remove deprecated, legacy, and compatibility-only code; collapse duplicate implementations."

🤖 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
`@web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx`
around lines 208 - 227, Extract the duplicated rechunk switch and conditional
rechunk_rules field into one internal component that accepts the template index
and preserves the existing form names, labels, tooltips, placeholder, and
visibility behavior. Replace the local implementations in
web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx:208-227
and
web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx:201-220
with this shared component; both sites require direct replacement.

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/advanced_rag/knowlege_compile/runner.py`:
- Around line 635-645: Update the rechunked_chunks branch in the compilation
progress reporting to include inserted, updated, and duplicates_dropped from agg
alongside the existing source-to-output chunk summary. Preserve the existing
completion message for runs without rechunking.

---

Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 501-520: Update run_structure_compile_over_batches to honor the
rechunking stage boundary: identify the first template whose parser_config has
rechunk enabled, process templates through that boundary, replace the current
input with its returned rechunked_chunks, and feed those generated chunks to
subsequent templates without allowing re-chunking again. Ensure later templates
no longer consume the original incoming_batch or re-enable rechunking.

In `@rag/flow/compiler/compiler.py`:
- Around line 163-189: The _split_markdown_blocks method must also detect fenced
code blocks and emit them as atomic blocks, alongside Markdown tables. Track
fence opening and closing delimiters while scanning lines, flush preceding
ordinary text, preserve the complete fenced block as a single atomic entry, and
ensure downstream _slumber_candidates and naive_merge exclude blocks marked
atomic.

---

Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 635-645: Add a structured application log in the rechunked_chunks
branch alongside the existing progress_cb call, including the template ID,
source chunk count, output chunk count, and compilation counters from agg. Use
the module’s established logger and preserve the existing progress and
completion messages.
- Around line 438-442: Add structured logging in the knowledge_graph branch of
the batching budget calculation, including template_id, the model context length
(max_length), and the selected batch budget. Log after computing the bounded
result and preserve the existing min/max calculation and return behavior.

In `@rag/flow/compiler/compiler.py`:
- Around line 606-641: Add structured logging around the staged rechunk flow in
_run_templates and its surrounding first_rechunk_index branch: record the
selected first rechunk template, input chunk count, formal chunk count, and
later-template count without including chunk text. Ensure logs also cover empty
formalization results, using the module’s existing logging mechanism and
preserving the current execution behavior.

In
`@web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx`:
- Around line 208-227: Extract the duplicated rechunk switch and conditional
rechunk_rules field into one internal component that accepts the template index
and preserves the existing form names, labels, tooltips, placeholder, and
visibility behavior. Replace the local implementations in
web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx:208-227
and
web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx:201-220
with this shared component; both sites require direct replacement.
🪄 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: 4450d0c0-97ef-428d-8e15-e480a873b02d

📥 Commits

Reviewing files that changed from the base of the PR and between 852de9f and 45e63fa.

📒 Files selected for processing (18)
  • api/db/init_data/compilation_templates/knowledge_graph.yaml
  • api/db/init_data/compilation_templates/mind_map.yaml
  • api/db/init_data/compilation_templates/page_index.yaml
  • api/db/init_data/compilation_templates/session_essence.yaml
  • api/db/init_data/compilation_templates/session_graph.yaml
  • api/db/init_data/compilation_templates/timeline.yaml
  • rag/advanced_rag/knowlege_compile/_common.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/flow/compiler/compiler.py
  • web/src/interfaces/database/compilation-template.ts
  • web/src/interfaces/request/compilation-template.ts
  • web/src/locales/en.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx
  • web/src/pages/user-setting/compilation-templates/create-next/utils.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/utils.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • web/src/interfaces/database/compilation-template.ts
  • web/src/interfaces/request/compilation-template.ts
  • rag/advanced_rag/knowlege_compile/_common.py
  • web/src/locales/zh.ts
  • web/src/locales/en.ts
  • web/src/pages/user-setting/compilation-templates/create-next/utils.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/utils.ts
  • rag/advanced_rag/knowlege_compile/structure.py

@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 (2)
rag/flow/compiler/compiler.py (2)

655-697: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Positional t{index} IDs still leak to output when rechunking fails.

This still reproduces the issue flagged in the previous review, despite the "Addressed" annotation. At Line 678, if formal_chunks: skips the whole block when the rechunk template returns no groups, so chunks keeps the t{index} ids assigned at Lines 643-644. At Line 680-686, when formal_chunks is present but _formalize_rechunked_chunks filters everything out, the code only logs a warning and still does not restore the hashed ids. In both cases, self.set_output("chunks", chunks) at Line 699 emits chunks whose id is t1..tN, which are not unique across documents in the same knowledge base and can collide or overwrite on persistence.

Restore the hashed ids whenever the semantic rechunk pass does not produce usable formal chunks.

🛡️ Proposed fix to restore hashed IDs on rechunk failure
                 formal_chunks = (compile_info.get(first_template_id) or {}).get("rechunked_chunks")
-                if formal_chunks:
-                    formalized_chunks = self._formalize_rechunked_chunks(chunks, formal_chunks, doc_id)
-                    if formalized_chunks:
-                        chunks = formalized_chunks
-                    else:
-                        logging.warning(
-                            "Compiler: rechunking returned no valid formal chunks for doc %s; keeping original chunks",
-                            doc_id,
-                        )
+                formalized_chunks = self._formalize_rechunked_chunks(chunks, formal_chunks, doc_id) if formal_chunks else []
+                if formalized_chunks:
+                    chunks = formalized_chunks
+                else:
+                    logging.warning(
+                        "Compiler: rechunking returned no valid formal chunks for doc %s; restoring hashed chunk IDs",
+                        doc_id,
+                    )
+                    for ck in chunks:
+                        ck["id"] = xxhash.xxh64((ck["text"] + str(ck["doc_id"])).encode("utf-8")).hexdigest()
🤖 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/flow/compiler/compiler.py` around lines 655 - 697, Update the rechunk
failure handling in the compiler flow around _formalize_rechunked_chunks so
chunks always retain or regain their document-scoped hashed IDs when
formal_chunks is absent or formalization returns no usable chunks. Apply the
existing hashed-ID generation logic used before the rechunk pass, including when
the formalization result is empty, before later templates run and before
set_output("chunks", chunks) persists the results.

563-598: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Decouple non-Tree rechunk scheduling from Tree chunk sizing.

should_rechunk currently includes every active template before split_tree_templates() separates Tree templates at Line 622. If a non-Tree template sets rechunk, _PARSER_CANDIDATE_TOKEN_SIZE is used for every rechunk branch, and the same 128-token chunks are passed to _compile_tree_templates(). This gives the Tree/RAPTOR path far smaller context and more leaf fragments than intended.

Compute should_rechunk and target_token_size from Tree templates only, or separate the Tree/non-Tree paths before normalizing chunks at Lines 574-598.

🤖 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/flow/compiler/compiler.py` around lines 563 - 598, Decouple Tree chunk
sizing from non-Tree rechunk requests in the compiler flow. Update the logic
around _template_requests_rechunk, should_rechunk, and target_token_size so only
Tree templates influence the RAPTOR candidate chunk size; non-Tree templates
must not cause _compile_tree_templates() to receive smaller 128-token chunks.
Preserve non-Tree rechunk handling by separating the template paths before the
normalization branches.
🧹 Nitpick comments (2)
rag/flow/compiler/compiler.py (2)

261-345: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging to the silent fallback paths in _normalize_upstream_chunks.

This is a new normalization flow, but several fallback branches return [] silently for malformed or unrecognized upstream shapes: the non-list chunks check (Line 278), the non-list json/json_result check (Line 293), the missing/blank markdown-text-html payload (Line 329), and the unrecognized output_format (Line 345). If an upstream component emits an unexpected payload shape, the Compiler silently drops all chunks with no diagnostic trail, making the underlying upstream issue hard to trace in production.

Add a logging.warning on each of these fallback branches to record the output_format and the unexpected condition encountered.

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

🤖 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/flow/compiler/compiler.py` around lines 261 - 345, Add logging.warning
calls to each silent fallback in _normalize_upstream_chunks: non-list
upstream["chunks"], non-list JSON records, missing or blank textual payloads,
and unrecognized output_format. Include the current output_format and a concise
description of the unexpected condition in every warning, while preserving the
existing [] return behavior.

Source: Coding guidelines


574-598: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Redundant re-normalization when should_rechunk is False.

For markdown/text/html (Line 574) and json (Line 580) output formats, _normalize_upstream_chunks is called again unconditionally, duplicating the identical computation already performed at Line 498 whenever should_rechunk is False (split_json_text=False with either the default or explicit target_token_size yields the same result). The chunks-format branch at Line 589 already guards this call with should_rechunk; the other two branches do not, doubling parsing/splitting work for every document that is not being rechunked.

♻️ Proposed fix to skip redundant re-normalization
         if kwargs.get("output_format") in {"markdown", "text", "html"}:
-            chunks = self._normalize_upstream_chunks(
-                kwargs,
-                split_json_text=should_rechunk,
-                target_token_size=target_token_size,
-            )
+            if should_rechunk:
+                chunks = self._normalize_upstream_chunks(
+                    kwargs,
+                    split_json_text=should_rechunk,
+                    target_token_size=target_token_size,
+                )
         elif kwargs.get("output_format") == "json":
-            chunks = self._normalize_upstream_chunks(
-                kwargs,
-                split_json_text=should_rechunk,
-                target_token_size=target_token_size,
-            )
+            if should_rechunk:
+                chunks = self._normalize_upstream_chunks(
+                    kwargs,
+                    split_json_text=should_rechunk,
+                    target_token_size=target_token_size,
+                )
             if not chunks:
                 self.set_output("chunks", chunks)
                 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/flow/compiler/compiler.py` around lines 574 - 598, Update the
output-format handling around _normalize_upstream_chunks so the
markdown/text/html and json branches reuse the chunks already computed when
should_rechunk is false, while preserving normalization with the existing
arguments when rechunking is required. Keep the current empty-json early return
behavior unchanged.
🤖 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 `@rag/flow/compiler/compiler.py`:
- Around line 655-697: Update the rechunk failure handling in the compiler flow
around _formalize_rechunked_chunks so chunks always retain or regain their
document-scoped hashed IDs when formal_chunks is absent or formalization returns
no usable chunks. Apply the existing hashed-ID generation logic used before the
rechunk pass, including when the formalization result is empty, before later
templates run and before set_output("chunks", chunks) persists the results.
- Around line 563-598: Decouple Tree chunk sizing from non-Tree rechunk requests
in the compiler flow. Update the logic around _template_requests_rechunk,
should_rechunk, and target_token_size so only Tree templates influence the
RAPTOR candidate chunk size; non-Tree templates must not cause
_compile_tree_templates() to receive smaller 128-token chunks. Preserve non-Tree
rechunk handling by separating the template paths before the normalization
branches.

---

Nitpick comments:
In `@rag/flow/compiler/compiler.py`:
- Around line 261-345: Add logging.warning calls to each silent fallback in
_normalize_upstream_chunks: non-list upstream["chunks"], non-list JSON records,
missing or blank textual payloads, and unrecognized output_format. Include the
current output_format and a concise description of the unexpected condition in
every warning, while preserving the existing [] return behavior.
- Around line 574-598: Update the output-format handling around
_normalize_upstream_chunks so the markdown/text/html and json branches reuse the
chunks already computed when should_rechunk is false, while preserving
normalization with the existing arguments when rechunking is required. Keep the
current empty-json early return behavior unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3e1f80cb-3d7c-4b00-9dca-47b9a59a68c3

📥 Commits

Reviewing files that changed from the base of the PR and between 45e63fa and b55525e.

📒 Files selected for processing (4)
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/flow/compiler/compiler.py
  • rag/llm/chat_model.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • rag/llm/chat_model.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/advanced_rag/knowlege_compile/structure.py

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

Thanks for this PR — LLM-guided semantic rechunking is a solid improvement for knowledge compilation quality. The architecture of having the first rechunk template define boundaries and subsequent templates consume them is clean. I have several concerns that need addressing before this can land:

High priority

1. Potential content loss in _split_slumber_level

The threshold check if end - start >= cls._PARSER_MIN_SPLIT_CHARACTERS can silently drop short segments that appear before a delimiter delimiter when the remaining text produces ≥2 valid splits (which prevents the recursion fallback in _slumber_candidates from trying the next level on the full text):

# Example: "Short header.\n\nSection A content.\n\nSection B content."
# "Short header.\n\n" = ~17 chars, dropped.
# Remaining segments are both valid → len(splits) = 2 → no recursion → header lost.

The merge loop afterward only merges fragments that were already appended, so dropped segments are never recovered. Consider appending all segments to parts initially and only filtering short ones in a smarter merge pass, or always including the first segment regardless of length.

2. DeepSeek token handling in _clean_conf is a breaking change

The modification to chat_model.py _clean_conf removes max_tokens for ALL DeepSeek calls, not just knowledge compilation. This means any existing code path that passes max_tokens to a DeepSeek model will silently lose its token limit unless it also passes max_completion_tokens. The max_completion_tokens value only survives when explicitly set by knowledge compilation. Other callers (Agent UI, chat, etc.) would have their max_tokens stripped with no replacement.

Consider scoping this to only activate when max_completion_tokens is actually present in gen_conf, or use a dedicated parameter to opt into this behavior.

Medium priority

3. Missing test coverage

812 additions across 20 files with zero test files changed. This feature touches chunk boundary logic, LLM response parsing, and the compiler pipeline — all prime candidates for regressions. At minimum, unit tests for _slumber_candidates, _split_slumber_level, _is_atomic_json_record, _struct_expand_source_chunk_ids, and the _normalize_upstream_chunks dispatch would help.

4. Dual normalization of chunks in _invoke

When rechunking is enabled and output_format == "chunks", chunks pass through _normalize_upstream_chunks twice — once without splitting (target_token_size=1024) and once with splitting (target_token_size=128). The first normalization generates hash-based IDs, the second generates positional t-IDs, and the first set is discarded. This is wasteful and confusing. Consider restructuring so only one pass happens.

5. Knowledge graph batch budget reduction

KNOWLEDGE_GRAPH_CONTEXT_FRACTION = 0.1 with max 4096 tokens is a 10x reduction from the default. This might be intentional for latency, but please document the rationale. Low context could degrade entity/relation extraction for knowledge graphs.

Minor

6. In-place mutation in _merge_small_text_chunks

pending["text"] = combined mutates the chunk dict in-place. If any caller holds a reference to these chunk dicts, they will see the mutated text. Consider using deepcopy or constructing new dicts.

7. Regex in _struct_extract_hypergraph

The chunk text regex r"\[CHUNK_ID:\s*([^\]]+)\]\n(.*?)\n\[END_CHUNK\]" with [^\]]+ for the ID capture group could theoretically match across unwanted boundaries if the actual chunk text contains ]. More defensive to use [^\]]*? or a more specific pattern.

8. source_chunk_ids remapping asymmetry

Entity IDs are remapped via temp_to_uuid (filtering out unmapped IDs), while edge IDs are remapped via chunk_id_map.values() set membership. The two code paths do the same thing but with different mechanisms. Consider using a shared helper for consistency.

9. Frontend type check looks good

The typeof value === "boolean" addition to transformTemplateToPayload correctly handles the rechunk: false case. No issues there.

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

🧹 Nitpick comments (2)
rag/llm/chat_model.py (2)

1695-1702: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging for DeepSeek token normalization.

Lines 1697-1702 add a new configuration path. The code silently accepts or discards the selected limit. Add a structured debug log for the source field and normalized result. Do not log prompts or credentials.

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/llm/chat_model.py` around lines 1695 - 1702, Add a structured debug log
in the token-normalization flow around raw_max_completion_tokens,
raw_max_tokens, and candidate, recording the selected source field and
normalized result after processing. Keep prompts and credentials out of the log,
and preserve the existing validation and fallback behavior.

Source: Coding guidelines


1697-1702: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add focused tests for the token-selection rules.

Cover max_completion_tokens precedence, positive max_tokens fallback, boolean and invalid-value rejection, and removal of max_tokens for non-DeepSeek providers. Run targeted pytest or Ruff checks instead of the full suite.

As per coding guidelines, **/*: Preserve still-valid behavior with focused tests; **/*.{py,pyi}: For backend changes, prefer targeted pytest or Ruff checks over full-suite validation.

🤖 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/llm/chat_model.py` around lines 1697 - 1702, Add focused tests around the
token-selection logic using raw_max_completion_tokens and raw_max_tokens: verify
max_completion_tokens takes precedence, positive max_tokens is used as fallback,
boolean and invalid values are rejected, and max_tokens is removed for
non-DeepSeek providers. Run the relevant targeted pytest or Ruff checks rather
than the full suite.

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.

Nitpick comments:
In `@rag/llm/chat_model.py`:
- Around line 1695-1702: Add a structured debug log in the token-normalization
flow around raw_max_completion_tokens, raw_max_tokens, and candidate, recording
the selected source field and normalized result after processing. Keep prompts
and credentials out of the log, and preserve the existing validation and
fallback behavior.
- Around line 1697-1702: Add focused tests around the token-selection logic
using raw_max_completion_tokens and raw_max_tokens: verify max_completion_tokens
takes precedence, positive max_tokens is used as fallback, boolean and invalid
values are rejected, and max_tokens is removed for non-DeepSeek providers. Run
the relevant targeted pytest or Ruff checks rather than the full suite.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b96d6b7f-b29b-4ca3-9cd8-9ee66924a693

📥 Commits

Reviewing files that changed from the base of the PR and between b55525e and ae2ca28.

📒 Files selected for processing (2)
  • rag/flow/compiler/compiler.py
  • rag/llm/chat_model.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/flow/compiler/compiler.py

@wangq8
wangq8 merged commit 44e13d1 into infiniflow:main Jul 31, 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 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants