Skip to content

Feat: compilation result navigation in agentic search - #17002

Merged
yingfeng merged 3 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search2
Jul 16, 2026
Merged

yingfeng merged 3 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search2

Conversation

@KevinHuSh

Copy link
Copy Markdown
Contributor

Summary

Compilation result navigation in agentic search.

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 16, 2026
@KevinHuSh KevinHuSh added ci Continue Integration and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 16, 2026
@dosubot dosubot Bot added 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 16, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft July 16, 2026 09:52
@KevinHuSh
KevinHuSh marked this pull request as ready for review July 16, 2026 09:52
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 16, 2026
@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2ccc911b-1020-4224-b5f3-b579d2e06f02

📥 Commits

Reviewing files that changed from the base of the PR and between 3a97bb4 and f1d675d.

📒 Files selected for processing (2)
  • rag/advanced_rag/harness/tools/navigation.py
  • rag/advanced_rag/harness/tools/search.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • rag/advanced_rag/harness/tools/search.py
  • rag/advanced_rag/harness/tools/navigation.py

📝 Walkthrough

Walkthrough

The 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.

Changes

Agentic RAG navigation

Layer / File(s) Summary
Compiled-structure navigation
rag/advanced_rag/harness/tools/navigation.py
Adds compiled catalog, mindmap, and knowledge-graph navigation pipelines that obtain model-selected evidence and fall back to hybrid search.
Navigation tool contracts and wiring
rag/advanced_rag/harness/config.py, rag/advanced_rag/harness/pipeline.py, rag/advanced_rag/harness/tools/*
Replaces TOC/page-index tools with catalog_navigate, updates gating and compilation checks, and adds keyword-aware exploration and navigation schemas.
Retrieval caching and search interfaces
rag/advanced_rag/agentic_rag.py, rag/advanced_rag/harness/tools/search.py
Adds per-turn retrieval caching, deterministic cache keys, keyword-narrowing logs, and the structured_query query/keywords interface.
Agentic progress and result messaging
rag/advanced_rag/agentic_rag_graph.py, rag/advanced_rag/harness/{agent.py,planner.py,think_log.py}, rag/advanced_rag/harness/orchestrator/*, rag/llm/*
Standardizes progress labels and tool-loop messages while exposing direct answers, claim progress, evidence counts, and completion states.

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
Loading

Possibly related PRs

  • infiniflow/ragflow#16859: Introduces the RAGTools framework in the same file where this PR adds per-request retrieval caching.

Poem

I hop through catalogs, neat and bright,
Graph paths twinkle in the night.
Cached searches save each carrot crumb,
Clear tool thoughts say what’s to come.
“Run the tool!” my whiskers cheer—
Better RAG is burrowing here!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately reflects the main change: compilation result navigation in agentic search.
Description check ✅ Passed The description includes the required Summary section and states the PR's purpose, though it is brief.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (1)
rag/advanced_rag/harness/tools/search.py (1)

195-200: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Return a copy of the cached result to prevent shared mutation.

Callers like graph_explore (in navigation.py) intentionally mutate the dictionary returned by hybrid_search by 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

📥 Commits

Reviewing files that changed from the base of the PR and between feba9e1 and 3a97bb4.

📒 Files selected for processing (19)
  • api/utils/validation_utils.py
  • rag/advanced_rag/agentic_rag.py
  • rag/advanced_rag/agentic_rag_graph.py
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/config.py
  • rag/advanced_rag/harness/orchestrator/__init__.py
  • rag/advanced_rag/harness/orchestrator/agentic.py
  • rag/advanced_rag/harness/orchestrator/direct.py
  • rag/advanced_rag/harness/pipeline.py
  • rag/advanced_rag/harness/planner.py
  • rag/advanced_rag/harness/tools/__init__.py
  • rag/advanced_rag/harness/tools/exploration.py
  • rag/advanced_rag/harness/tools/gating.py
  • rag/advanced_rag/harness/tools/navigation.py
  • rag/advanced_rag/harness/tools/registry.py
  • rag/advanced_rag/harness/tools/search.py
  • rag/advanced_rag/think_log.py
  • rag/llm/chat_model.py
  • rag/llm/tool_decorator.py

Comment thread api/utils/validation_utils.py Resolved
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Comment on lines +21 to +27
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"),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +365 to +370
# ── 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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

Comment on lines +522 to +540
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

@yingfeng
yingfeng marked this pull request as draft July 16, 2026 10:03
@yingfeng
yingfeng marked this pull request as ready for review July 16, 2026 10:03
@codecov

codecov Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (2a6e210) to head (f1d675d).
⚠️ Report is 38 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yingfeng
yingfeng merged commit d5d04ad into infiniflow:main Jul 16, 2026
3 checks passed
@KevinHuSh
KevinHuSh deleted the feat/agentic_search2 branch July 20, 2026 10:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants