Repository navigation
feat: add LLM-guided semantic rechunking for knowledge compilation - #17546
Conversation
📝 WalkthroughWalkthroughRechunking 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. ChangesRechunked knowledge compilation
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
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
wangq8
left a comment
There was a problem hiding this comment.
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)
continuePreviously, 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 = 128when 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
SwitchFormFieldimport:@/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
enandzh. - The
rechunkboolean is properly handled inisConfigMetaKeyandtransformTemplateToPayload.
No blocking issues — the knowledge_graph change in runner.py is the one thing I would clarify before merging.
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (3)
rag/advanced_rag/knowlege_compile/structure.py (2)
454-499: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo 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 winHoist
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 valueHardcoded 65536 unconditionally overrides a caller-supplied limit.
Callers that already set
max_completion_tokens/max_tokensfor a specific compile step lose it here. Considerconf.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
📒 Files selected for processing (14)
rag/advanced_rag/knowlege_compile/_common.pyrag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/structure.pyrag/flow/compiler/compiler.pyrag/llm/chat_model.pyrag/svr/task_executor_refactor/chunk_post_processor.pyweb/src/interfaces/database/compilation-template.tsweb/src/interfaces/request/compilation-template.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsxweb/src/pages/user-setting/compilation-templates/create-next/utils.tsweb/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsxweb/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
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 liftStage compilation around the rechunking template.
run_structure_compile_over_batchesbuffers every template from the sameincoming_batch, but only the template whoseparser_config.get("rechunk")is true returnsrechunked_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 winPreserve fenced code blocks as atomic Markdown blocks.
_split_markdown_blocksonly detects tables. A fenced code block enters the ordinary-text path and can be split by_slumber_candidatesornaive_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 winLog 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 winAdd 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 winAdd 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 winExtract 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
📒 Files selected for processing (18)
api/db/init_data/compilation_templates/knowledge_graph.yamlapi/db/init_data/compilation_templates/mind_map.yamlapi/db/init_data/compilation_templates/page_index.yamlapi/db/init_data/compilation_templates/session_essence.yamlapi/db/init_data/compilation_templates/session_graph.yamlapi/db/init_data/compilation_templates/timeline.yamlrag/advanced_rag/knowlege_compile/_common.pyrag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/structure.pyrag/flow/compiler/compiler.pyweb/src/interfaces/database/compilation-template.tsweb/src/interfaces/request/compilation-template.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsxweb/src/pages/user-setting/compilation-templates/create-next/utils.tsweb/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsxweb/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
There was a problem hiding this comment.
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 winPositional
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, sochunkskeeps thet{index}ids assigned at Lines 643-644. At Line 680-686, whenformal_chunksis present but_formalize_rechunked_chunksfilters 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 whoseidist1..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 winDecouple non-Tree rechunk scheduling from Tree chunk sizing.
should_rechunkcurrently includes every active template beforesplit_tree_templates()separates Tree templates at Line 622. If a non-Tree template setsrechunk,_PARSER_CANDIDATE_TOKEN_SIZEis 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_rechunkandtarget_token_sizefrom 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 winAdd 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-listchunkscheck (Line 278), the non-listjson/json_resultcheck (Line 293), the missing/blank markdown-text-html payload (Line 329), and the unrecognizedoutput_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.warningon each of these fallback branches to record theoutput_formatand 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 winRedundant re-normalization when
should_rechunkis False.For
markdown/text/html(Line 574) andjson(Line 580) output formats,_normalize_upstream_chunksis called again unconditionally, duplicating the identical computation already performed at Line 498 whenevershould_rechunkis False (split_json_text=Falsewith either the default or explicittarget_token_sizeyields the same result). Thechunks-format branch at Line 589 already guards this call withshould_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
📒 Files selected for processing (4)
rag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/structure.pyrag/flow/compiler/compiler.pyrag/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
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
rag/llm/chat_model.py (2)
1695-1702: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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 winAdd focused tests for the token-selection rules.
Cover
max_completion_tokensprecedence, positivemax_tokensfallback, boolean and invalid-value rejection, and removal ofmax_tokensfor 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
📒 Files selected for processing (2)
rag/flow/compiler/compiler.pyrag/llm/chat_model.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/flow/compiler/compiler.py
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=truedetermines the semantic boundaries, and subsequent templates reuse the generated chunks with rechunking disabled.What changed?
Type of change