Repository navigation
Port Python agentic search to Go (nav service, harness, tools) - #17702
Conversation
… harness + tools) Implements the Go port of Python rag/advanced_rag agentic search: - dataset_nav read/write service: internal/service/nav (interface leaf pkg) + internal/service/nlp/datasetnav.go (ES-backed incremental upsert/remove + KNN search + list clusters/children, available_int=0 nav rows). - Remove the standalone datasetnav KnowledgeCompiler variant (no Python kind); add tree + structure(page_index) compile-complete by-product hooks instead. - Deprecate DatasetArtifactService nav methods in favor of NavService (field mismatch with Python was dead code); handler REST shape unchanged. - Agent tools: dataset_navigation_by_tree (einotool.BaseTool, LLM two-round selection), hybrid/vector/bm25_search, ontology/mindmap_navigate. - harness package: route/planner/orchestrator/sufficiency/answer + RunAgenticRAG graph; THINKING_MODES (low/medium/high/ultra). - RetrievalRequest.DocScope wired to nlp.DocIDs; real embedder wiring. - Tests: unit (in-memory engine) + integration (available_int=0 isolation). Note: ragflow_server build artifact added to .gitignore.
…e scope test - Add harness.ProductionRunner that wires the real hybrid_search tool and the canonical dataset-nav router (NavigateDatasetByTree) into RunAgenticRAG, so the tools are actually invoked rather than merely registered. - Converge nav routing to the single full LLM two-round entry in harness; tool.DatasetNavigationByTree stays as the thin registered einotool. - Add E2E test proving question -> doc-scope routing -> scoped retrieval (search tool receives doc_scope=[d1,d2]). - Clarify DatasetArtifactService DeleteNav/DeleteNavNode as minimal-loop approximations (drain direct doc children only; no subtree/cascade), and add tests documenting this; DeleteNav previously deleted nothing (root clusters have empty DocID), now drains root-cluster doc children.
…omponent cycle - Add internal/agent/chat (leaf, deps only eino schema + gorm) hosting the Invoker interface, Request/Response types and the SetDefaultInvoker / GetDefaultInvoker singleton. This is the shared LLM seam. - component/llm.go: ChatInvoker/ChatInvokeRequest/ChatInvokeResponse become aliases of chat types; SetDefaultChatInvoker/GetDefaultChatInvokerForTest delegate to chat; production einoChatInvoker registered as chat default at init. getDefaultChatInvoker falls back to einoChatInvoker when unset. - harness (route/planner/navigation/answer/datasetnav): switch from component.GetDefaultChatInvokerForTest to chat.GetDefaultInvoker, removing the component import there. - Resolves the long-standing architecture debt: internal/agent/tool can now import the chat seam to write LLM tools without an import cycle.
Two correctness fixes from review:
1. dataset_navigation_by_tree now actually routes by the query: it calls
NavService.Search with topic+keywords (semantic KNN over the nav tree) to
return RELEVANT doc ids, falling back to a root-cluster walk only when
semantic routing yields nothing. Previously it ignored topic/keywords and
returned arbitrary docs from the first clusters.
2. Multi-KB sessions no longer collapse to the first KB:
- canvasDatasetID -> canvasDatasetIDs (returns all explicit dataset ids).
- tool.DatasetNavigationByTree and harness.ProductionRunner.routeDocs now
route across every bound dataset and merge the doc scopes, so retrieval in
the other KBs is reachable.
Tests: dataset_navigation_test.go (topic routing, multi-KB search-per-dataset,
canvasDatasetIDs multi/dedup) + production_test.go E2E uses kb1+kb2 and asserts
doc_scope + kb_ids include all bound KBs.
📝 WalkthroughWalkthroughThe PR adds an agentic-RAG workflow, shared chat invocation, dataset navigation services and tools, compiler-generated navigation artifacts, document-scoped retrieval, and navigation API delegation. It removes standalone dataset-navigation compilation and adds tests across these flows. ChangesAgentic search and dataset navigation
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested labels: 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: 14
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
🟡 Minor comments (11)
tasks/agentic_search_port_plan.md-496-498 (1)
496-498: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winRemove the duplicate section heading.
## 8. 参考文件索引appears twice. Keep one heading to avoid duplicate navigation anchors.🤖 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 `@tasks/agentic_search_port_plan.md` around lines 496 - 498, Remove the duplicate “## 8. 参考文件索引” heading, keeping a single instance of this section heading so navigation anchors remain unique.Source: Linters/SAST tools
tasks/agentic_search_port_plan.md-234-234 (1)
234-234: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winSpecify the code-fence language.
The directory-listing fence at Line 234 has no language identifier. Use
textso Markdown tooling can validate and render it correctly.🤖 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 `@tasks/agentic_search_port_plan.md` at line 234, Update the directory-listing code fence in the port plan document to specify the text language identifier, while preserving its existing contents.Source: Linters/SAST tools
internal/service/dataset_artifact_service.go-676-689 (1)
676-689: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
DeleteNavhidesListChildrenfailures.Line 679 uses
continuewhenListChildrenreturns an error. The method then reports success with an incomplete count. The caller cannot tell a clean delete from a partial delete. Return the error, or at minimum log it with the cluster name.🐛 Proposed fix
for _, c := range clusters { children, _, err := ns.ListChildren(ctx, tenantID, datasetID, c.Name, 0, 10000) if err != nil { - continue + return deleted, fmt.Errorf("datasetnav: list children of cluster %q: %w", c.Name, err) }🤖 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 676 - 689, Update DeleteNav’s ListChildren error handling to propagate the failure instead of silently continuing, so the caller cannot receive a successful but incomplete deletion result. Preserve the existing child-removal and deleted-count behavior for clusters whose children are listed successfully.internal/ingestion/component/knowledge_compiler/component_test.go-342-346 (1)
342-346: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThis fixture hides the summary/vector mismatch.
The graph product supplies both
Content(the graph JSON) andVector.upsertStructureNavtherefore stores the vector of the JSON next to the summary text derived from it. The test asserts onlyfake.summary, so the mismatch passes. See the comment oninternal/ingestion/component/knowledge_compiler/component.golines 286-298.After the production fix, extend this test to assert the value of
in.Embedd.🤖 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/component_test.go` around lines 342 - 346, Extend the test around upsertStructureNav to assert fake.in.Embedd alongside fake.summary, verifying that the stored embedding matches the summary text rather than the original graph JSON vector. Use the existing fixture and fake input symbols without changing production behavior.internal/ingestion/component/knowledge_compiler/component.go-189-195 (1)
189-195: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winGuard against an empty
in.DocIDbefore writing the nav row.
in.DocIDcomes from thedoc_idinput. Neither helper nornav.UpsertDocrejects an empty value.NavService.UpsertDocwritesdoc_idandtitle_kwdfrom that field and later reads it back with adoc_idfilter. An empty value therefore creates a nav row that no document owns, and the dedup lookup for the next empty-doc_iddocument matches it. The routing tool then returns an entry thatcollectdiscards, so the row is pure noise in the index.Skip the by-product when the document id is empty.
🛡️ Proposed guard
- if len(navProducts) > 0 { + if len(navProducts) > 0 && in.DocID != "" { if navVariant == common.VariantTree { upsertTreeNav(ctx, navDeps, in.DocID, navProducts) } else { upsertStructureNav(ctx, navDeps, in.DocID, navProducts) } }🤖 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/component.go` around lines 189 - 195, Update the navigation upsert block around upsertTreeNav and upsertStructureNav to require both a non-empty in.DocID and non-empty navProducts. Skip all nav writes when in.DocID is empty, while preserving the existing variant-based helper selection for valid document IDs.internal/ingestion/component/knowledge_compiler/component.go-11-11 (1)
11-11: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUse the project logger for nav by-product skips.
These skip and failure messages use the standard logger, so they do not go through the Zap sink used by ingestion components. Replace the
log.Printfcalls inupsertTreeNavandupsertStructureNavwith the project logger so missing navigation rows are captured consistently.🤖 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/component.go` at line 11, Replace the standard logger usage in upsertTreeNav and upsertStructureNav with the project logger for all navigation skip and failure messages, removing the corresponding log.Printf calls while preserving their existing messages and control flow.internal/agent/harness/navigation.go-124-130 (1)
124-130: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThe evidence cap is checked after the append, so the result can exceed
maxEvidenceChunks.
loadChunksByIDslimits each call tomaxEvidenceChunks. The loop appends a full batch and only then tests the total. With two or more documents in scope the returned payload can hold up to twice the cap. Trim after the loop.♻️ Proposed fix
var chunks []map[string]interface{} for _, ids := range idsByDoc { chunks = append(chunks, loadChunksByIDs(ctx, tenantID, dedupStrings(ids))...) if len(chunks) >= maxEvidenceChunks { + chunks = chunks[:maxEvidenceChunks] break } }Note that
idsByDocis a map, so the iteration order is random. The set of documents that survive the cap changes between identical requests. If deterministic results matter, iterate over a sorted key list.🤖 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/agent/harness/navigation.go` around lines 124 - 130, Ensure the evidence collection in the idsByDoc loop never returns more than maxEvidenceChunks by trimming chunks after accumulation to exactly that cap, while preserving the existing loading behavior. Because idsByDoc is a map, iterate its document keys in sorted order before calling loadChunksByIDs to make capped results deterministic.internal/agent/harness/orchestrator.go-197-216 (1)
197-216: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winByte-offset string truncation splits multi-byte UTF-8 runes in
orchestrator.goanddatasetnav.go. Both sites cut a string with a byte index instead of a rune index. For CJK, Cyrillic, or accented content this leaves an invalid trailing rune. The truncated text is sent to the model in a prompt and, in the orchestrator case, is also scanned byCrossCheckClaimfor numbers and entities.
internal/agent/harness/orchestrator.go#L197-L216: replacetext[:200]insummarizewith a rune-safe truncation.internal/agent/harness/datasetnav.go#L137-L140: replacedesc[:300]inaskNavSelectwith the same rune-safe truncation.🐛 Proposed shared fix
Add one helper, for example in
orchestrator.go:// truncateRunes cuts s to at most n runes without splitting a rune. func truncateRunes(s string, n int) string { if n <= 0 { return "" } r := []rune(s) if len(r) <= n { return s } return string(r[:n]) }Then in
internal/agent/harness/orchestrator.go:- if len(text) > 200 { - text = text[:200] - } + text = truncateRunes(text, 200)And in
internal/agent/harness/datasetnav.go:desc := strings.Join(strings.Fields(it.Description), " ") - if len(desc) > 300 { - desc = desc[:300] - } + desc = truncateRunes(desc, 300)🤖 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/agent/harness/orchestrator.go` around lines 197 - 216, Replace byte-based truncation with a shared rune-safe helper (such as truncateRunes) that limits text without splitting UTF-8 characters. Update summarize in internal/agent/harness/orchestrator.go:197-216 to use it for the 200-rune limit, and askNavSelect in internal/agent/harness/datasetnav.go:137-140 to use it for the 300-rune limit.internal/agent/harness/answer_test.go-29-36 (1)
29-36: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winMake
installChatrestore the package-level invoker state.
TestFormalizeAnswer_GeneratesandTestFormalizeAnswer_PartialPreambleboth callinstallChat, but the test file does not define it. Add the missing helper as a no-op wrapper aroundinternal/agent/chat.SetDefaultInvoker(nil)witht.Cleanup, or remove these calls. Leaving it undefined makesinternal/agent/harness/answer_test.gofail at build time.🤖 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/agent/harness/answer_test.go` around lines 29 - 36, Define the missing installChat test helper used by TestFormalizeAnswer_Generates and TestFormalizeAnswer_PartialPreamble, configuring the package-level chat invoker and registering t.Cleanup to restore it with internal/agent/chat.SetDefaultInvoker(nil); alternatively remove both calls if the helper is unnecessary, while keeping the tests buildable.internal/agent/harness/navigation.go-41-41 (1)
41-41: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRemove the unreachable
catalogKindsentries or restore the original kinds.
normalizeKindfilterspage_index/pageindexandknowledge_graphtotimeline, so catalog kind lookup can no longer match those template inputs. AlignnormalizeKindwith the compilation templatecompilation_template_kind_kwdvalues (page_index,pageindex,knowledge_graph) instead of leaving these keys unreachable.🤖 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/agent/harness/navigation.go` at line 41, Align normalizeKind with the compilation_template_kind_kwd values by preserving page_index, pageindex, and knowledge_graph as supported catalog kinds, and remove unreachable or mismatched entries from catalogKinds. Ensure catalog kind lookup can match these template inputs without changing handling for the other valid kinds.Source: Coding guidelines
internal/agent/tool/dataset_navigation.go-38-44 (1)
38-44: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
DocScopefield is unused.
datasetNavigationArgs.DocScopeis declared but never read inInvokableRun. No doc-scope filtering is applied in either the semantic-search path or the cluster-walk fallback. Either wire it into the search/fallback logic or remove it.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 `@internal/agent/tool/dataset_navigation.go` around lines 38 - 44, Remove the unused datasetNavigationArgs.DocScope field and its JSON tag, since InvokableRun does not read or apply it in either navigation path. Ensure no stale references remain in related argument handling or documentation.Source: Coding guidelines
🧹 Nitpick comments (25)
internal/service/nlp/datasetnav.go (2)
497-505: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
hash/fnvinstead of a hand-rolled FNV-1a.The constants 2166136261 and 16777619 reimplement FNV-1a 32-bit, which the standard library already provides. The standard library version also removes the
uint32(s[i])conversion that the static analysis tool flagged. That warning is a false positive, becauses[i]is abyteand the conversion widens.♻️ Proposed refactor
+// contentHash8 is a stable 8-char FNV-1a hash. func contentHash8(s string) string { - h := uint32(2166136261) - for i := 0; i < len(s); i++ { - h ^= uint32(s[i]) - h *= 16777619 - } - return fmt.Sprintf("%08x", h) + h := fnv.New32a() + _, _ = h.Write([]byte(s)) + return fmt.Sprintf("%08x", h.Sum32()) }Add the import:
import "hash/fnv"🤖 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 497 - 505, Update contentHash8 to use the standard library hash/fnv implementation for FNV-1a 32-bit instead of manually maintaining the hash constants and loop; preserve the existing stable 8-character hexadecimal output.Source: Linters/SAST tools
310-321: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueRemove
depth_intif no external code reads it.Searches found no
depth_intconsumers in the repo. Since this field is only written here and never read, remove it from the navigation chunk inserts rather than fixing the returned depth.🤖 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 310 - 321, Remove the depth_int field from the map passed to InsertChunks in the navigation chunk insertion flow, leaving all other chunk metadata unchanged.Source: Coding guidelines
internal/service/nlp/datasetnav_test.go (2)
329-365: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd a nested-descent test for
findBestCluster.Every current test uses a single level of clusters. The stub embedder derives the vector from the first character only, so all summaries in a test either match at similarity 1.0 or match weakly. No test builds a parent cluster with a weak child, which is the case that exposes the descent defect described in
internal/service/nlp/datasetnav.goLines 354-391.Add a test that creates a parent cluster, adds a child cluster with a low-similarity vector, and then upserts a document that closely matches the parent. Assert that the document merges into the parent instead of creating a new root cluster.
I can generate this test. Tell me if you want it.
🤖 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_test.go` around lines 329 - 365, Add a nested-descent test alongside TestNavService_Acceptance4_ListChildren that constructs a parent cluster, inserts a low-similarity child cluster, then upserts a document closely matching the parent. Assert the document merges into the existing parent rather than creating a new root cluster, exercising findBestCluster’s nested traversal path.
223-249: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
strconv.Itoa, and guard the stub embedder against empty text.
strconvItoareimplementsstrconv.Itoa. The coding guidelines prefer well-known libraries over hand-rolled implementations of standard algorithms.
stubNavEmbedder.Encodealso indexest[0]at Line 244. An empty text panics.NavEmbedder.Encodein production filters blank texts, so a future test that passes an empty string would fail with a panic instead of a clear assertion.♻️ Proposed refactor
-func strconvItoa(n int) string { - if n == 0 { - return "0" - } - digits := []byte{} - for n > 0 { - digits = append([]byte{byte('0' + n%10)}, digits...) - n /= 10 - } - return string(digits) -}Replace the two call sites with
strconv.Itoaand add thestrconvimport.for i, t := range texts { dim := 8 v := make([]float32, dim) + seed := 0 + if t != "" { + seed = int(t[0]) + } for d := 0; d < dim; d++ { - v[d] = float32(int(t[0]) + d) + v[d] = float32(seed + d) } out[i] = v }🤖 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_test.go` around lines 223 - 249, Replace the hand-rolled strconvItoa helper and its call sites with strconv.Itoa, adding the strconv import and removing the helper. Update stubNavEmbedder.Encode to handle empty text safely before accessing t[0], preserving deterministic vectors for non-empty texts.Source: Coding guidelines
internal/service/nav_embedder.go (1)
54-72: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win
Encodedrops blank texts, so the output is not index-aligned with the input.The returned slice is shorter than
textswhen any entry is blank. A caller that pairstexts[i]with the result at indexigets a wrong vector. Current callers ininternal/service/nlp/datasetnav.gopass exactly one text, so the defect is latent. Either preserve alignment by emitting anilvector for each blank entry, or state the filtering behavior in theEncodedoc comment.Line 68 also shadows the receiver
ewith the loop variable. Rename the loop variable for clarity.♻️ Proposed refactor
out := make([][]float32, 0, len(embeds)) - for _, e := range embeds { - out = append(out, toF32(e.Embedding)) + for _, emb := range embeds { + out = append(out, toF32(emb.Embedding)) }🤖 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/nav_embedder.go` around lines 54 - 72, Update Encode to preserve one output position per input text by emitting a nil vector for blank entries while embedding only non-blank texts, then map returned embeddings back to their original indices. Rename the loop variable that currently shadows receiver e to a distinct name, preserving existing error handling and embedding behavior for non-blank inputs.internal/agent/component/llm.go (2)
145-154: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCollapse the redundant nil branch and correct the stale comment.
Both branches of
SetDefaultChatInvokercallchat.SetDefaultInvoker(inv). Thenilcheck has no effect. The comment also states that the production invoker is registered incmd/server_main.go, but Line 177 registers it in this file'sinit().♻️ Proposed fix
// SetDefaultChatInvoker delegates to the shared chat package singleton (test // helper). Pass nil to restore the "not configured" state. The production -// einoChatInvoker is registered at boot in cmd/server_main.go. +// einoChatInvoker is registered by this package's init(). func SetDefaultChatInvoker(inv ChatInvoker) { - if inv == nil { - chat.SetDefaultInvoker(nil) - return - } chat.SetDefaultInvoker(inv) }🤖 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/agent/component/llm.go` around lines 145 - 154, Update SetDefaultChatInvoker to directly delegate inv to chat.SetDefaultInvoker without the redundant nil branch, preserving nil passthrough behavior. Correct the surrounding comment to state that the production einoChatInvoker is registered by this file’s init() rather than cmd/server_main.go.Source: Coding guidelines
162-179: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConverge on one default-invoker path.
init()installs&einoChatInvoker{}as the shared default, whilegetDefaultChatInvoker()also returns a fresh&einoChatInvoker{}when the shared default is nil. Restore it through the shared default or remove the local fallback; otherwiseSetDefaultChatInvoker(nil)resets the singleton but the component still falls back to production instead of exposing the unconfigured state.🤖 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/agent/component/llm.go` around lines 162 - 179, Unify default invoker resolution between init and getDefaultChatInvoker: remove the local &einoChatInvoker{} fallback from getDefaultChatInvoker and rely on chat.GetDefaultInvoker() after init installs the production default. Preserve SetDefaultChatInvoker(nil) as an unconfigured state instead of silently recreating the production invoker.Source: Coding guidelines
internal/service/dataset_artifact_service.go (2)
621-625: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the DEPRECATED markers and the migration notes.
All four navigation methods are the current runtime path. Their doc comments mark them DEPRECATED, describe the removed implementation, compare the behavior to Python
delete_nav, and record "future NavService work". The coding guidelines forbid dual-track migration notes and stale superseded documentation, and require deletion over deprecation markers on code that is still the only path.Keep the behavioral contract, and delete the history.
♻️ Proposed doc rewrite
-// ListNavClusters returns the navigation clusters of a dataset. It is DEPRECATED -// and now delegates to the ES-backed NavService (internal/service datasetnav): -// the previous implementation queried nav_cluster_kwd/count_int fields that -// Python never writes, so it could never read the real nav tree. Do not add -// field-level patches here — route everything through NavService. +// ListNavClusters returns the root navigation clusters of a dataset.-// ListNavChildren returns the children of a navigation cluster. DEPRECATED — -// delegates to NavService.ListChildren. +// ListNavChildren returns the direct children of a navigation cluster.-// DeleteNav removes the direct nav_doc children of every root cluster of a -// dataset. DEPRECATED — this is the minimal-loop approximation of Python -// delete_nav: it drains only the immediate nav_doc rows under root clusters and -// does NOT implement Python's full subtree traversal or empty-cluster cascade -// cleanup. Prefer the NavService (future work) for a complete delete. Returns -// the number of nav_doc rows removed. +// DeleteNav removes the direct nav_doc children of every root cluster of a +// dataset. It does not traverse sub-clusters and does not remove empty +// clusters. It returns the number of nav_doc rows removed.-// DeleteNavNode deletes the direct nav_doc children of a named cluster. -// DEPRECATED — the minimal loop only drains immediate doc children (returns the -// count); it does NOT delete sub-clusters recursively nor perform Python's -// empty-cluster cascade. A full tree-node delete is future NavService work. +// DeleteNavNode removes the direct nav_doc children of the named cluster. It +// does not remove sub-clusters. It returns the number of nav_doc rows removed.Also applies to: 642-643, 660-665, 693-696
🤖 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 621 - 625, Update the doc comments for all four navigation methods, including ListNavClusters and the methods at the other referenced locations, to remove DEPRECATED markers, migration/history notes, removed-implementation details, Python behavior comparisons, and future-work notes. Preserve only concise documentation of each method’s current behavioral contract and NavService-backed behavior.Source: Coding guidelines
631-631: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winReplace the repeated hardcoded page size of 10000.
Five call sites pass
0, 10000as page and page size. Two consequences follow.First, a dataset with more than 10000 clusters or children is silently truncated.
DeleteNavandDeleteNavNodethen delete a subset and still returnnil, so the caller believes the delete completed.Second, a single 10000-row read per cluster inside the
DeleteNavloop makes the delete cost grow with the cluster count multiplied by the page size.Extract a named constant, and page until the returned
totalis consumed.Also applies to: 649-649, 671-671, 677-677, 703-703
🤖 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` at line 631, Replace the repeated 10000 page-size literals in the dataset artifact service call sites with a named constant. Update the cluster and child listing flows in DeleteNav and DeleteNavNode to fetch successive pages until all rows indicated by total are consumed, ensuring deletions are complete without issuing oversized single-page reads.internal/agent/chat/chat.go (1)
65-71: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove unused
ErrNotConfiguredandconfigError.
GetDefaultInvokerreturnsnilwhen no invoker is installed, and no caller checkschat.ErrNotConfigured. Delete the dead exported sentinel and the unusedconfigErrortype to avoid stale documentation about a nonexistent return 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/agent/chat/chat.go` around lines 65 - 71, Remove the unused exported ErrNotConfigured sentinel and the configError type, including its Error method, from the chat package. Leave GetDefaultInvoker’s existing nil behavior unchanged and remove the stale documentation associated with the deleted error.Source: Coding guidelines
internal/ingestion/component/knowledge_compiler/component_test.go (1)
296-306: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a case that exercises the embedding branch.
The root product carries
Vector: []float32{0.1, 0.2}, soupsertTreeNavtakes the pre-computed-vector path and never callsdeps.Embed. ThemockEmbedder{dim: 8}indepsis unused. Lines 232-247 ofcomponent.go— the nil-embedder guard, theEncodeerror path, and the empty-result guard — stay uncovered.Add a sub-case with a root product that has no
Vector, and assert thatUpsertDocreceives an 8-dimension vector.🤖 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/component_test.go` around lines 296 - 306, Extend the test around upsertTreeNav with a sub-case whose root product omits Vector, forcing the deps.Embed path and exercising the nil/error/empty-result guards as applicable. Configure the mockEmbedder to produce an 8-dimensional embedding and assert that the UpsertDoc request receives a vector of dimension 8.internal/ingestion/component/knowledge_compiler/component.go (1)
313-335: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winCap the generated summary length.
pageIndexSummaryconcatenates every entity description in the graph. A document with a large entity graph produces a summary of unbounded size. That string is sent to the embedding model and stored incontent_with_weighton the nav row. Embedding providers reject or truncate over-long inputs, and the nav payload grows without limit.Add a character or entity cap.
♻️ Proposed change
+// navSummaryMaxChars bounds the generated nav summary so the embedding call +// stays inside provider input limits. +const navSummaryMaxChars = 4000 + func pageIndexSummary(graphJSON string) string { var graph struct { Entities []struct { Name string `json:"name"` Description string `json:"description"` } `json:"entities"` } if err := json.Unmarshal([]byte(graphJSON), &graph); err != nil { return "" } var b strings.Builder for _, e := range graph.Entities { desc := strings.Join(strings.Fields(e.Description), " ") if desc == "" { continue } + if b.Len() >= navSummaryMaxChars { + break + } if e.Name != "" { b.WriteString(e.Name + ": ") } b.WriteString(desc + "\n") } return b.String() }🤖 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/component.go` around lines 313 - 335, Cap the output produced by pageIndexSummary to a fixed maximum size, limiting either the number of processed entities or accumulated summary characters before appending more descriptions. Preserve the existing whitespace normalization, name formatting, and empty-description handling, and ensure the returned summary never exceeds the chosen cap.internal/service/nlp/datasetnav_integration_test.go (1)
49-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the shared nav search constants and index-name helper.
findNavRowshould reuseNavService’snavIndexName(tenantID)and avoid hard-coding"dataset_nav"so this integration assert stays aligned with production naming.🤖 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_integration_test.go` around lines 49 - 55, Update findNavRow to construct the index through NavService’s navIndexName(tenantID) helper and use the shared navigation search constant instead of hard-coding "dataset_nav" in the Filter. Keep the existing request fields and assertion behavior unchanged.internal/agent/harness/sufficiency.go (2)
201-212: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value
buildFeedbackcan return a dangling prefix.A claim can appear in
missingbecauseHasEvidenceis false whileCrossCheckPassedis true (lines 180-184). In that casehintsstays empty and the function returns the string"missing: "with nothing after it. Include the claim ids frommissingwhen no hint was produced.♻️ Proposed fix
var hints []string for _, r := range results { if !r.CrossCheckPassed { hints = append(hints, fmt.Sprintf("claim %s: %d mismatch(es)", r.ClaimID, len(r.Mismatches))) + } else if !r.HasEvidence { + hints = append(hints, fmt.Sprintf("claim %s: no resolvable evidence", r.ClaimID)) } } return "missing: " + strings.Join(hints, "; ")🤖 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/agent/harness/sufficiency.go` around lines 201 - 212, Update buildFeedback to ensure every missing claim is represented when cross-check results produce no hints. Use the claim IDs from missing as fallback entries when hints remains empty, while preserving the existing mismatch hints and “all claims verified” behavior.
156-177: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the ineffectual initial assignment.
Every arm of the switch assigns
status, includingdefault. golangci-lint reports the initializer at line 156 as ineffectual.♻️ Proposed fix
- status := "INSUFFICIENT" + var status string switch {Based on the golangci-lint
ineffassignhint at line 156.🤖 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/agent/harness/sufficiency.go` around lines 156 - 177, Remove the initial "INSUFFICIENT" assignment to status before the switch in the sufficiency evaluation flow; retain all existing assignments within the switch arms, including default.Source: Linters/SAST tools
internal/agent/harness/answer_test.go (1)
51-71: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a decomposition-mode test for
RunAgenticRAG.Both
RunAgenticRAGtests use "low", which takes theDirectSearchbranch. The "medium" branch is untested end to end. That branch contains the pre-search merge (lines 63-67 of agentic_rag.go) and the pointer aliasing intostate.Plan.Claims(lines 75-78), where claim mutation byDecomposeAndSearchmust be visible instate.Plan. A "medium" test with a stub search and a stub planner response would cover both.Based on the coding guideline "Preserve still-valid behavior with focused tests".
🤖 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/agent/harness/answer_test.go` around lines 51 - 71, Add a focused medium-mode end-to-end test for RunAgenticRAG using stub search and planner responses, verifying the pre-search merge and that claim mutations from DecomposeAndSearch are reflected in state.Plan.Claims. Keep the existing low-mode and empty-search tests unchanged.Source: Coding guidelines
internal/agent/harness/orchestrator.go (1)
182-192: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCollapse the
REPLANbranch or implement it.
REPLANandCONTINUEproduce identical behavior: the loop advances one cycle. The comment marks the branch as "simplified", which records a deferred migration step rather than the current behavior. Either implement the replan (for example, clearIsVerifiedandAgentResulton failing claims so they are retried) or remove the branch and let the default path handle it.Based on the coding guideline "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 `@internal/agent/harness/orchestrator.go` around lines 182 - 192, Update the action switch in the orchestrator loop to remove the redundant REPLAN case and its stale “simplified” comment, allowing REPLAN to follow the same default cycle-advance behavior as CONTINUE.Source: Coding guidelines
internal/agent/harness/orchestrator_test.go (1)
83-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a multi-claim case and assert the verdict status.
The test uses one claim, so it cannot detect the
EvidenceIDsindex mismatch flagged in orchestrator.go lines 152-178. That defect only appears from the second claim onward. The test also asserts only thatres.Verdictis non-nil, so a wrong status passes.Add a two-claim case where each claim's search returns a distinct chunk, then assert that both claims verify and that the verdict status is
SUFFICIENT.🤖 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/agent/harness/orchestrator_test.go` around lines 83 - 97, The TestDecomposeAndSearch_Verifies test only covers one claim and does not validate the verdict status. Extend it to use two claims whose search callback returns distinct evidence chunks for each claim, then assert both claims are verified and res.Verdict.Status equals SUFFICIENT.internal/agent/harness/types.go (1)
111-151: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the exported surface of the mode table.
THINKING_MODESis an exported, mutable package-level map. Any package can add or replace entries and change routing behavior globally.GetModealready provides the read path. Make the map private and keepGetModeas the only accessor. The Go name would also becomethinkingModes, which matches Go naming conventions.Note that
THINKING_MODESis referenced directly inside the package (for exampleTHINKING_MODES["medium"]in route.go, planner.go, sufficiency.go, orchestrator.go) and in tests, so the rename is mechanical.Based on the coding guideline "Reduce public surface area when a helper can be made private or internal".
🤖 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/agent/harness/types.go` around lines 111 - 151, Rename the package-level mode table THINKING_MODES to private thinkingModes, preserving all entries and behavior. Update every direct reference within the package, including route.go, planner.go, sufficiency.go, orchestrator.go, and tests, while keeping GetMode as the sole accessor for external callers.Source: Coding guidelines
internal/agent/harness/agentic_rag.go (1)
49-67: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winGuard against a nil
searchcallback.
RunAgenticRAGnever returns an error and falls back at every other stage:RouteNodefalls back on an LLM failure,PlannerNodefalls back to a direct plan, andFormalizeAnswerreturns a fixed message. A nilsearchbreaks that contract with a panic at line 64 or lines 79-81.🛡️ Proposed fix
if state.Question == "" { return AnswerResult{FinalAnswer: emptyResultMessage, Empty: true} } + if search == nil { + log.Printf("agentic_rag: no search function provided; returning empty result") + return AnswerResult{FinalAnswer: emptyResultMessage, Empty: true} + }🤖 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/agent/harness/agentic_rag.go` around lines 49 - 67, Update RunAgenticRAG to handle a nil search callback without invoking it, preserving the function’s non-panicking fallback behavior. Guard both the decomposition pre_search call and the later search usage around the existing search references, leaving state initialization and downstream fallback processing intact.internal/agent/harness/answer.go (1)
90-103: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winLog the invoker failure.
Line 100 discards
errand returns a generic message. Every other node in this package logs its failure before falling back: route.go line 76, planner.go line 90, datasetnav.go line 163. Without a log entry, a failing final-answer call is indistinguishable from a model that produced that exact text.♻️ Proposed fix
if err != nil { + log.Printf("agentic_rag: formalize_answer failed (fallback): %v", err) return AnswerResult{FinalAnswer: "I'm sorry, I encountered an error while composing the answer."} }Add
"log"to the import block.🤖 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/agent/harness/answer.go` around lines 90 - 103, Update the error branch after chat.Invoker.Invoke in the answer flow to log the returned err with the standard log package before returning the existing generic FinalAnswer. Add the log import and follow the failure-logging pattern used by nearby package nodes such as route.go, planner.go, and datasetnav.go.internal/agent/harness/datasetnav.go (1)
148-149: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace the deprecated
strings.Title.
strings.Titleis deprecated and uses word-boundary capitalization rules. Sincenounis passed asclustersordocuments, capitalize the first byte directly instead.♻️ Proposed fix
system := strings.ReplaceAll(navSelectSystem, "{noun}", noun) - user := fmt.Sprintf("Question:\n%s\n\n%s (numbered):\n%s\n\nOutput JSON:", query, strings.Title(noun), b.String()) + label := noun + if label != "" { + label = strings.ToUpper(label[:1]) + label[1:] + } + user := fmt.Sprintf("Question:\n%s\n\n%s (numbered):\n%s\n\nOutput JSON:", query, label, b.String())🤖 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/agent/harness/datasetnav.go` around lines 148 - 149, Update the user prompt construction in the navigation flow to remove the deprecated strings.Title call. Capitalize the first byte of noun directly for the displayed heading, preserving the existing formatting and behavior for clusters and documents.internal/agent/tool/agentic_search.go (3)
312-319: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
md5Hexdoes not compute MD5.The function is named
md5Hexbut implements a custom 32-bit FNV-1a-style hash, not MD5. Rename it to reflect what it actually does (e.g.contentHash), or replace it withcrypto/md5if a real MD5 digest is intended.As per coding guidelines, prefer well-known library implementations for standard tasks such as hashing; if a real hash isn't required here, at minimum the name should not claim MD5.
🤖 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/agent/tool/agentic_search.go` around lines 312 - 319, Update the md5Hex function to use the standard crypto/md5 implementation if callers require an actual MD5 digest; otherwise rename it to contentHash or another accurate name and update every call site. Ensure the function name and returned format no longer falsely claim to be MD5.Source: Coding guidelines
289-296: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winManual insertion sort duplicates
sort.Slice.
highlightKeywordshand-rolls an insertion sort to ordertermsby descending length. Usesort.Sliceinstead for clarity and to avoid a hand-rolled O(n²) sort.As per coding guidelines, "Prefer well-known libraries/frameworks over 'rolling your own' for common tasks (cryptography, core data structures, standard algorithms)."♻️ Proposed fix using sort.Slice
+ "sort" ... - for i := 1; i < len(terms); i++ { - for j := i; j > 0 && len(terms[j]) > len(terms[j-1]); j-- { - terms[j], terms[j-1] = terms[j-1], terms[j] - } - } + sort.Slice(terms, func(i, j int) bool { return len(terms[i]) > len(terms[j]) })🤖 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/agent/tool/agentic_search.go` around lines 289 - 296, In highlightKeywords, replace the manual insertion-sort loop over terms with the standard library’s sort.Slice using a comparator that orders terms by descending length. Preserve the copied terms slice and its existing ordering behavior.Source: Coding guidelines
145-166: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winRegex recompiled on every chunk in
narrowByKeywords.
highlightKeywordsbuilds a newregexp.MustCompileon each call.narrowByKeywordscallsnarrowContent(which callshighlightKeywords) once per chunk in a loop, using the samekwdsfor every chunk. Compile the regex once pernarrowByKeywordscall and reuse it across chunks.⚡ Proposed fix to compile the highlight regex once per call
func narrowByKeywords(chunks []RetrievalChunk, keywords string) []RetrievalChunk { kwds := splitKeywords(keywords) if len(kwds) == 0 { return chunks } + re := buildHighlightRegex(kwds) seen := map[string]struct{}{} out := make([]RetrievalChunk, 0, len(chunks)) for _, c := range chunks { - nc, ok := narrowContent(c.Content, kwds) + nc, ok := narrowContent(c.Content, kwds, re) if !ok { continue }-func narrowContent(content string, kwds []string) (string, bool) { +func narrowContent(content string, kwds []string, re *regexp.Regexp) (string, bool) { ... - return "..." + highlightKeywords(b.String(), kwds) + "...", true + return "..." + re.ReplaceAllString(b.String(), "<em>${1}</em>") + "...", true } -func highlightKeywords(text string, kwds []string) string { +func buildHighlightRegex(kwds []string) *regexp.Regexp { if len(kwds) == 0 { - return text + return regexp.MustCompile(`$^`) // matches nothing } terms := make([]string, len(kwds)) copy(terms, kwds) - for i := 1; i < len(terms); i++ { - for j := i; j > 0 && len(terms[j]) > len(terms[j-1]); j-- { - terms[j], terms[j-1] = terms[j-1], terms[j] - } - } + sort.Slice(terms, func(i, j int) bool { return len(terms[i]) > len(terms[j]) }) pattern := "(" for i, t := range terms { if t == "" { continue } if i > 0 { pattern += "|" } pattern += regexp.QuoteMeta(t) } pattern += ")" - re := regexp.MustCompile(`(?i)` + pattern) - return re.ReplaceAllString(text, "<em>${1}</em>") + return regexp.MustCompile(`(?i)` + pattern) }Also applies to: 244-283, 285-310
🤖 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/agent/tool/agentic_search.go` around lines 145 - 166, Update narrowByKeywords to compile the keyword-highlight regex once after splitKeywords and reuse it for every chunk, instead of invoking narrowContent/highlightKeywords in a way that recompiles it per chunk. Adjust narrowContent or highlightKeywords to accept and use the precompiled regex while preserving the existing filtering, deduplication, and content-highlighting behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9f29342f-805e-4731-8588-7c8d98dbc1a2
📒 Files selected for processing (44)
.gitignorecmd/ragflow_server.gointernal/agent/chat/chat.gointernal/agent/component/llm.gointernal/agent/harness/agentic_rag.gointernal/agent/harness/answer.gointernal/agent/harness/answer_test.gointernal/agent/harness/datasetnav.gointernal/agent/harness/datasetnav_test.gointernal/agent/harness/navigation.gointernal/agent/harness/navigation_test.gointernal/agent/harness/orchestrator.gointernal/agent/harness/orchestrator_test.gointernal/agent/harness/planner.gointernal/agent/harness/production.gointernal/agent/harness/production_test.gointernal/agent/harness/route.gointernal/agent/harness/route_test.gointernal/agent/harness/sufficiency.gointernal/agent/harness/types.gointernal/agent/tool/agentic_search.gointernal/agent/tool/agentic_search_test.gointernal/agent/tool/canvas_ctx.gointernal/agent/tool/dataset_navigation.gointernal/agent/tool/dataset_navigation_test.gointernal/agent/tool/registry.gointernal/agent/tool/retrieval_nlp.gointernal/agent/tool/retrieval_service.gointernal/dao/compilation_template_seed.gointernal/dao/compilation_template_seed_test.gointernal/ingestion/component/knowledge_compiler/common/types.gointernal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/component_test.gointernal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.gointernal/ingestion/component/knowledge_compiler/datasetnav/datasetnav_test.gointernal/service/dataset_artifact_nav_test.gointernal/service/dataset_artifact_service.gointernal/service/nav/nav.gointernal/service/nav_embedder.gointernal/service/nlp/datasetnav.gointernal/service/nlp/datasetnav_integration_test.gointernal/service/nlp/datasetnav_test.gotasks/agentic_search_port_plan.mdtasks/agentic_search_self_review.md
💤 Files with no reviewable changes (3)
- internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go
- internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav_test.go
- internal/dao/compilation_template_seed.go
| func (s *NavService) appendDocToCluster(ctx context.Context, de engine.DocEngine, tenantID, kbID, clusterName, docID string) error { | ||
| chunks, _, err := s.navSearch(ctx, tenantID, kbID, | ||
| navFilter(map[string]interface{}{"type_kwd": []string{"nav_cluster"}, "title_kwd": []string{clusterName}}), | ||
| []string{"doc_ids_kwd", "doc_count_int"}, 0, 1, nil) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if len(chunks) == 0 { | ||
| return nil | ||
| } | ||
| ids := []string{} | ||
| if raw, ok := chunks[0]["doc_ids_kwd"].([]interface{}); ok { | ||
| for _, d := range raw { | ||
| if dd, ok := d.(string); ok { | ||
| ids = append(ids, dd) | ||
| } | ||
| } | ||
| } | ||
| found := false | ||
| for _, id := range ids { | ||
| if id == docID { | ||
| found = true | ||
| break | ||
| } | ||
| } | ||
| if !found { | ||
| ids = append(ids, docID) | ||
| } | ||
| count := intValue(chunks[0]["doc_count_int"]) | ||
| if !found { | ||
| count++ | ||
| } | ||
| return de.UpdateChunks(ctx, | ||
| map[string]interface{}{"title_kwd": []string{clusterName}, "kb_id": kbID}, | ||
| map[string]interface{}{"doc_ids_kwd": ids, "doc_count_int": count}, | ||
| s.navIndexName(tenantID), kbID) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Pin the update filter to nav rows, and guard the read-modify-write.
Two problems exist in appendDocToCluster.
First, the UpdateChunks condition at Lines 438-441 matches on title_kwd and kb_id only. It omits compile_kwd = dataset_nav and type_kwd = nav_cluster, unlike every read path, which uses navFilter. Any non-nav chunk in the same dataset whose title_kwd equals the cluster name receives doc_ids_kwd and doc_count_int. That corrupts regular chunk rows.
Second, the read at Line 407 and the write at Line 438 form a read-modify-write with no concurrency control. Two parallel UpsertDoc calls that merge into the same cluster both read the same doc_ids_kwd, and the second write drops the first document ID and undercounts doc_count_int. Serialize per cluster, or use an engine-side atomic append if one exists.
🐛 Proposed fix for the update filter
return de.UpdateChunks(ctx,
- map[string]interface{}{"title_kwd": []string{clusterName}, "kb_id": kbID},
+ navFilter(map[string]interface{}{
+ "type_kwd": []string{"nav_cluster"},
+ "title_kwd": []string{clusterName},
+ "kb_id": kbID,
+ }),
map[string]interface{}{"doc_ids_kwd": ids, "doc_count_int": count},
s.navIndexName(tenantID), kbID)🤖 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 406 - 442, Update
appendDocToCluster so the UpdateChunks filter includes the same nav-specific
constraints as navFilter, specifically compile_kwd=dataset_nav and
type_kwd=nav_cluster alongside the existing title and kb filters. Also protect
the read-modify-write sequence in appendDocToCluster with per-cluster
serialization, or replace it with an available engine-side atomic append, so
concurrent UpsertDoc calls preserve all document IDs and counts.
There was a problem hiding this comment.
Pull request overview
Ports the Python rag/advanced_rag agentic-search and dataset navigation capabilities into the Go stack, adding an ES-backed dataset-nav service plus an agentic-search harness and tools that can route retrieval through the nav tree.
Changes:
- Introduces a new ES-backed
NavService(dataset navigation) with unit + integration tests. - Adds agentic-search tools (
hybrid_search/vector_search/bm25_search) and a dataset-nav routing tool, including doc-scope plumbing into retrieval. - Ports core harness flow (route → planner → orchestrator → sufficiency → answer) and moves the chat-invoker seam into a leaf
internal/agent/chatpackage.
Reviewed changes
Copilot reviewed 43 out of 44 changed files in this pull request and generated 7 comments.
Show a summary per file
| File | Description |
|---|---|
| tasks/agentic_search_self_review.md | Self-review notes and fixes log |
| internal/service/nlp/datasetnav.go | ES-backed dataset-nav implementation |
| internal/service/nlp/datasetnav_test.go | In-memory engine unit tests |
| internal/service/nlp/datasetnav_integration_test.go | Integration test vs live engine |
| internal/service/nav/nav.go | NavService interface + singleton |
| internal/service/nav_embedder.go | Production embedder for nav |
| internal/service/dataset_artifact_service.go | Deprecated nav REST delegates |
| internal/service/dataset_artifact_nav_test.go | Tests for deprecated delete semantics |
| internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav_test.go | Removed old datasetnav compiler tests |
| internal/ingestion/component/knowledge_compiler/component.go | Writes nav by-product post compile |
| internal/ingestion/component/knowledge_compiler/component_test.go | Tests for by-product + variant removal |
| internal/ingestion/component/knowledge_compiler/common/types.go | Removes datasetnav as a variant |
| internal/dao/compilation_template_seed.go | Removes datasetnav seeded template |
| internal/dao/compilation_template_seed_test.go | Locks out datasetnav seed kind |
| internal/agent/tool/retrieval_service.go | Adds DocScope to retrieval request |
| internal/agent/tool/retrieval_nlp.go | Plumbs DocIDs into NLP retrieval |
| internal/agent/tool/registry.go | Registers agentic-search + nav tool |
| internal/agent/tool/dataset_navigation.go | Tool: dataset_navigation_by_tree |
| internal/agent/tool/dataset_navigation_test.go | Tool routing behavior tests |
| internal/agent/tool/canvas_ctx.go | Shared tenant/dataset context helpers |
| internal/agent/tool/agentic_search.go | Tools: hybrid/vector/bm25 search |
| internal/agent/tool/agentic_search_test.go | Keyword narrowing + splitting tests |
| internal/agent/harness/types.go | Harness types + mode strategies |
| internal/agent/harness/sufficiency.go | Cross-check + fusion scoring |
| internal/agent/harness/route.go | LLM routing node |
| internal/agent/harness/route_test.go | Route + planner tests |
| internal/agent/harness/production.go | Production runner wiring tools |
| internal/agent/harness/production_test.go | E2E wiring tests (fake tools) |
| internal/agent/harness/planner.go | LLM planner (claim decomposition) |
| internal/agent/harness/orchestrator.go | Direct + decompose orchestrators |
| internal/agent/harness/orchestrator_test.go | Orchestrator + sufficiency tests |
| internal/agent/harness/navigation.go | Ontology/mindmap navigation routing |
| internal/agent/harness/navigation_test.go | Structure navigation tests |
| internal/agent/harness/datasetnav.go | LLM two-pass nav selection + BFS |
| internal/agent/harness/datasetnav_test.go | Nav selection + BFS tests |
| internal/agent/harness/answer.go | Final answer composition from evidence |
| internal/agent/harness/answer_test.go | Answer node tests |
| internal/agent/harness/agentic_rag.go | End-to-end harness driver |
| internal/agent/component/llm.go | Moves chat seam to leaf package |
| internal/agent/chat/chat.go | New leaf chat invoker singleton |
| cmd/ragflow_server.go | Wires NavService at server start |
| .gitignore | Ignores ragflow_server binary |
| if bestName != "" && sim >= navMergeThreshold { | ||
| parent := bestName | ||
| if err := s.appendDocToCluster(ctx, de, in.TenantID, in.KbID, bestName, in.DocID); err != nil { | ||
| return err | ||
| } | ||
| _, err = de.InsertChunks(ctx, []map[string]interface{}{{ | ||
| "compile_kwd": navCompileKwd, | ||
| "available_int": 0, | ||
| "type_kwd": "nav_doc", | ||
| "title_kwd": in.DocID, | ||
| "parent_kwd": parent, | ||
| "depth_int": 1, | ||
| "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), | ||
| }}, idx, in.KbID) | ||
| return err | ||
| } |
| if ck, _ := row["compile_kwd"].(string); !strings.Contains(ck, "dataset_nav") { | ||
| t.Errorf("nav row compile_kwd = %q, want dataset_nav", ck) | ||
| } |
| // UpsertDoc places one document summary into the nav tree (incremental, | ||
| // ES-backed read-modify-write; deterministic placement in the minimal loop). | ||
| UpsertDoc(ctx context.Context, in UpsertDocInput) error | ||
| // RemoveDoc removes a document and cascades empty-cluster cleanup. | ||
| RemoveDoc(ctx context.Context, tenantID, kbID, docID string) error | ||
|
|
| parent := navRootParent | ||
| depth := 0 | ||
| if bestName != "" && sim >= navMinSim { | ||
| parent = bestName | ||
| depth = 1 | ||
| } |
Correctness fixes across harness/tool/nav/component: - orchestrator: EvidenceIDs now reference GLOBAL kbinfos indices (Kbinfos.Merge returns them) so later claims' cross-checks resolve against accumulated chunks, not per-search positions. - planner: unknown (non-empty) mode label falls back to medium instead of a zero-valued mode. - production: routeDocs combines topic+keywords into the nav routing query. - sufficiency: entity presence now records as a match (not only mismatch) and crossPassed uses float comparison to avoid integer-division bias. - tool dataset_navigation: per-request max_docs now takes effect (was ignored). - component: dataset-nav by-products accumulate ALL tree/structure specs (not just the last); structure by-product embeds the SUMMARY text, not graph JSON. - nlp datasetnav: findBestCluster keeps the STRONGEST match across descent levels (a strong ancestor is no longer displaced by a weaker child); appendDocToCluster pins its update filter to the nav_cluster row. - agentic_rag: log question length, not content (privacy). Tests: global-index merge, unknown-mode planner fallback.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/ingestion/component/knowledge_compiler/component.go (1)
184-186: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove migration-history references from the comment.
Describe the current Go behavior. Remove the Python file references.
As per coding guidelines, remove stale documentation and keep comments aligned with the current runtime 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/ingestion/component/knowledge_compiler/component.go` around lines 184 - 186, Update the comment above the dataset-nav by-product writes to describe only the current Go behavior: writing each by-product after all specs run and logging failures without aborting the pipeline. Remove the Python compiler.py and runner.py migration-history references.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 `@internal/ingestion/component/knowledge_compiler/component.go`:
- Around line 298-303: Update the embedding validation in the knowledge compiler
flow after deps.Embed.Encode to also reject an empty first embedding by checking
len(embeddings[0]) before assigning or storing vec. Preserve the existing error
and empty-list handling, and skip UpsertDoc whenever the first vector has no
values.
---
Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/component.go`:
- Around line 184-186: Update the comment above the dataset-nav by-product
writes to describe only the current Go behavior: writing each by-product after
all specs run and logging failures without aborting the pipeline. Remove the
Python compiler.py and runner.py migration-history references.
🪄 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: 2a16d0a8-c54d-4b51-9f6d-5f68ecdf3395
📒 Files selected for processing (11)
internal/agent/harness/agentic_rag.gointernal/agent/harness/orchestrator.gointernal/agent/harness/orchestrator_test.gointernal/agent/harness/planner.gointernal/agent/harness/production.gointernal/agent/harness/route_test.gointernal/agent/harness/sufficiency.gointernal/agent/tool/dataset_navigation.gointernal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/component_test.gointernal/service/nlp/datasetnav.go
🚧 Files skipped from review as they are similar to previous changes (8)
- internal/agent/harness/production.go
- internal/agent/harness/sufficiency.go
- internal/agent/harness/planner.go
- internal/agent/harness/route_test.go
- internal/agent/harness/orchestrator.go
- internal/agent/tool/dataset_navigation.go
- internal/ingestion/component/knowledge_compiler/component_test.go
- internal/service/nlp/datasetnav.go
| embeddings, err := deps.Embed.Encode(ctx, []string{summary}) | ||
| if err != nil || len(embeddings) == 0 { | ||
| log.Printf("knowledge_compiler: datasetnav by-product skipped (structure embedding failed): %v", err) | ||
| return | ||
| } | ||
| vec := embeddings[0] |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Reject an empty first embedding.
The check rejects an empty embedding list but accepts [][]float32{{}}. That value is stored as a navigation vector and cannot represent the summary. Check len(embeddings[0]) before UpsertDoc.
Proposed fix
- if err != nil || len(embeddings) == 0 {
+ if err != nil || len(embeddings) == 0 || len(embeddings[0]) == 0 {
log.Printf("knowledge_compiler: datasetnav by-product skipped (structure embedding failed): %v", err)
return
}📝 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.
| embeddings, err := deps.Embed.Encode(ctx, []string{summary}) | |
| if err != nil || len(embeddings) == 0 { | |
| log.Printf("knowledge_compiler: datasetnav by-product skipped (structure embedding failed): %v", err) | |
| return | |
| } | |
| vec := embeddings[0] | |
| embeddings, err := deps.Embed.Encode(ctx, []string{summary}) | |
| if err != nil || len(embeddings) == 0 || len(embeddings[0]) == 0 { | |
| log.Printf("knowledge_compiler: datasetnav by-product skipped (structure embedding failed): %v", err) | |
| return | |
| } | |
| vec := embeddings[0] |
🤖 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/component.go` around lines
298 - 303, Update the embedding validation in the knowledge compiler flow after
deps.Embed.Encode to also reject an empty first embedding by checking
len(embeddings[0]) before assigning or storing vec. Preserve the existing error
and empty-list handling, and skip UpsertDoc whenever the first vector has no
values.
- chat: add Set/GetDefaultModelName; einoChatInvoker falls back to it when a Request omits ModelName, so harness/agentic-search LLM calls no longer hard-fail with "model_id required". - llm.go: remove unconditional init() default-install so chat.GetDefaultInvoker() stays nil until bootstrap; register the production invoker in cmd instead. - nlp datasetnav: findBestCluster now also returns the best cluster's depth; nav_doc and sibling sub-cluster rows use depth = parentDepth+1 (was hard-coded 1), keeping the stored tree depth consistent under nested clusters. - nav: RemoveDoc doc comment no longer over-promises empty-cluster cascade. - integration test: read compile_kwd with a list-wrapped-safe helper. - cmd: install the production chat invoker at bootstrap. Tests: nav_doc depth under root cluster; default-model fallback path.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 `@cmd/ragflow_server.go`:
- Around line 839-843: Update the bootstrap code around
component.InstallDefaultChatInvoker() to also register the default chat model
using globalConfig.GetDefaultChatModel().Name via chat.SetDefaultModelName(...),
ensuring einoChatInvoker.Invoke has a model when Request.ModelName is absent.
In `@internal/agent/chat/chat.go`:
- Around line 74-76: Update einoChatInvoker.Invoke to resolve an empty ModelName
through the request tenant using GetDefaultModelName(ctx, tenantID,
ModelTypeChat), instead of relying on the process-wide defaultModel field.
Preserve explicitly provided model names, and ensure the tenant context and
identifier are obtained from the request before invoking the chat model.
In `@internal/service/nlp/datasetnav_test.go`:
- Around line 367-386: Update TestNavService_NavDocDepth to track whether a row
with doc_id "d2" is encountered, while preserving the existing depth_int
assertion; after iterating over eng.rows, fail the test if no matching row was
found.
🪄 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: 1f98339a-9bdf-4e8b-beb0-2a5c9f00527a
📒 Files selected for processing (7)
cmd/ragflow_server.gointernal/agent/chat/chat.gointernal/agent/component/llm.gointernal/service/nav/nav.gointernal/service/nlp/datasetnav.gointernal/service/nlp/datasetnav_integration_test.gointernal/service/nlp/datasetnav_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
- internal/service/nav/nav.go
- internal/service/nlp/datasetnav_integration_test.go
- internal/agent/component/llm.go
- internal/service/nlp/datasetnav.go
| // Install the production eino-based chat invoker as the shared chat default, | ||
| // so agentic-search harness LLM calls work in production. Without this, | ||
| // chat.GetDefaultInvoker() stays nil and the harness falls back gracefully. | ||
| component.InstallDefaultChatInvoker() | ||
|
|
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 8 \
'func InstallDefaultChatInvoker|SetDefaultModelName|GetDefaultModelName' \
internal/agent cmdRepository: infiniflow/ragflow
Length of output: 4355
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '--- cmd/ragflow_server.go nearby bootstrap ---\n'
sed -n '760,870p' cmd/ragflow_server.go
printf '\n--- SetDefaultModelName usages ---\n'
rg -n -C 3 'SetDefaultModelName\(.*\)|DefaultChatModel|ChatModel|Model.*Config|model_id' cmd internal app .github --glob '*.go' --glob '*.yaml' --glob '*.yml' --glob '*.md' --glob 'README*' | sed -n '1,220p'Repository: infiniflow/ragflow
Length of output: 247
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- cmd/ragflow_server.go nearby bootstrap ---'
sed -n '760,870p' cmd/ragflow_server.go
echo
echo '--- SetDefaultModelName usages ---'
rg -n -C 3 'SetDefaultModelName\(|DefaultChatModel|ChatModel|Model.*Config|model_id' cmd internal app .github --glob '*.go' --glob '*.yaml' --glob '*.yml' --glob '*.md' --glob 'README*' | sed -n '1,260p'Repository: infiniflow/ragflow
Length of output: 19244
Register the default chat model when installing the invoker.
component.InstallDefaultChatInvoker() only calls chat.SetDefaultInvoker(...), while einoChatInvoker.Invoke requires either Request.ModelName or chat.GetDefaultModelName(). Add chat.SetDefaultModelName(...) at this bootstrap point from globalConfig.GetDefaultChatModel().Name, or pass the intended model explicitly to the invoker.
🤖 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 `@cmd/ragflow_server.go` around lines 839 - 843, Update the bootstrap code
around component.InstallDefaultChatInvoker() to also register the default chat
model using globalConfig.GetDefaultChatModel().Name via
chat.SetDefaultModelName(...), ensuring einoChatInvoker.Invoke has a model when
Request.ModelName is absent.
| mu sync.RWMutex | ||
| inst Invoker | ||
| defaultModel string |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 6 \
'SetDefaultModelName|GetDefaultModelName|InstallDefaultChatInvoker|ModelName|TenantID|tenant_id' \
internal/agent internal/service cmdRepository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== internal/agent/chat/chat.go outline =="
ast-grep outline internal/agent/chat/chat.go || true
echo "== internal/agent/chat/chat.go relevant sections =="
sed -n '1,140p' internal/agent/chat/chat.go
echo "== internal/agent/component/llm.go relevant sections around fallback =="
sed -n '150,260p' internal/agent/component/llm.go
echo "== call sites for chat invoker setup and default model setters =="
rg -n -C 4 'InstallDefaultChatInvoker|InstallChatInvoker|GetDefaultModelName|SetDefaultModelName|NewChatInvoker|DefaultModel|defaultModel' .Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== exact SetDefaultModelName occurrences =="
rg -n -C 4 'SetDefaultModelName\(' .
echo "== tenant model service methods around default model =="
rg -n -C 6 'func .*DefaultModel|GetDefaultModelName|SetDefaultModel' internal/service internal/router internal/dao internal/tenant internal/llm cmd internal | head -n 300
echo "== ChatInvokeRequest construction sites =="
rg -n -C 5 'ChatInvokeRequest\{|ModelName\?:|ModelName:' . | head -n 300Repository: infiniflow/ragflow
Length of output: 20539
Resolve chat model defaults from tenant context.
SetDefaultModelName only has one process-wide string, and the server never calls it during bootstrap. einoChatInvoker.Invoke depends on this value when ModelName is empty, so requests that omit a model fail instead of using the tenant LLM default that the rest of the service resolves with GetDefaultModelName(ctx, tenantID, ModelTypeChat). Resolve the default inside the invoker from the tenant used by the request, or change the fallback contract.
🤖 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/agent/chat/chat.go` around lines 74 - 76, Update
einoChatInvoker.Invoke to resolve an empty ModelName through the request tenant
using GetDefaultModelName(ctx, tenantID, ModelTypeChat), instead of relying on
the process-wide defaultModel field. Preserve explicitly provided model names,
and ensure the tenant context and identifier are obtained from the request
before invoking the chat model.
| // TestNavService_NavDocDepth asserts a nav_doc merged under a root cluster | ||
| // (depth 0) gets depth_int = parentDepth+1 = 1, not a hard-coded value. | ||
| func TestNavService_NavDocDepth(t *testing.T) { | ||
| eng := newMemNavEngine() | ||
| ns := newTestNav(eng) | ||
| if err := ns.UpsertDoc(context.Background(), navUpsertInput("t1", "kb1", "d1", "aaa one")); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if err := ns.UpsertDoc(context.Background(), navUpsertInput("t1", "kb1", "d2", "aaa two")); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| // The nav_doc for d2 sits under the root cluster; its depth_int must be 1. | ||
| for _, row := range eng.rows { | ||
| if row["doc_id"] == "d2" { | ||
| if d, ok := row["depth_int"].(int); !ok || d != 1 { | ||
| t.Errorf("nav_doc d2 depth_int = %v, want 1 (parentDepth 0 + 1)", row["depth_int"]) | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Fail when the d2 navigation row is absent.
The loop only validates rows with doc_id == "d2". If the second UpsertDoc creates no row, the loop performs zero checks and the test passes. Track a found flag and fail after the loop when no d2 row exists.
Proposed test fix
+ found := false
for _, row := range eng.rows {
if row["doc_id"] == "d2" {
+ found = true
if d, ok := row["depth_int"].(int); !ok || d != 1 {
t.Errorf("nav_doc d2 depth_int = %v, want 1 (parentDepth 0 + 1)", row["depth_int"])
}
}
}
+ if !found {
+ t.Fatal("nav_doc d2 was not created")
+ }📝 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.
| // TestNavService_NavDocDepth asserts a nav_doc merged under a root cluster | |
| // (depth 0) gets depth_int = parentDepth+1 = 1, not a hard-coded value. | |
| func TestNavService_NavDocDepth(t *testing.T) { | |
| eng := newMemNavEngine() | |
| ns := newTestNav(eng) | |
| if err := ns.UpsertDoc(context.Background(), navUpsertInput("t1", "kb1", "d1", "aaa one")); err != nil { | |
| t.Fatal(err) | |
| } | |
| if err := ns.UpsertDoc(context.Background(), navUpsertInput("t1", "kb1", "d2", "aaa two")); err != nil { | |
| t.Fatal(err) | |
| } | |
| // The nav_doc for d2 sits under the root cluster; its depth_int must be 1. | |
| for _, row := range eng.rows { | |
| if row["doc_id"] == "d2" { | |
| if d, ok := row["depth_int"].(int); !ok || d != 1 { | |
| t.Errorf("nav_doc d2 depth_int = %v, want 1 (parentDepth 0 + 1)", row["depth_int"]) | |
| } | |
| } | |
| } | |
| } | |
| // TestNavService_NavDocDepth asserts a nav_doc merged under a root cluster | |
| // (depth 0) gets depth_int = parentDepth+1 = 1, not a hard-coded value. | |
| func TestNavService_NavDocDepth(t *testing.T) { | |
| eng := newMemNavEngine() | |
| ns := newTestNav(eng) | |
| if err := ns.UpsertDoc(context.Background(), navUpsertInput("t1", "kb1", "d1", "aaa one")); err != nil { | |
| t.Fatal(err) | |
| } | |
| if err := ns.UpsertDoc(context.Background(), navUpsertInput("t1", "kb1", "d2", "aaa two")); err != nil { | |
| t.Fatal(err) | |
| } | |
| // The nav_doc for d2 sits under the root cluster; its depth_int must be 1. | |
| found := false | |
| for _, row := range eng.rows { | |
| if row["doc_id"] == "d2" { | |
| found = true | |
| if d, ok := row["depth_int"].(int); !ok || d != 1 { | |
| t.Errorf("nav_doc d2 depth_int = %v, want 1 (parentDepth 0 + 1)", row["depth_int"]) | |
| } | |
| } | |
| } | |
| if !found { | |
| t.Fatal("nav_doc d2 was not created") | |
| } | |
| } |
🤖 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_test.go` around lines 367 - 386, Update
TestNavService_NavDocDepth to track whether a row with doc_id "d2" is
encountered, while preserving the existing depth_int assertion; after iterating
over eng.rows, fail the test if no matching row was found.
Port Python rag/advanced_rag agentic search to Go: ES-backed dataset-nav service, agentic-search harness, and agent tools.
Includes agentic-search port plan and self-review docs.