Repository navigation
Feat: compilation result navigation in agentic search - #17002
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe PR adds compiled catalog and knowledge-graph navigation, replaces legacy navigation tools, introduces per-turn hybrid-search caching, expands keyword-aware search interfaces, and standardizes streamed progress and orchestration messages. ChangesAgentic RAG navigation
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Agent
participant ToolRegistry
participant catalog_navigate
participant graph_explore
participant hybrid_search
participant SourceChunks
Agent->>ToolRegistry: select navigation tool
ToolRegistry->>catalog_navigate: topic, keywords, doc_scope
catalog_navigate->>SourceChunks: load compiled evidence
catalog_navigate-->>Agent: answer and passages
Agent->>graph_explore: query, keywords, doc_scope
graph_explore->>hybrid_search: fallback retrieval when KG evidence is unavailable
hybrid_search-->>Agent: cached or retrieved passages
Possibly related PRs
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: 9
🧹 Nitpick comments (1)
rag/advanced_rag/harness/tools/search.py (1)
195-200: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winReturn a copy of the cached result to prevent shared mutation.
Callers like
graph_explore(innavigation.py) intentionally mutate the dictionary returned byhybrid_searchby adding a fallback"answer"key. Since the cache stores and returns the exact same dictionary reference, this mutation modifies the shared cache state, potentially leaking into subsequent retrieval calls within the same turn.Consider returning a shallow copy to protect the cache integrity.
♻️ Proposed refactor
if cache is not None and cache_key in cache: cached = cache[cache_key] _LOG.info(f"[Hybrid search] Already searched this — reusing the {len(cached.get('chunks', []))} passage(s) found earlier.") - return cached + return dict(cached)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/advanced_rag/harness/tools/search.py` around lines 195 - 200, Update the cache-hit branch in hybrid_search to return a shallow copy of the cached result rather than the cached dictionary itself. Preserve the existing cache lookup and logging behavior while ensuring caller mutations, such as graph_explore adding an "answer" key, cannot modify the shared cache entry.
🤖 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 `@api/utils/validation_utils.py`:
- Line 424: Keep the task_page_size lower bound at 1 in its Annotated Field
definition unless zero-page semantics are intentionally supported. If supporting
zero, update the task service consumer to distinguish None from 0 instead of
using a truthiness-based or fallback expression, and add coverage confirming
zero is honored.
In `@rag/advanced_rag/agentic_rag_graph.py`:
- Line 341: Guard the “Research complete” log in _drive() with not
holder.get("error") so it is emitted only after successful graph execution; when
holder["error"] is set, rely on the existing fallback error message instead.
In `@rag/advanced_rag/harness/tools/__init__.py`:
- Around line 21-27: Update the compilation gate in the gating logic used by
register_tool to support tuple requirements such as catalog_navigate’s ("toc",
"page_index"). Replace the single-membership check in tools/gating.py with the
same set-intersection behavior used by pipeline.filter_available_tools, while
preserving existing behavior for scalar compilation types.
In `@rag/advanced_rag/harness/tools/navigation.py`:
- Around line 365-370: Remove the duplicate graph_explore implementation in
navigation.py, including its associated helper code in the affected range, and
retain the registered implementation from tools/exploration.py as the single
source of truth. Ensure callers continue resolving graph_explore through the
existing tools/__init__.py registration without adding another export or
compatibility wrapper.
- Around line 378-390: Update the document-resolution path in _kg_scopes and its
graph_explore caller to execute each Peewee-backed tools._resolve_doc_tenant
call through the existing thread_pool_exec helper, following the pattern used by
_load_compiled_structure, while preserving the current grouping and
unresolved-document behavior.
- Line 32: Update the artifact-kind handling around _CATALOG_KINDS and the
related navigation logic to keep knowledge_graph artifacts distinct from catalog
timeline artifacts. Preserve the original kind, or use template metadata to
distinguish it before catalog navigation classifies or merges the artifact,
ensuring KG entities are not treated as page-index/catalog data or queried from
the wrong compiled structure.
- Around line 522-540: Update the entity deduplication in the local
_add_entities flow so ent_names keys include the current KB/document scope
alongside the normalized entity name, rather than using only e["name"].lower().
Pass the relevant kb_id, tenant_id, and doc_ids context when adding seeds and
any subsequent entities, preserving deduplication within each scope while
allowing identical names from different scoped KBs or documents to be explored.
- Around line 325-335: Update the fallback and keyword-filtering flow around
hybrid_search, _narrow_by_keywords, and the returned answer/chunks mapping so an
outline-derived answer is never returned without its supporting evidence. When
no source chunks exist, clear the answer before returning fallback chunks; when
keyword filtering removes every chunk, restore the original unfiltered chunks
rather than returning an unsupported answer.
In `@rag/advanced_rag/harness/tools/search.py`:
- Around line 248-252: Normalize the retrieval response before keyword filtering
in both vector_search at rag/advanced_rag/harness/tools/search.py:248-252 and
bm25_search at rag/advanced_rag/harness/tools/search.py:271-275. Move each
_normalize call ahead of the if keywords block, then return the
already-normalized result so None or empty responses are handled safely before
accessing chunks.
---
Nitpick comments:
In `@rag/advanced_rag/harness/tools/search.py`:
- Around line 195-200: Update the cache-hit branch in hybrid_search to return a
shallow copy of the cached result rather than the cached dictionary itself.
Preserve the existing cache lookup and logging behavior while ensuring caller
mutations, such as graph_explore adding an "answer" key, cannot modify the
shared cache entry.
🪄 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
Run ID: b70dd588-8d3f-4c3b-ad79-d5b76d1cc6b0
📒 Files selected for processing (19)
api/utils/validation_utils.pyrag/advanced_rag/agentic_rag.pyrag/advanced_rag/agentic_rag_graph.pyrag/advanced_rag/harness/agent.pyrag/advanced_rag/harness/config.pyrag/advanced_rag/harness/orchestrator/__init__.pyrag/advanced_rag/harness/orchestrator/agentic.pyrag/advanced_rag/harness/orchestrator/direct.pyrag/advanced_rag/harness/pipeline.pyrag/advanced_rag/harness/planner.pyrag/advanced_rag/harness/tools/__init__.pyrag/advanced_rag/harness/tools/exploration.pyrag/advanced_rag/harness/tools/gating.pyrag/advanced_rag/harness/tools/navigation.pyrag/advanced_rag/harness/tools/registry.pyrag/advanced_rag/harness/tools/search.pyrag/advanced_rag/think_log.pyrag/llm/chat_model.pyrag/llm/tool_decorator.py
| tools.kbinfos = final_kb | ||
|
|
||
| _LOG.info("[agentic-rag] RUN END | streamed=%s, loops=%d, chunks=%d", produced, state.get("loop", 0), len((state.get("kbinfos") or {}).get("chunks", []))) | ||
| _LOG.info("[Agentic RAG] Research complete — %d passage(s) gathered after %d round(s).", len((state.get("kbinfos") or {}).get("chunks", [])), state.get("loop", 0)) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Do not report successful completion after graph failure.
_drive() sets holder["error"] when graph execution fails, but this line still emits “Research complete” before the fallback error message. Emit a failure-specific log or guard this message with not holder.get("error").
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/advanced_rag/agentic_rag_graph.py` at line 341, Guard the “Research
complete” log in _drive() with not holder.get("error") so it is emitted only
after successful graph execution; when holder["error"] is set, rely on the
existing fallback error message instead.
| register_tool( | ||
| "catalog_navigate", | ||
| _navigate_schema("catalog_navigate", "Answer from the document's compiled catalog (table of contents / page index)"), | ||
| catalog_navigate, | ||
| requires_compilation=True, | ||
| compilation_type=("toc", "page_index"), | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Update every compilation gate for tuple requirements.
This registration uses ("toc", "page_index"), but tools/gating.py Line 68 still evaluates comp_type in comps. A tuple cannot match the string artifact names, so catalog_navigate is always removed from orchestrator-gated tools even when compilation exists. Apply the same set-intersection logic used by pipeline.filter_available_tools.
Proposed gating fix
- return any(comp_type in comps for comps in compilation_map.values())
+ wanted = {comp_type} if isinstance(comp_type, str) else set(comp_type or ())
+ return bool(wanted) and any(wanted & comps for comps in compilation_map.values())🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/advanced_rag/harness/tools/__init__.py` around lines 21 - 27, Update the
compilation gate in the gating logic used by register_tool to support tuple
requirements such as catalog_navigate’s ("toc", "page_index"). Replace the
single-membership check in tools/gating.py with the same set-intersection
behavior used by pipeline.filter_available_tools, while preserving existing
behavior for scalar compilation types.
| # ── Knowledge-graph exploration ───────────────────────────────────────────── | ||
| # | ||
| # Unlike catalog/mindmap (which read the merged "graph" JSON of one doc), the KG | ||
| # store keeps one searchable row per entity/relation, so graph_explore *searches* | ||
| # its way to a small subgraph: seed entities by the question, hop out over | ||
| # relations to the 2nd-degree neighbours, then answer from that subgraph. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Converge the duplicate graph_explore implementations.
tools/__init__.py registers graph_explore from tools/exploration.py, leaving this new implementation unregistered and vulnerable to divergence. Keep one implementation in its owning module and delete the duplicate.
As per coding guidelines, “During review, remove deprecated, legacy, compatibility-only, duplicate, stale, or unnecessarily exported code when it is not required by the current implementation.”
Also applies to: 501-586
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/advanced_rag/harness/tools/navigation.py` around lines 365 - 370, Remove
the duplicate graph_explore implementation in navigation.py, including its
associated helper code in the affected range, and retain the registered
implementation from tools/exploration.py as the single source of truth. Ensure
callers continue resolving graph_explore through the existing tools/__init__.py
registration without adding another export or compatibility wrapper.
Source: Coding guidelines
| entities: list[dict] = [] | ||
| relations: list[dict] = [] | ||
| ent_names: set[str] = set() | ||
|
|
||
| def _add_entities(new: list[dict]) -> list[str]: | ||
| added = [] | ||
| for e in new: | ||
| key = e["name"].lower() | ||
| if key in ent_names: | ||
| continue | ||
| ent_names.add(key) | ||
| entities.append(e) | ||
| added.append(e["name"]) | ||
| return added | ||
|
|
||
| for kb_id, tenant_id, doc_ids in scopes: | ||
| seed_rows = await _kg_search(tools, kb_id, tenant_id, doc_ids, "entity", text=text, top_n=_KG_SEEDS) | ||
| seeds = [e for e in (_kg_parse_entity(r) for r in seed_rows.values()) if e] | ||
| frontier = _add_entities(seeds) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Scope entity deduplication by KB/document.
ent_names is global and keyed only by lowercase name. When two scoped KBs contain the same entity, the later seed is discarded, its frontier becomes empty, and that KB’s relations and evidence are never explored. Include the scope and document identity in the deduplication key.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/advanced_rag/harness/tools/navigation.py` around lines 522 - 540, Update
the entity deduplication in the local _add_entities flow so ent_names keys
include the current KB/document scope alongside the normalized entity name,
rather than using only e["name"].lower(). Pass the relevant kb_id, tenant_id,
and doc_ids context when adding seeds and any subsequent entities, preserving
deduplication within each scope while allowing identical names from different
scoped KBs or documents to be explored.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17002 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
Compilation result navigation in agentic search.