Repository navigation
Port dataset nav and structure graph fixes to Go, merge agents list - #18183
Conversation
Merge compilation template groups into agents list Order agents list by canvas category then name Install nav service in ingestor so tree/structure products reach the nav tree Set doc_id on nav_cluster rows so ES InsertChunks keeps them Return items key for nav list and children endpoints Return DatasetNavNode shape for nav list/children (snake_case, has_children) Port tree-to-graph projection: write entity/relation rows and graph blob for tree variant Port document structure graph endpoint to full Python parity Use readable nav cluster and doc names instead of internal ids Derive nav fallback title from first line, stripping markdown markers Emit nav_doc leaf when creating a new nav cluster
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
🚧 Files skipped from review as they are similar to previous changes (5)
📝 WalkthroughWalkthroughThe change adds RAPTOR tree-to-graph products, structured dataset graph retrieval, readable navigation payloads, and mixed agent and compilation-template-group listings. It also updates service contracts, validation, server wiring, and tests. ChangesKnowledge compilation and dataset navigation
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant RAPTOR
participant TreeGraph
participant Embedder
participant Navigation
RAPTOR->>TreeGraph: summary products
TreeGraph->>Embedder: entity and relation descriptions
Embedder-->>TreeGraph: embeddings
TreeGraph->>Navigation: graph products for dataset navigation
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: 8
🧹 Nitpick comments (6)
internal/service/agent.go (1)
712-721: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winSerialize group children after pagination.
marshalMergeGroupItemqueries and marshals child templates for every matching group beforeslicePageruns. A small page can therefore cause one query per unreturned group. Keep the group inmergeCanvasItem, sort and page first, then load children only for selected groups.🤖 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 `@internal/service/agent.go` around lines 712 - 721, Update the merge-group flow around marshalMergeGroupItem so groups are first stored as mergeCanvasItem entries, sorted, and passed through slicePage; only then call marshalMergeGroupItem for the selected groups before returning the response. Preserve existing ordering, pagination, and error handling while ensuring unreturned groups do not trigger child queries.internal/dao/compilation_template_group.go (1)
62-65: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove migration-history comments from the Go runtime path.
Keep comments focused on the current behavior. Do not retain Python implementation details as runtime documentation.
internal/dao/compilation_template_group.go#L62-L65: describe the exact owned-and-valid group filter without referring to Pythonlist_saved().internal/service/agent.go#L611-L619: describe category parsing and group inclusion without Python parity references.As per coding guidelines, “keep package and doc comments aligned with the current runtime path rather than migration history” and remove stale documentation.
🤖 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 `@internal/dao/compilation_template_group.go` around lines 62 - 65, Update the comments at internal/dao/compilation_template_group.go:62-65 and internal/service/agent.go:611-619 to describe only current runtime behavior. In the compilation template group comment, state the owned-and-valid filtering and built-in exclusion without Python migration references; in the agent comment, describe category parsing and group inclusion without Python parity references. No code changes are required.Source: Coding guidelines
internal/service/nlp/datasetnav.go (2)
1133-1136: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCall
contentHash8directly instead of adding a wrapper.
shortHash8only forwards tocontentHash8. Remove it and callcontentHash8inreadableClusterName.As per coding guidelines: "prefer deletion over shims, deprecated branches, wrapper APIs, and dual-track migrations".
🤖 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 `@internal/service/nlp/datasetnav.go` around lines 1133 - 1136, Remove the redundant shortHash8 wrapper and update readableClusterName to call contentHash8 directly, preserving the existing hash behavior without introducing a forwarding API.Source: Coding guidelines
437-457: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the duplicated
nav_docrow literal.This map literal repeats the merge-branch insert at lines 384-401. Only
parent_kwdanddepth_intdiffer. Two copies of the row schema drift apart as fields are added.♻️ Proposed helper
+// navDocRow builds the nav_doc leaf row for a document under the given parent. +func navDocRow(in nav.UpsertDocInput, parent string, depth int, vec []float32) map[string]interface{} { + return map[string]interface{}{ + "id": navDocID(in.TenantID, in.KbID, in.DocID), + "compile_kwd": navCompileKwd, + "available_int": 0, + "type_kwd": "nav_doc", + "title_kwd": cleanTitle(fallbackTitle(in.Summary)), + "parent_kwd": parent, + "depth_int": depth, + "doc_id": in.DocID, + "doc_count_int": 1, + "content_with_weight": payloadJSONNav(map[string]interface{}{"type": "nav_doc", "description": in.Summary}), + "q_" + fmt.Sprintf("%d", len(vec)) + "_vec": f32ToF64Slice(vec), + } +}Then both branches call
de.InsertChunks(ctx, []map[string]interface{}{navDocRow(in, parent, depth+1, vec)}, idx, in.KbID).As per coding guidelines: "When old and new implementations coexist, converge on one implementation path".
🤖 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 `@internal/service/nlp/datasetnav.go` around lines 437 - 457, Extract the duplicated nav_doc map construction into a shared navDocRow helper, preserving all existing fields while accepting the parent name, depth, and vector as parameters. Update both the merge branch and the new-cluster branch to call this helper when invoking de.InsertChunks, so only one row schema is maintained.Source: Coding guidelines
internal/service/dataset_artifact_service.go (1)
652-656: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDrop the migration history from the doc comment.
The comment describes the removed
NavigationItemtype. Keep only the current contract.♻️ Proposed comment trim
-// ListNavClusters returns the navigation clusters of a dataset. It delegates to -// the ES-backed NavService and returns the frontend DatasetNavNode shape -// (snake_case NavNode JSON), matching Python GET /navigation exactly. The old -// NavigationItem{name,title,count} shape did not match the frontend interface -// and has been removed. +// ListNavClusters returns the navigation clusters of a dataset. It delegates to +// the ES-backed NavService and returns the snake_case NavNode shape consumed by +// the frontend navigation tree.As per coding guidelines: "keep package and doc comments aligned with the current runtime path rather than migration history".
🤖 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 `@internal/service/dataset_artifact_service.go` around lines 652 - 656, Update the doc comment for ListNavClusters to remove the migration history mentioning the removed NavigationItem type, old shape, and removal. Keep only the current contract: delegation to the ES-backed NavService and return of the frontend DatasetNavNode shape matching Python GET /navigation.Source: Coding guidelines
internal/handler/dataset_artifact.go (1)
342-344: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winRemove the unused
GraphTypefield fromDocumentStructureGraphInput.The handler and frontend send only
keywords. No repository consumer sendsgraph_typeor reads the old navigation and graph keys.🤖 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 `@internal/handler/dataset_artifact.go` around lines 342 - 344, Remove the unused GraphType field from DocumentStructureGraphInput and update its construction, binding, and serialization paths to accept only keywords. Preserve the handler’s items response contract and avoid retaining compatibility for graph_type or legacy navigation/graph keys.
🤖 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 `@internal/ingestion/component/knowledge_compiler/component.go`:
- Around line 571-611: Extract the shared entity/relation/graph and
mention-count metadata mapping from the current branch and
common.VariantStructure into one private helper. Update both variant paths to
call that helper, preserving the existing kind-specific fields, lowercase entity
name behavior, error propagation, and metadata keys without retaining duplicate
mapping logic or transitional wrappers.
In `@internal/ingestion/component/knowledge_compiler/tree/graph.go`:
- Around line 134-137: Correct the collapseUnary documentation in
internal/ingestion/component/knowledge_compiler/tree/graph.go lines 134-137 to
state that the wrapper retains its title/identity while adopting the child’s
descendants; update the fixture comment in
internal/ingestion/component/knowledge_compiler/tree/graph_test.go lines 15-17
to expect A rather than B after collapse.
In `@internal/service/agent.go`:
- Around line 622-624: Update the groups-only branch in the agent listing method
to return an empty result when the caller’s userID is absent from
effectiveOwnerIDs, before invoking listAgentsGroupsOnly. Preserve the existing
delegation when the caller is an effective owner, and add coverage for
compilation_template_group with another owner’s ID.
- Around line 877-885: Prevent overflow in the pagination calculation before
slicing the collection: update the pagination logic around the start/end
computation to safely handle unbounded positive page and pageSize values,
returning an empty result when the requested page begins beyond the collection
instead of producing a negative index. Preserve normal pagination behavior for
valid in-range values and ensure no slice occurs with overflowed indices.
In `@internal/service/dataset_structure_graph.go`:
- Around line 804-824: Remove the nil insertion/readback block from
resolveGraphBucket and eliminate the now-unused templateMetaByID parameter and
map construction. Preserve the existing kind-only fallback over actual template
metadata, and update all callers—including keywordSubgraph—to use the simplified
signature without introducing nil entries.
- Around line 492-520: Update graphRowSearch to accept an offset parameter and
use it in the search request instead of always sending zero. Pass entityOffset
from the large-bucket entity loop, and update every other graphRowSearch call
site to pass 0 so existing behavior is preserved.
In `@internal/service/nlp/datasetnav.go`:
- Around line 186-192: Preserve the stored lookup key in NavNode.Name for
cluster rows when building the node in the dataset navigation flow. Restrict the
graphIsRawID readable-name fallback to non-cluster rows, or otherwise keep the
cluster key available to ListChildren and the navigation handler so existing
cluster records continue expanding correctly.
- Line 425: Prevent cluster nodes from carrying a document ID into deletion:
update the row-to-node mapping around nodeFromRow so rows producing NavNode.Type
== "cluster" leave DocID empty while document nodes retain in.KbID. Ensure
DeleteNav does not call RemoveDoc for cluster nodes.
---
Nitpick comments:
In `@internal/dao/compilation_template_group.go`:
- Around line 62-65: Update the comments at
internal/dao/compilation_template_group.go:62-65 and
internal/service/agent.go:611-619 to describe only current runtime behavior. In
the compilation template group comment, state the owned-and-valid filtering and
built-in exclusion without Python migration references; in the agent comment,
describe category parsing and group inclusion without Python parity references.
No code changes are required.
In `@internal/handler/dataset_artifact.go`:
- Around line 342-344: Remove the unused GraphType field from
DocumentStructureGraphInput and update its construction, binding, and
serialization paths to accept only keywords. Preserve the handler’s items
response contract and avoid retaining compatibility for graph_type or legacy
navigation/graph keys.
In `@internal/service/agent.go`:
- Around line 712-721: Update the merge-group flow around marshalMergeGroupItem
so groups are first stored as mergeCanvasItem entries, sorted, and passed
through slicePage; only then call marshalMergeGroupItem for the selected groups
before returning the response. Preserve existing ordering, pagination, and error
handling while ensuring unreturned groups do not trigger child queries.
In `@internal/service/dataset_artifact_service.go`:
- Around line 652-656: Update the doc comment for ListNavClusters to remove the
migration history mentioning the removed NavigationItem type, old shape, and
removal. Keep only the current contract: delegation to the ES-backed NavService
and return of the frontend DatasetNavNode shape matching Python GET /navigation.
In `@internal/service/nlp/datasetnav.go`:
- Around line 1133-1136: Remove the redundant shortHash8 wrapper and update
readableClusterName to call contentHash8 directly, preserving the existing hash
behavior without introducing a forwarding API.
- Around line 437-457: Extract the duplicated nav_doc map construction into a
shared navDocRow helper, preserving all existing fields while accepting the
parent name, depth, and vector as parameters. Update both the merge branch and
the new-cluster branch to call this helper when invoking de.InsertChunks, so
only one row schema is maintained.
🪄 Autofix
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: 97b501a4-9e27-489a-bd36-54a13276e25c
📒 Files selected for processing (19)
cmd/ragflow_server.gointernal/dao/compilation_template_group.gointernal/handler/agent_test.gointernal/handler/dataset_artifact.gointernal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/golden/metrics.gointernal/ingestion/component/knowledge_compiler/tree/graph.gointernal/ingestion/component/knowledge_compiler/tree/graph_test.gointernal/ingestion/component/knowledge_compiler/tree/raptor.gointernal/service/agent.gointernal/service/agent_test.gointernal/service/compilation_template_service.gointernal/service/compilation_template_service_test.gointernal/service/dataset_artifact_service.gointernal/service/dataset_structure_graph.gointernal/service/dataset_structure_graph_test.gointernal/service/nav/nav.gointernal/service/nlp/datasetnav.gointernal/service/nlp/datasetnav_test.go
| // collapseUnary merges a node that wraps exactly one child into that child, | ||
| // mirroring Python raptor_tree_to_graph._collapse_unary: the parent's and the | ||
| // child's descriptions/source-chunk-ids are concatenated (dedup'd), then the | ||
| // collapsed node adopts the child's children. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the unary-collapse documentation.
The algorithm preserves the wrapper node title and adopts the child descendants. It does not merge the wrapper node into its child.
internal/ingestion/component/knowledge_compiler/tree/graph.go#L134-L137: describe the retained wrapper identity and adopted child descendants.internal/ingestion/component/knowledge_compiler/tree/graph_test.go#L15-L17: update the fixture comment to expectA, notB, after collapse.
As per coding guidelines: “Remove dead tests, commented-out code, stale documentation, and ‘move later’ notes instead of preserving them.”
📍 Affects 2 files
internal/ingestion/component/knowledge_compiler/tree/graph.go#L134-L137(this comment)internal/ingestion/component/knowledge_compiler/tree/graph_test.go#L15-L17
🤖 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 `@internal/ingestion/component/knowledge_compiler/tree/graph.go` around lines
134 - 137, Correct the collapseUnary documentation in
internal/ingestion/component/knowledge_compiler/tree/graph.go lines 134-137 to
state that the wrapper retains its title/identity while adopting the child’s
descendants; update the fixture comment in
internal/ingestion/component/knowledge_compiler/tree/graph_test.go lines 15-17
to expect A rather than B after collapse.
Source: Coding guidelines
| } | ||
| _, err = de.InsertChunks(ctx, []map[string]interface{}{{ | ||
| "id": navClusterID(in.TenantID, in.KbID, name), | ||
| "doc_id": in.KbID, // cluster rows carry the kb as doc_id (Python _build_nav_cluster_row), so ES InsertChunks does not skip them |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Does ListChildren return nav_cluster rows as well as nav_doc rows?
ast-grep run --pattern 'func (s *NavService) ListChildren($$$) { $$$ }' --lang go internal/service/nlp/datasetnav.go
# What does deleteNavDoc / RemoveDoc filter on?
rg -nP --type=go -C10 'func \(s \*NavService\) (RemoveDoc|deleteNavDoc)\(' internal/service/nlp/datasetnav.goRepository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- datasetnav.go symbols ---'
ast-grep outline internal/service/nlp/datasetnav.go
printf '%s\n' '--- relevant definitions and call sites ---'
rg -n -C12 --type=go \
'ListChildren|DeleteNav|RemoveDoc|deleteNavDoc|nodeFromRow|nav_cluster|NavNode' \
internal/service/nlp/datasetnav.go internal/service/nlpRepository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- DeleteNav implementations and callers ---'
rg -n -C14 --type=go \
'func .*DeleteNav|DeleteNav\(|ListChildren\(' \
internal
printf '%s\n' '--- NavNode definition and cluster row builders ---'
rg -n -C10 --type=go --type=py \
'type NavNode|NavNode struct|_build_nav_cluster_row|build_nav_cluster_row|doc_id.*kb|nav_cluster' \
. | head -n 500Repository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- exact deletion path ---'
sed -n '675,714p' internal/service/dataset_artifact_service.go
sed -n '150,205p' internal/service/nlp/datasetnav.go
sed -n '963,1028p' internal/service/nlp/datasetnav.go
printf '%s\n' '--- NavNode shape and relevant tests ---'
rg -n -C12 --type=go 'type NavNode struct|TestDeleteNav_RemovesOnlyDirectDocChildren|doc_id.*kb_id|doc_id.*in.KbID' internal/serviceRepository: infiniflow/ragflow
Length of output: 35248
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
nav = Path("internal/service/nlp/datasetnav.go").read_text()
artifact = Path("internal/service/dataset_artifact_service.go").read_text()
checks = {
"cluster rows store kbID as doc_id": '"doc_id": in.KbID' in nav,
"ListChildren filters only by parent_kwd": 'navFilter(map[string]interface{}{"parent_kwd": []string{name}})' in nav,
"ListChildren maps nav_cluster rows to cluster nodes": 'if typ == "nav_cluster" {' in nav and 'nodeType = "cluster"' in nav,
"nodeFromRow copies doc_id unconditionally": 'DocID: firstStringValue(row["doc_id"])' in nav,
"DeleteNav calls ListChildren for each root cluster": 'ns.ListChildren(ctx, tenantID, datasetID, c.Name, 0, 10000)' in artifact,
"DeleteNav calls RemoveDoc for every non-empty DocID": 'if ch.DocID != "" {' in artifact and 'ns.RemoveDoc(ctx, tenantID, datasetID, ch.DocID)' in artifact,
}
for label, value in checks.items():
print(f"{label}: {value}")
assert value, label
# Model the relevant data-shape transformation and call edge.
kb_id = "kb-1"
cluster_row = {"type_kwd": "nav_cluster", "doc_id": kb_id}
node = {"Type": "cluster", "DocID": cluster_row["doc_id"]}
root_children = [node]
remove_doc_args = [
(kb_id, child["DocID"])
for child in root_children
if child["DocID"] != ""
]
print("nested cluster child reaches RemoveDoc with:", remove_doc_args)
assert remove_doc_args == [(kb_id, kb_id)]
PYRepository: infiniflow/ragflow
Length of output: 527
Suppress DocID for cluster nodes. ListChildren returns nested nav_cluster rows, and nodeFromRow copies their doc_id (kbID) into NavNode.DocID. DeleteNav then calls RemoveDoc(..., kbID) for that cluster. Set DocID to empty when NavNode.Type == "cluster", or filter DeleteNav to document nodes only.
🤖 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 `@internal/service/nlp/datasetnav.go` at line 425, Prevent cluster nodes from
carrying a document ID into deletion: update the row-to-node mapping around
nodeFromRow so rows producing NavNode.Type == "cluster" leave DocID empty while
document nodes retain in.KbID. Ensure DeleteNav does not call RemoveDoc for
cluster nodes.
… cluster key intact, graph search offset, shared structure-graph mapping
Fix compilation template config validation for JSONMap; merge template groups into agents list ordered by category/name; install nav service in ingestor; write readable nav cluster/doc names and emit nav_doc leaves; port tree-to-graph projection and full document structure graph endpoint parity.