Repository navigation
fix: persist pipeline tree graph rows - #17400
Conversation
📝 WalkthroughWalkthroughPage-index compilation now extracts hierarchical titles, facts, and conclusions, buffers chunks by token budget, preserves scoped chunk attribution, persists normalized tree graph rows, and displays entity types in tree views. ChangesTree and page-index compilation
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant ChunkStream
participant CompilerRunner
participant StructureExtractor
participant TreeCompiler
participant TreeGraphStorage
ChunkStream->>CompilerRunner: provide document chunks
CompilerRunner->>StructureExtractor: submit token-bounded chunks with IDs
StructureExtractor-->>CompilerRunner: return structured entities and relations
CompilerRunner->>TreeCompiler: compile and normalize tree
TreeCompiler->>TreeGraphStorage: persist tree rows and graph JSON
Possibly related PRs
Suggested labels: 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
rag/advanced_rag/knowlege_compile/structure.py (1)
2092-2146: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftAdd focused coverage for replacement and template isolation.
Exercise recompiling one
(doc_id, template_id), verify stale rows are removed, another template remains intact, and relation rows exposefrom_entity_kwd/to_entity_kwd.As per coding guidelines, backend code targets Python 3.13+ and valid backend behavior must be preserved with focused tests and targeted pytest or Ruff checks.
🤖 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 2092 - 2146, Add focused pytest coverage for _struct_upsert_tree_graph_rows that recompiles the same (doc_id, compilation_template_id), verifies stale entity and relation rows are deleted before replacement, confirms rows for a different template remain intact, and checks relation rows expose from_entity_kwd and to_entity_kwd. Use targeted mocks for embedding and document-store operations, preserving Python 3.13-compatible behavior.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2144-2146: Make structure replacement and graph-JSON persistence
atomic across rag/advanced_rag/knowlege_compile/structure.py:2144-2146 and
rag/flow/compiler/compiler.py:158-173. Replace the destructive
delete-then-insert flow with a transactional/repository-level operation or
staged generation that preserves the old data until both row and graph writes
succeed; coordinate both sites so any failure rolls back or leaves the previous
consistent generation active.
---
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2092-2146: Add focused pytest coverage for
_struct_upsert_tree_graph_rows that recompiles the same (doc_id,
compilation_template_id), verifies stale entity and relation rows are deleted
before replacement, confirms rows for a different template remain intact, and
checks relation rows expose from_entity_kwd and to_entity_kwd. Use targeted
mocks for embedding and document-store operations, preserving Python
3.13-compatible behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 68c0ea97-ecd6-46df-ba27-2db7b9822e0e
📒 Files selected for processing (2)
rag/advanced_rag/knowlege_compile/structure.pyrag/flow/compiler/compiler.py
| await thread_pool_exec(settings.docStoreConn.delete, delete_condition, index, kb_id) | ||
| if rows: | ||
| await thread_pool_exec(settings.docStoreConn.insert, rows, index, kb_id) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Make tree-row replacement and graph persistence atomic.
A successful delete followed by a failed insert permanently removes the prior structure graph; a successful row insert followed by failed graph-JSON upsert leaves the two representations out of sync. Use a transactional/repository-level replace operation, or stage a new generation and only switch/clean up after all writes succeed.
rag/advanced_rag/knowlege_compile/structure.py#L2144-L2146: avoid destructive delete-before-insert without rollback.rag/flow/compiler/compiler.py#L158-L173: coordinate the structure-row and graph-JSON writes in the same recoverable operation.
📍 Affects 2 files
rag/advanced_rag/knowlege_compile/structure.py#L2144-L2146(this comment)rag/flow/compiler/compiler.py#L158-L173
🤖 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 2144 - 2146,
Make structure replacement and graph-JSON persistence atomic across
rag/advanced_rag/knowlege_compile/structure.py:2144-2146 and
rag/flow/compiler/compiler.py:158-173. Replace the destructive
delete-then-insert flow with a transactional/repository-level operation or
staged generation that preserves the old data until both row and graph writes
succeed; coordinate both sites so any failure rolls back or leaves the previous
consistent generation active.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17400 +/- ##
=======================================
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: 7
🧹 Nitpick comments (6)
rag/advanced_rag/knowlege_compile/page_index_tree_builder.py (5)
54-58: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the unused
_MAX_DEPTHconstant.
_MAX_DEPTHis never referenced; the depth limit is only enforced via the prompt text. As per coding guidelines, "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."🤖 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/page_index_tree_builder.py` around lines 54 - 58, Remove the unused _MAX_DEPTH constant from the constants section of page_index_tree_builder.py; leave _CONTENT_BUDGET_FRACTION and _DEFAULT_CONTEXT_WINDOW unchanged.Source: Coding guidelines
399-408: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
chunksparameter is unused.
_tree_to_es_docsonly ever useschunk_id_map; drop the parameter and the corresponding argument at line 620.🤖 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/page_index_tree_builder.py` around lines 399 - 408, Remove the unused chunks parameter from _tree_to_es_docs and update its call site around line 620 to stop passing chunks. Preserve the remaining parameters and document-generation behavior unchanged.
593-630: 🩺 Stability & Availability | 🔵 Trivial | 🏗️ Heavy liftFailures degrade to a silent empty result, and a long progressive build cannot be cancelled.
Every failure path returns
[], so the caller cannot distinguish "no structure found" from "LLM/embedding failed" — the parse reports success with zero page_index rows._progressive_buildalso issues one LLM call per partition with no cancellation hook, so a cancelled task keeps burning tokens until every partition finishes.Consider propagating
PageIndexTreeError(the runner already wraps the call in try/except) and threading the runner'scancel_checkinto the partition loop.🤖 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/page_index_tree_builder.py` around lines 593 - 630, Update the page-index tree runner’s exception handling to propagate PageIndexTreeError instead of returning [] so callers can distinguish construction failures from empty results; preserve handling for unexpected errors unless the existing contract requires propagation. Thread the runner’s cancel_check through _progressive_build and its partition loop, checking it between LLM calls and aborting promptly when cancellation is requested.
388-391: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRedundant re-initialization and unused loop variable.
_merge_partition_rootsalready returnschildren: [], andpart_idxis unused (Ruff B007). Folds naturally into the fix above.🤖 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/page_index_tree_builder.py` around lines 388 - 391, In _merge_partition_roots, remove the redundant merged_root["children"] re-initialization because the returned structure already initializes it, and change the partial_roots iteration to avoid the unused part_idx variable while preserving each part_root’s section assignment and append behavior.Source: Linters/SAST tools
167-180: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winA single chunk larger than
content_budgetsilently produces an over-budget partition.When
currentis empty the chunk is appended unconditionally, so an oversized chunk yields a partition above budget.gen_jsonthen fits the prompt viamessage_fit_in, truncating content; the LLM cannot emit everychunk_index,_validate_coverageraises, andbuild_page_index_treereturns[]— the whole page_index output is lost with only a log line. Consider logging/handling the oversized-chunk case explicitly.♻️ Suggested handling
for ch in chunks: text = ch.get("text") or ch.get("content_with_weight") or "" tks = num_tokens_from_string(text) + if tks > content_budget: + logger.warning( + "page_index_tree: chunk exceeds content budget (%d > %d); partition will be truncated by the model context fit", + tks, + content_budget, + ) if current_tokens + tks > content_budget and current:🤖 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/page_index_tree_builder.py` around lines 167 - 180, Update the partitioning loop to explicitly detect chunks whose token count exceeds content_budget, including the chunk’s token count and identifying context in a warning or error. Apply a deliberate policy for oversized chunks—such as rejecting or separately handling them—rather than silently creating an over-budget partition that later fails coverage validation in build_page_index_tree.rag/advanced_rag/knowlege_compile/runner.py (1)
498-501: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCarry
parser_cfgin the comprehension instead of rebuilding a dict per iteration.
dict(active_templates)is rebuilt on every loop pass and silently drops duplicate template ids.♻️ Proposed fix
- page_index_template_ids = [tid for tid, cfg in active_templates if _is_page_index_template(cfg)] - if page_index_template_ids and all_chunks: - for template_id in page_index_template_ids: - parser_cfg = dict(active_templates).get(template_id) or {} + page_index_templates = [(tid, cfg) for tid, cfg in active_templates if _is_page_index_template(cfg)] + if page_index_templates and all_chunks: + for template_id, parser_cfg in page_index_templates: + parser_cfg = parser_cfg or {}🤖 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 498 - 501, Update the page-index template collection and iteration around _is_page_index_template so each selected item carries both template_id and its parser_cfg. Iterate those pairs directly and remove the per-iteration dict(active_templates) lookup, preserving the existing filtering and processing behavior while retaining duplicate entries.
🤖 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/page_index_tree_builder.py`:
- Around line 231-257: Remove the unused _collect_subtree_chunk_ids helper and
its duplicate subtree-walking logic. Keep a single implementation path by
preserving or reusing _collect_subtree_ids in _tree_to_es_docs, ensuring
existing leaf chunk ID collection and deduplication behavior remains unchanged.
- Around line 479-521: Fix entity-to-chunk pairing in the payload construction
flow by collecting each node’s subtree chunk_ids inside _walk at the same time
it emits a payload, preserving the existing skip behavior for nodes without
title or summary. Store chunk_ids alongside each payload, including the correct
child-derived IDs for relations, then build es_docs directly from those paired
tuples. Remove _collect_subtree_ids, subtree_chunk_ids, and the ei cursor, along
with the duplicated chunk-ID computation they replace.
- Around line 433-441: Update relation payload construction in the page index
tree builder to use the field names resolved by _struct_relation_member_fields,
falling back to source and target when unresolved, so configured relation-member
names populate both endpoints. Also replace the name-key payload discriminator
in _struct_to_doc_storage_doc with explicit entity/relation kind tracking,
avoiding key-based classification.
- Around line 379-393: Rebase partition-relative leaf indexes before attaching
each partition root in the merge flow. Add and use an _offset_leaf_indexes
helper to recursively add the partition’s global starting offset to each leaf
chunk_index, using the cumulative sizes of preceding partitions; apply it within
the loop that sets part_root["node_type"] and appends children, preserving
non-leaf traversal and existing tree assembly.
In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 469-472: In rag/advanced_rag/knowlege_compile/runner.py lines
469-472, compute the page_index template subset once before the batch loop,
extend all_chunks only when that subset is non-empty, and use template-id
membership instead of calling _is_page_index_template for each batch. In lines
498-501, iterate the hoisted (template_id, parser_cfg) pairs directly and remove
the per-iteration dict(active_templates) rebuild.
- Around line 527-532: Update the exception handling around the page-index tree
builder to catch and re-raise TaskCanceledException before the broad Exception
handler, matching the cancellation handling in the other handlers in runner.py.
Keep the existing logging behavior for all non-cancellation exceptions.
- Around line 520-521: The page_index final flush currently appends all es_docs
without enforcing DOC_STRUCTURE_MERGE_MAX_DOCS. Update the page_index
accumulation and merge_compiled_structures flow to chunk the accumulated
documents by DOC_STRUCTURE_MERGE_MAX_DOCS before each flush, preserving existing
normal batch commits and ensuring no merge receives an oversized batch.
---
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/page_index_tree_builder.py`:
- Around line 54-58: Remove the unused _MAX_DEPTH constant from the constants
section of page_index_tree_builder.py; leave _CONTENT_BUDGET_FRACTION and
_DEFAULT_CONTEXT_WINDOW unchanged.
- Around line 399-408: Remove the unused chunks parameter from _tree_to_es_docs
and update its call site around line 620 to stop passing chunks. Preserve the
remaining parameters and document-generation behavior unchanged.
- Around line 593-630: Update the page-index tree runner’s exception handling to
propagate PageIndexTreeError instead of returning [] so callers can distinguish
construction failures from empty results; preserve handling for unexpected
errors unless the existing contract requires propagation. Thread the runner’s
cancel_check through _progressive_build and its partition loop, checking it
between LLM calls and aborting promptly when cancellation is requested.
- Around line 388-391: In _merge_partition_roots, remove the redundant
merged_root["children"] re-initialization because the returned structure already
initializes it, and change the partial_roots iteration to avoid the unused
part_idx variable while preserving each part_root’s section assignment and
append behavior.
- Around line 167-180: Update the partitioning loop to explicitly detect chunks
whose token count exceeds content_budget, including the chunk’s token count and
identifying context in a warning or error. Apply a deliberate policy for
oversized chunks—such as rejecting or separately handling them—rather than
silently creating an over-budget partition that later fails coverage validation
in build_page_index_tree.
In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 498-501: Update the page-index template collection and iteration
around _is_page_index_template so each selected item carries both template_id
and its parser_cfg. Iterate those pairs directly and remove the per-iteration
dict(active_templates) lookup, preserving the existing filtering and processing
behavior while retaining duplicate entries.
🪄 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: dc105d97-6ace-467a-8471-8dec16b598db
📒 Files selected for processing (3)
rag/advanced_rag/knowlege_compile/page_index_tree_builder.pyrag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/structure.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/advanced_rag/knowlege_compile/structure.py
| def _collect_subtree_chunk_ids( | ||
| node: dict, | ||
| chunk_id_map: list[str], | ||
| ) -> list[str]: | ||
| """Walk a subtree and collect all leaf chunk_ids.""" | ||
| ids: list[str] = [] | ||
|
|
||
| def _walk(n: dict) -> None: | ||
| if n.get("type") == "leaf": | ||
| idx = n.get("chunk_index") | ||
| if isinstance(idx, int) and 0 <= idx < len(chunk_id_map): | ||
| cid = chunk_id_map[idx] | ||
| if cid: | ||
| ids.append(cid) | ||
| else: | ||
| for child in n.get("children") or []: | ||
| _walk(child) | ||
|
|
||
| _walk(node) | ||
| # Order-preserving dedup | ||
| seen: set[str] = set() | ||
| result: list[str] = [] | ||
| for cid in ids: | ||
| if cid not in seen: | ||
| seen.add(cid) | ||
| result.append(cid) | ||
| return result |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
_collect_subtree_chunk_ids is dead code duplicating _collect_subtree_ids.
Nothing calls this helper; _tree_to_es_docs re-implements the same walk locally at lines 483-502. Delete this one (or use it from _tree_to_es_docs) so there is a single implementation. As per coding guidelines, "Prefer one implementation path instead of preserving old and new versions side by side" and "Remove dead tests, commented-out code…".
🤖 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/page_index_tree_builder.py` around lines
231 - 257, Remove the unused _collect_subtree_chunk_ids helper and its duplicate
subtree-walking logic. Keep a single implementation path by preserving or
reusing _collect_subtree_ids in _tree_to_es_docs, ensuring existing leaf chunk
ID collection and deduplication behavior remains unchanged.
Source: Coding guidelines
| for part_idx, part_chunks in enumerate(partitions): | ||
| root = await _build_partition_tree(part_chunks, chat_mdl, part_idx) | ||
| partial_roots.append(root) | ||
|
|
||
| # Step 2: TreeMerge — unified root from partition summaries. | ||
| merged_root = await _merge_partition_roots(partial_roots, chat_mdl) | ||
|
|
||
| # Step 3: Attach partition roots as children of unified root. | ||
| # Each partition root becomes a "section" under the unified root. | ||
| merged_root["children"] = [] | ||
| for part_idx, part_root in enumerate(partial_roots): | ||
| part_root["node_type"] = "section" | ||
| merged_root["children"].append(part_root) | ||
|
|
||
| return merged_root, partitions |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win
Partition-relative chunk_index values are never remapped to global indexes.
Each partition tree is built and validated against indexes 0..len(part_chunks)-1 (line 324), but the merged tree is returned as-is and consumed with the global chunk_id_map (build_page_index_tree discards the returned partitions at line 608). Every entity from partition 1 onward therefore gets source_chunk_ids belonging to the first partition's chunks — silently wrong provenance in the persisted ES rows.
Rebase leaf indexes onto the global offset while attaching each partition root.
🐛 Proposed fix: offset leaf indexes per partition
# Step 3: Attach partition roots as children of unified root.
# Each partition root becomes a "section" under the unified root.
merged_root["children"] = []
- for part_idx, part_root in enumerate(partial_roots):
- part_root["node_type"] = "section"
- merged_root["children"].append(part_root)
+ offset = 0
+ for part_chunks, part_root in zip(partitions, partial_roots):
+ _offset_leaf_indexes(part_root, offset)
+ offset += len(part_chunks)
+ part_root["node_type"] = "section"
+ merged_root["children"].append(part_root)
return merged_root, partitionsPlus the helper:
def _offset_leaf_indexes(node: dict, offset: int) -> None:
"""Rebase partition-relative leaf indexes onto global chunk indexes."""
if node.get("type") == "leaf":
idx = node.get("chunk_index")
if isinstance(idx, int):
node["chunk_index"] = idx + offset
return
for child in node.get("children") or []:
_offset_leaf_indexes(child, offset)🧰 Tools
🪛 Ruff (0.15.21)
[warning] 389-389: Loop control variable part_idx not used within loop body
(B007)
🤖 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/page_index_tree_builder.py` around lines
379 - 393, Rebase partition-relative leaf indexes before attaching each
partition root in the merge flow. Add and use an _offset_leaf_indexes helper to
recursively add the partition’s global starting offset to each leaf chunk_index,
using the cumulative sizes of preceding partitions; apply it within the loop
that sets part_root["node_type"] and appends children, preserving non-leaf
traversal and existing tree assembly.
| if parent_title: | ||
| relations.append( | ||
| { | ||
| "type": "include", | ||
| "source": parent_title, | ||
| "target": title, | ||
| "description": f"'{parent_title}' includes '{title}'", | ||
| } | ||
| ) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Relation payloads hardcode source/target while _struct_to_doc_storage_doc reads src_field/target_field.
_struct_relation_member_fields can resolve to config-provided names (e.g. src/tgt via identifiers.relation_members) or to (None, None). In those cases payload.get(src_field) misses and from_entity_kwd/to_entity_kwd are never stamped, so the structure graph loses every edge endpoint. Key the payload off the resolved field names (falling back to source/target).
🐛 Proposed fix
if parent_title:
+ src_key = src_field or "source"
+ tgt_key = target_field or "target"
relations.append(
{
"type": "include",
- "source": parent_title,
- "target": title,
+ src_key: parent_title,
+ tgt_key: title,
"description": f"'{parent_title}' includes '{title}'",
}
)Note this also breaks the "name" in payload entity/relation discriminator only if a resolved field is literally name; prefer tracking the kind explicitly instead of sniffing keys.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if parent_title: | |
| relations.append( | |
| { | |
| "type": "include", | |
| "source": parent_title, | |
| "target": title, | |
| "description": f"'{parent_title}' includes '{title}'", | |
| } | |
| ) | |
| if parent_title: | |
| src_key = src_field or "source" | |
| tgt_key = target_field or "target" | |
| relations.append( | |
| { | |
| "type": "include", | |
| src_key: parent_title, | |
| tgt_key: title, | |
| "description": f"'{parent_title}' includes '{title}'", | |
| } | |
| ) |
🤖 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/page_index_tree_builder.py` around lines
433 - 441, Update relation payload construction in the page index tree builder
to use the field names resolved by _struct_relation_member_fields, falling back
to source and target when unresolved, so configured relation-member names
populate both endpoints. Also replace the name-key payload discriminator in
_struct_to_doc_storage_doc with explicit entity/relation kind tracking, avoiding
key-based classification.
| # Pre-compute subtree chunk_ids for each internal node. We walk the tree | ||
| # once and assign chunk_ids to each entity based on its position. | ||
| subtree_chunk_ids: list[list[str]] = [] | ||
|
|
||
| def _collect_subtree_ids(node: dict) -> list[str]: | ||
| """Return chunk_ids for this node's subtree, appending to the global list for entities.""" | ||
| if node.get("type") == "leaf": | ||
| idx = node.get("chunk_index") | ||
| if isinstance(idx, int) and 0 <= idx < len(chunk_id_map): | ||
| cid = chunk_id_map[idx] | ||
| return [cid] if cid else [] | ||
| return [] | ||
| ids_list: list[str] = [] | ||
| for child in node.get("children") or []: | ||
| ids_list.extend(_collect_subtree_ids(child)) | ||
| # Dedup preserving order | ||
| seen: set[str] = set() | ||
| deduped: list[str] = [] | ||
| for cid in ids_list: | ||
| if cid and cid not in seen: | ||
| seen.add(cid) | ||
| deduped.append(cid) | ||
| subtree_chunk_ids.append(deduped) | ||
| return deduped | ||
|
|
||
| _collect_subtree_ids(root) | ||
|
|
||
| # subtree_chunk_ids now has one entry per internal node, in DFS order. | ||
| # entities list is also in DFS order. Zip them. | ||
| es_docs: list[dict] = [] | ||
| ei = 0 # entity index into subtree_chunk_ids | ||
| for i, payload in enumerate(all_payloads): | ||
| is_entity = "name" in payload | ||
| if is_entity: | ||
| chunk_ids = subtree_chunk_ids[ei] if ei < len(subtree_chunk_ids) else [] | ||
| ei += 1 | ||
| else: | ||
| # Relation: use the child entity's chunk_ids (next entity in DFS). | ||
| # Since relations and entities are interleaved in DFS order | ||
| # (entity → its children → next sibling entity), we use the chunk_ids | ||
| # from the entity at position ei (the child we just walked into). | ||
| # Fall back to empty if out of bounds. | ||
| chunk_ids = subtree_chunk_ids[ei] if ei < len(subtree_chunk_ids) else [] |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy lift
Entity↔chunk_ids pairing is misaligned: entities is pre-order, subtree_chunk_ids is post-order.
_walk appends an entity before descending into children, while _collect_subtree_ids appends its entry after recursing (line 501). The two lists are therefore in different orders, so the zip at lines 510-521 attaches the wrong source_chunk_ids to nearly every entity. Two further divergences compound it:
_walkskips nodes with neithertitlenorsummary(line 425), but_collect_subtree_idsemits an entry for every internal node — the lists can also differ in length.- Relations reuse
subtree_chunk_ids[ei]without advancing, which the comment itself describes as a guess.
Collect the chunk_ids in _walk alongside each payload so the pairing is correct by construction.
🐛 Sketch: pair chunk_ids at emission time
- entities: list[dict] = []
- relations: list[dict] = []
+ entities: list[tuple[dict, list[str]]] = []
+ relations: list[tuple[dict, list[str]]] = []
def _walk(node: dict, parent_title: str | None) -> None:
if node.get("type") == "leaf":
return
title = (node.get("title") or "").strip()
summary = (node.get("summary") or "").strip()
+ node_chunk_ids = _collect_subtree_chunk_ids(node, chunk_id_map)
if title or summary:
- entity_payload = {...}
- entities.append(entity_payload)
+ entities.append(({...}, node_chunk_ids))
if parent_title:
- relations.append({...})
+ relations.append(({...}, node_chunk_ids))Then drop _collect_subtree_ids / the ei cursor entirely and read the chunk_ids straight off each (payload, chunk_ids) tuple. This also removes the duplication flagged at lines 231-257.
🤖 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/page_index_tree_builder.py` around lines
479 - 521, Fix entity-to-chunk pairing in the payload construction flow by
collecting each node’s subtree chunk_ids inside _walk at the same time it emits
a payload, preserving the existing skip behavior for nodes without title or
summary. Store chunk_ids alongside each payload, including the correct
child-derived IDs for relations, then build es_docs directly from those paired
tuples. Remove _collect_subtree_ids, subtree_chunk_ids, and the ei cursor, along
with the duplicated chunk-ID computation they replace.
wangq8
left a comment
There was a problem hiding this comment.
Thanks for this substantial fix! The approach of building a table-of-contents tree via LLM and persisting entity+relation rows is the right architecture — it directly addresses the root cause where the structure graph API received empty templates because only a graph blob was persisted.
Strengths:
- Smart two-pass strategy: single-pass tree build for short docs, progressive partition+merge for long docs — keeps LLM calls cost-effective
- Proper deletion of old rows before re-insertion avoids stale data after recompilation
- Integration into
runner.pyis clean: page_index templates are skipped in the per-chunk loop and handled by the tree builder after all batches are collected _struct_upsert_tree_graph_rowscorrectly persists entities and relations as independent structure rows, matching what the structure graph API expects
Bug found — relations get empty chunk_ids in _tree_to_es_docs:
In _tree_to_es_docs, all entities come before all relations in the combined list:
all_payloads: list[dict] = entities + relationsThe ei counter tracks position into subtree_chunk_ids and is incremented for each entity. But relations are processed AFTER all entities, so by the time the first relation is reached, ei already equals len(subtree_chunk_ids), and the bounds check falls back to []:
chunk_ids = subtree_chunk_ids[ei] if ei < len(subtree_chunk_ids) else []This means EVERY relation doc gets an empty source_chunk_ids list. The downstream impact is that relations will lack chunk-level provenance — the structure graph API may not be able to trace which chunks a parent→child relation covers.
Suggested fix: interleave entities and relations in DFS order (as _walk emits them) rather than concatenating the two lists, OR track entity→chunk_ids in a separate lookup map keyed by entity title/position.
Other notes:
_collect_subtree_idsmodifiessubtree_chunk_idsas a side effect while also returning values — this dual purpose is fragile. Consider separating collection from assembly.- The progressive build accumulates
all_chunksinrunner.pyfor the entire document. For very large documents this could be memory-intensive; consider streaming or capping. - The tree merge prompt is English-only — multilingual documents may get lower-quality merged titles/summaries.
Overall the approach is solid and this definitely fixes the reported issue, but the chunk_ids bug in relation docs should be addressed before merging.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 496-514: The token-budget flushes in the page-index buffering loop
should report progress through the existing progress_cb mechanism, matching the
analogous merge-flush path. Add logging immediately before each _submit_one call
triggered by buffer overflow or reaching the budget, while leaving normal
buffering and submission 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: 8a2173fb-ef8b-4ccc-8866-8eef7f6c16e2
📒 Files selected for processing (5)
api/db/init_data/compilation_templates/page_index.yamlrag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/structure.pyweb/src/components/ui/tree-view.tsxweb/src/pages/chunk/representation/utils/adapters.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/advanced_rag/knowlege_compile/structure.py
|
|
||
| buffer = page_index_buffers[template_id] | ||
| budget = _page_index_budget(template_id) | ||
| buffer_tokens = page_index_buffer_tokens[template_id] | ||
| for chunk in incoming_batch: | ||
| text = chunk.get("content_with_weight") or chunk.get("text") or "" | ||
| chunk_tokens = num_tokens_from_string(text if isinstance(text, str) else "") | ||
| if buffer and buffer_tokens + chunk_tokens > budget: | ||
| await _submit_one(buffer, template_id, parser_cfg) | ||
| buffer = [] | ||
| buffer_tokens = 0 | ||
| buffer.append(chunk) | ||
| buffer_tokens += chunk_tokens | ||
| if buffer_tokens >= budget: | ||
| await _submit_one(buffer, template_id, parser_cfg) | ||
| buffer = [] | ||
| buffer_tokens = 0 | ||
| page_index_buffers[template_id] = buffer | ||
| page_index_buffer_tokens[template_id] = buffer_tokens |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Add logging at the new token-budget flush points.
The token-budget-triggered flushes (buffer full, chunk would overflow) submit compile batches silently, unlike the analogous merge-flush path (line 419) which logs via progress_cb. This new flow should surface flush events for observability/debugging of page_index buffering.
📝 Proposed fix
if buffer and buffer_tokens + chunk_tokens > budget:
+ progress_cb(msg=f" page_index buffer flush ({buffer_tokens} tokens, {len(buffer)} chunks) for template ({template_ids_by_id[template_id]}/{total})")
await _submit_one(buffer, template_id, parser_cfg)
buffer = []
buffer_tokens = 0
buffer.append(chunk)
buffer_tokens += chunk_tokens
if buffer_tokens >= budget:
+ progress_cb(msg=f" page_index buffer flush ({buffer_tokens} tokens, {len(buffer)} chunks) for template ({template_ids_by_id[template_id]}/{total})")
await _submit_one(buffer, template_id, parser_cfg)
buffer = []
buffer_tokens = 0As per coding guidelines, "Add logging for new flows".
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| buffer = page_index_buffers[template_id] | |
| budget = _page_index_budget(template_id) | |
| buffer_tokens = page_index_buffer_tokens[template_id] | |
| for chunk in incoming_batch: | |
| text = chunk.get("content_with_weight") or chunk.get("text") or "" | |
| chunk_tokens = num_tokens_from_string(text if isinstance(text, str) else "") | |
| if buffer and buffer_tokens + chunk_tokens > budget: | |
| await _submit_one(buffer, template_id, parser_cfg) | |
| buffer = [] | |
| buffer_tokens = 0 | |
| buffer.append(chunk) | |
| buffer_tokens += chunk_tokens | |
| if buffer_tokens >= budget: | |
| await _submit_one(buffer, template_id, parser_cfg) | |
| buffer = [] | |
| buffer_tokens = 0 | |
| page_index_buffers[template_id] = buffer | |
| page_index_buffer_tokens[template_id] = buffer_tokens | |
| buffer = page_index_buffers[template_id] | |
| budget = _page_index_budget(template_id) | |
| buffer_tokens = page_index_buffer_tokens[template_id] | |
| for chunk in incoming_batch: | |
| text = chunk.get("content_with_weight") or chunk.get("text") or "" | |
| chunk_tokens = num_tokens_from_string(text if isinstance(text, str) else "") | |
| if buffer and buffer_tokens + chunk_tokens > budget: | |
| progress_cb(msg=f" page_index buffer flush ({buffer_tokens} tokens, {len(buffer)} chunks) for template ({template_ids_by_id[template_id]}/{total})") | |
| await _submit_one(buffer, template_id, parser_cfg) | |
| buffer = [] | |
| buffer_tokens = 0 | |
| buffer.append(chunk) | |
| buffer_tokens += chunk_tokens | |
| if buffer_tokens >= budget: | |
| progress_cb(msg=f" page_index buffer flush ({buffer_tokens} tokens, {len(buffer)} chunks) for template ({template_ids_by_id[template_id]}/{total})") | |
| await _submit_one(buffer, template_id, parser_cfg) | |
| buffer = [] | |
| buffer_tokens = 0 | |
| page_index_buffers[template_id] = buffer | |
| page_index_buffer_tokens[template_id] = buffer_tokens |
🤖 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 496 - 514, The
token-budget flushes in the page-index buffering loop should report progress
through the existing progress_cb mechanism, matching the analogous merge-flush
path. Add logging immediately before each _submit_one call triggered by buffer
overflow or reaching the budget, while leaving normal buffering and submission
behavior unchanged.
Source: Coding guidelines
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 420-433: The _struct_payload_chunk_ids function must not fall back
to all batch_ids when attribution is missing or invalid. Return only validated
selected IDs, or reject/quarantine the unscoped item, and add logging for this
fallback or rejection so unsupported chunks are never attributed silently.
🪄 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: 52dc391d-20f0-4502-9d8a-1cb663ac14d4
📒 Files selected for processing (2)
rag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/structure.py
| def _struct_payload_chunk_ids(payload: dict, batch_ids: list) -> list: | ||
| """Keep only model-selected chunk IDs that belong to the current batch.""" | ||
| raw_ids = payload.get("source_chunk_ids") | ||
| if isinstance(raw_ids, str): | ||
| raw_ids = [raw_ids] | ||
| if not isinstance(raw_ids, list): | ||
| raw_ids = [] | ||
| allowed = set(batch_ids) | ||
| selected = [] | ||
| for chunk_id in raw_ids: | ||
| chunk_id = str(chunk_id).strip() | ||
| if chunk_id in allowed and chunk_id not in selected: | ||
| selected.append(chunk_id) | ||
| return selected or list(batch_ids) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Do not broaden missing attribution to the entire batch.
return selected or list(batch_ids) turns missing, malformed, or out-of-batch model attribution into evidence from every chunk. That breaks scoped source attribution and can cause downstream consumers to cite unsupported chunks. Keep only validated IDs, or reject/quarantine unscoped items, and log the fallback instead of silently broadening it.
As per coding guidelines, **/*.py: Add logging for new flows.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/advanced_rag/knowlege_compile/structure.py` around lines 420 - 433, The
_struct_payload_chunk_ids function must not fall back to all batch_ids when
attribution is missing or invalid. Return only validated selected IDs, or
reject/quarantine the unscoped item, and add logging for this fallback or
rejection so unsupported chunks are never attributed silently.
Source: Coding guidelines
wangq8
left a comment
There was a problem hiding this comment.
PR Review: #17400 — fix: persist pipeline tree graph rows
Thanks for the fix! This addresses the real issue where Pipeline tree compilation only saved a graph blob but not the per-entity/per-relation rows that the structure graph API consumes. The approach (delete-then-reinsert for idempotency) is sound.
What looks good ✅
_struct_upsert_tree_graph_rowscorrectly mirrors the pattern used by other compilationsrewrite_duplicate_tree_namesis a nice UX improvement- The dynamic token-budget batching in
runner.pyis a sensible optimization - UI badges for entity types in the page_index tree view are clean
Items to address
1. Removal of batch_size_cap=1 for page_index templates (unrelated behavioral change)
The PR drops batch_size_cap=1 if ... page_index else None in compile_structure_from_text. Previously page_index was strictly single-chunk-per-batch; now it gets dynamically packed alongside other templates. This is a significant change to extraction behavior — multi-chunk batches may affect heading extraction quality — and it is not mentioned in the PR description. If intentional, please justify in the PR body. If accidental, restore the cap or split into a separate PR.
2. Chunk ID fallback is overly generous
def _struct_payload_chunk_ids(payload, batch_ids):
...
return selected or list(batch_ids) # attributes entity to *all* chunksWhen the model returns no valid chunk IDs, the entity is attributed to every chunk in the batch. A no-evidence entity should probably have an empty source_chunk_ids list rather than be incorrectly linked to all chunks. Consider return selected (allowing empty) or at minimum log a warning.
3. must_not deletion when compilation_template_id is None
template_filter = (
{"compilation_template_ids": [compilation_template_id]}
if compilation_template_id
else {"must_not": {"exists": "compilation_template_ids"}} # overly broad?
)When compilation_template_id is None, the delete condition removes all tree rows for the document that lack compilation_template_ids. If there are other legitimate tree compilations without template IDs, they would be silently wiped. Is the None path actually reachable? If so, consider a more targeted filter, or add a comment explaining why this is safe.
4. Missing tests
The new _struct_upsert_tree_graph_rows function and the dynamic batching logic in _submit_batches have no tests. Even a basic unit test for the delete-then-insert cycle and the chunk ID filtering would help prevent regressions.
5. Minor: source_chunk_ids always empty for tree relations
source_chunk_ids = payload.get("source_chunk_ids") or [] if kind == "entity" else []Tree relations are always stored with an empty source_chunk_ids. This is fine if intentional (relations do not map to specific chunks), but the source_chunk_ids field was added to the relation skeleton in the prompt too — if the model returns them, they are silently discarded. Either drop the field from the relation skeleton or preserve it.
Summary
The core fix is correct and well-structured. The main concern is the unrelated removal of batch_size_cap=1 for page_index, which should either be justified or split out. The other items are edge-case hardening. Approving conditionally on addressing item 1.
What problem does this PR solve?
Pipeline tree compilation only persisted a graph blob, while the structure graph API reads entity and relation rows. As a result, successfully generated tree data was returned as an empty template.
This PR persists Pipeline tree entities and child relations as independent structure rows, while retaining the compact graph blob for template discovery. Existing rows for the same document and template are removed before re-insertion to avoid stale data after recompilation.
Type of change