Skip to content

Refactor: the tool usage in agent search progress - #17490

Merged
yingfeng merged 3 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search6
Jul 29, 2026
Merged

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

Conversation

@KevinHuSh

Copy link
Copy Markdown
Contributor

Summary

Refactor: the tool usage in agent search progress

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Navigation tools were renamed and reworked to route through compiled document structures and dataset trees. The pipeline now carries routed document IDs into later tools through doc_scope, while agent prompts and sessions support navigation-first execution and early report generation.

Changes

Document Routing Navigation

Layer / File(s) Summary
Routing contracts and tool wiring
rag/advanced_rag/harness/types.py, rag/advanced_rag/harness/tools/registry.py, rag/advanced_rag/harness/tools/__init__.py, rag/advanced_rag/harness/tools/gating.py, rag/advanced_rag/harness/config.py
Tool results support routed document IDs; navigation schemas, registrations, compilation requirements, priorities, context checks, and configured tool names use the new routing tools.
Compiled-document navigation
rag/advanced_rag/harness/tools/navigation.py
ontology_navigate and mindmap_navigate select compiled entities within scoped documents and return associated evidence chunks without hybrid-search fallback.
Dataset tree routing
rag/advanced_rag/harness/tools/navigation.py
dataset_navigation_by_tree selects relevant navigation clusters and document leaves, returning capped document IDs without retrieval.
Pipeline scope propagation
rag/advanced_rag/harness/pipeline.py
The pipeline stores normalized routed document IDs and injects them as doc_scope for subsequent within-document tools.
Research-agent navigation flow
rag/advanced_rag/harness/agent.py, rag/advanced_rag/harness/prompts/research_agent_prompt.py
Research prompts prioritize coarse-to-fine navigation, while native sessions assess navigation passages against the current claim and can steer the agent to generate_report.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ResearchAgent
  participant Pipeline
  participant dataset_navigation_by_tree
  participant ontology_navigate
  participant CompiledDocumentStore
  ResearchAgent->>Pipeline: execute coarse navigation
  Pipeline->>dataset_navigation_by_tree: route topic through dataset tree
  dataset_navigation_by_tree-->>Pipeline: return document IDs
  Pipeline->>ontology_navigate: pass inherited doc_scope
  ontology_navigate->>CompiledDocumentStore: select entities and load evidence chunks
  CompiledDocumentStore-->>ontology_navigate: return scoped chunks
  ontology_navigate-->>Pipeline: return normalized tool result
  Pipeline-->>ResearchAgent: provide navigation evidence
Loading

Suggested labels: 💞 feature, 🌈 python

Poem

I’m a bunny routing through trees in the night,
Finding doc IDs by moonbeam light.
Scoped chunks hop into the pipeline’s way,
Then reports bloom when answers stay.
Thump, thump—new tools guide the flight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main change: refactoring tool usage in the agent search flow.
Description check ✅ Passed The description includes the required Summary section and is aligned with the PR intent, though it is brief.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
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.

@yingfeng yingfeng added the ci Continue Integration label Jul 28, 2026

@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 (4)
rag/advanced_rag/harness/tools/navigation.py (2)

317-322: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant doc_scope normalization.

Lines 317-318 coerce a falsy doc_scope to [], then Line 320 returns on that exact condition — the assignment can never be observed. Two log lines also fire for the same empty-scope case.

♻️ Proposed simplification
-    if not doc_scope:
-        doc_scope = []
-    _LOG.info(f'[Ontology navigation] Looking through the document catalog for "{topic}" (keywords: {keywords}) in doc: {len(doc_scope)}')
     if not doc_scope:
-        _LOG.info(f'[Ontology navigation] No doc scope provided: "{topic}" (keywords: {keywords})')
+        _LOG.info('[Ontology navigation] No doc scope provided for "%s" (keywords: %s)', topic, keywords)
         return {"answer": "", "chunks": [], "doc_aggs": []}
+    _LOG.info('[Ontology navigation] Looking through the catalog of %d doc(s) for "%s" (keywords: %s)', len(doc_scope), topic, keywords)
🤖 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 317 - 322, Remove
the redundant `doc_scope = []` normalization in the ontology navigation flow.
Update the empty-scope handling around the `[Ontology navigation]` logging and
return so it uses a single check and emits only one log message before returning
the existing empty response.

521-529: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Cap is applied after the log, so the reported count can exceed what is returned.

Line 528 logs len(routed) but Line 529 truncates to _NAV_MAX_DOCS. Truncate first so the log matches the contract.

♻️ Proposed fix
-    _LOG.info("[Dataset navigation] Routed to %d document(s).", len(routed))
-    return routed[:_NAV_MAX_DOCS]
+    routed = routed[:_NAV_MAX_DOCS]
+    _LOG.info("[Dataset navigation] Routed to %d document(s).", len(routed))
+    return routed
🤖 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 521 - 529, Update
the document routing flow in the visible deduplication block to apply
_NAV_MAX_DOCS before logging the count. Ensure _LOG.info reports the length of
the capped routed collection, and return that same capped collection without
changing deduplication behavior.
rag/advanced_rag/harness/agent.py (1)

342-343: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Comment is stale as written.

ontology_navigate now hardcodes "answer": "" (navigation.py Line 324), so it never answers directly. Only structured_query still does.

📝 Proposed wording
-    # Some tools (ontology_navigate, structured_query) answer directly rather than
+    # Some tools (structured_query) answer directly rather than
     # only returning passages — surface that, or the agent never sees 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 `@rag/advanced_rag/harness/agent.py` around lines 342 - 343, Update the comment
near the tool-answer handling in the agent harness to remove ontology_navigate
from the direct-answer claim, since navigation.py’s ontology_navigate now
returns an empty answer. Keep the guidance referring to structured_query, which
still provides direct answers.
rag/advanced_rag/harness/tools/registry.py (1)

64-66: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

doc_scope is advertised on a tool that ignores it.

_navigate_schema is shared by dataset_navigation_by_tree, whose implementation accepts doc_scope but never reads it (navigation.py Lines 457-529). The model can pass a scope and silently get unscoped routing. Consider a separate schema for the router, or honor doc_scope there as a pre-filter on routed doc IDs.

Also, topic and keywords now carry near-identical descriptions, which gives the model little signal on how to split them.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/registry.py` around lines 64 - 66, Update the
schema used by dataset_navigation_by_tree and _navigate_schema so doc_scope is
not advertised unless the router applies it; either introduce a router-specific
schema or enforce doc_scope as a pre-filter on routed document IDs. Also revise
the topic and keywords descriptions to clearly distinguish navigation intent
from search terms.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/advanced_rag/harness/pipeline.py`:
- Around line 12-15: The routed document-scope contract is incomplete. In
rag/advanced_rag/harness/pipeline.py lines 12-15, add mindmap_navigate to
_DOC_SCOPE_CONSUMERS so it inherits the router’s scope; in
rag/advanced_rag/harness/tools/gating.py lines 77-80, update the gating
predicate for ontology_navigate and mindmap_navigate to require an existing
routed scope rather than relying only on context.current_claim.
- Around line 44-48: The Pipeline routing state in the downstream scoping logic
must not leak between claims. Update the pipeline/orchestrator flow around
_routed_docs and dataset_navigation_by_tree so routing results are reset or
keyed per claim, and change the doc_scope check to distinguish an explicitly
supplied empty scope from an omitted scope; only inherit _routed_docs when
doc_scope was not provided.

In `@rag/advanced_rag/harness/tools/__init__.py`:
- Around line 20-26: Update the ontology_navigate registration’s
compilation_type to use the runtime-normalized catalog kinds accepted by
_load_compiled_structure, replacing the mismatched "toc" and "mindmap" values
with the appropriate tree/timeline vocabulary while retaining "page_index". Keep
mindmap_navigate responsible for mindmap-only catalogs.

In `@rag/advanced_rag/harness/tools/navigation.py`:
- Around line 511-519: Update the INFO logs in the dataset navigation flow
around selected_clusters to log only the cluster names, not the full cluster
dictionaries containing KB objects or tenant data. Use lazy %-style logging
consistent with the module, preserving the existing messages and return behavior
for empty leaves or selected_docs.
- Around line 279-291: Update the entity-selection flow around _ask_nav_select
so it uses an entity-specific prompt scoped to the current doc_id and query,
without dataset-navigation or dataset-leaf wording. Remove the unused Graph
exploration paths _NAV_SYSTEM, _render_structure, and _ask_structure rather than
retaining compatibility shims; preserve the existing selected-entity limits and
empty-result handling.
- Around line 342-349: The navigation selection flow must avoid post-indexing
truncation and remove the unused _NAV_MAX_HITS_PER_KB constant. Update the
list-rendering logic used by _ask_nav_select so the numbered cluster/leaf lists
are capped to fit the model’s token budget before indices are assigned, then
validate and resolve returned indices against exactly that rendered list; do not
apply message_fit_in after indexing.
- Around line 431-453: Update the navigation traversal around the frontier loop
to use collections.deque with popleft() instead of list.pop(0), and add a
bounded node-expansion budget independent of document leaves. Enforce the budget
before each list_nav_children call, incrementing it only for nodes actually
expanded, while preserving seen_nodes deduplication and existing depth/leaf
limits.
- Around line 280-307: Update the entity-loading and chunk-loading flows around
_load_compiled_structure and _load_chunks_by_ids to run per-document I/O
concurrently with asyncio.gather instead of sequential awaits. Preserve each
result’s document association while flattening gathered results, and enforce
_MAX_EVIDENCE_CHUNKS across the combined chunk collection rather than allowing
the per-document caps to multiply.

In `@rag/advanced_rag/harness/types.py`:
- Around line 127-130: Preserve a non-null chunks invariant in the ToolResult
model by changing chunks from an optional field to a list with a default_factory
list, while retaining docs as optional for routing results. Update the
ToolResult definition in types.py so consumers such as agent.py can safely slice
result.chunks without additional guards.

---

Nitpick comments:
In `@rag/advanced_rag/harness/agent.py`:
- Around line 342-343: Update the comment near the tool-answer handling in the
agent harness to remove ontology_navigate from the direct-answer claim, since
navigation.py’s ontology_navigate now returns an empty answer. Keep the guidance
referring to structured_query, which still provides direct answers.

In `@rag/advanced_rag/harness/tools/navigation.py`:
- Around line 317-322: Remove the redundant `doc_scope = []` normalization in
the ontology navigation flow. Update the empty-scope handling around the
`[Ontology navigation]` logging and return so it uses a single check and emits
only one log message before returning the existing empty response.
- Around line 521-529: Update the document routing flow in the visible
deduplication block to apply _NAV_MAX_DOCS before logging the count. Ensure
_LOG.info reports the length of the capped routed collection, and return that
same capped collection without changing deduplication behavior.

In `@rag/advanced_rag/harness/tools/registry.py`:
- Around line 64-66: Update the schema used by dataset_navigation_by_tree and
_navigate_schema so doc_scope is not advertised unless the router applies it;
either introduce a router-specific schema or enforce doc_scope as a pre-filter
on routed document IDs. Also revise the topic and keywords descriptions to
clearly distinguish navigation intent from search terms.
🪄 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: 96b10b72-9b65-40e9-921a-5bb874e40887

📥 Commits

Reviewing files that changed from the base of the PR and between b4170d0 and 0950607.

📒 Files selected for processing (8)
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/config.py
  • rag/advanced_rag/harness/pipeline.py
  • rag/advanced_rag/harness/tools/__init__.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/types.py

Comment thread rag/advanced_rag/harness/pipeline.py Resolved
Comment on lines +44 to +48
# Downstream scoping: a within-document tool inherits the doc IDs a prior
# router (dataset_navigation_by_tree) produced, unless the caller passed
# an explicit doc_scope.
if tool_name in _DOC_SCOPE_CONSUMERS and self._routed_docs and not kwargs.get("doc_scope"):
kwargs["doc_scope"] = list(self._routed_docs)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Where is Pipeline constructed, and how long does one instance live?
rg -n -C4 'Pipeline\(' --type=py -g '!**/pipeline.py'

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate pipeline.py =="
fd -a 'pipeline\.py$' . | sed 's#^\./##' | head -50

echo "== relevant file outline/contents =="
if [ -f rag/advanced_rag/harness/pipeline.py ]; then
  wc -l rag/advanced_rag/harness/pipeline.py
  cat -n rag/advanced_rag/harness/pipeline.py
fi

echo "== occurrences of DatasetNavigationByTree / ontology_navigate / graph_explore / _DOC_SCOPE_CONSUMERS =="
rg -n "DatasetNavigationByTree|ontology_navigate|graph_explore|_DOC_SCOPE_CONSUMERS|routed_docs|doc_scope|Pipeline" --type=py -g '!**/pipeline.py' | head -200

Repository: infiniflow/ragflow

Length of output: 8133


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== exact Pipeline references (all tracked Py files) =="
git ls-files '*.py' | xargs rg -n -C3 '\bPipeline\b|from .*import .*Pipeline|Pipeline\(' || true

echo "== advanced_rag harness package files =="
fd -a . rag/advanced_rag/harness | sed 's#^\./##' | sort | head -100
rg -n -C3 'DatasetNavigationByTree|ontology_navigate|graph_explore|doc_scope|tool_registry|TOOL_REGISTRY|execute\(' rag/advanced_rag/harness --type=py | head -300

echo "== package imports mentioning harness =="
rg -n -C3 'advanced_rag|harness|rag\.advanced_rag' --type=py | head -300

Repository: infiniflow/ragflow

Length of output: 50374


Reset per-claim routing state or key it by claim.

rag/advanced_rag/harness/orchestrator/agentic.py creates one Pipeline for an orchestrator cycle, so Pipeline._routed_docs can leak between claims when dataset_navigation_by_tree previously returned matches, then later finds none. Line 47 also makes an explicitly empty doc_scope inherit the previous claim’s scope, so callers cannot widen it without changing the API 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 `@rag/advanced_rag/harness/pipeline.py` around lines 44 - 48, The Pipeline
routing state in the downstream scoping logic must not leak between claims.
Update the pipeline/orchestrator flow around _routed_docs and
dataset_navigation_by_tree so routing results are reset or keyed per claim, and
change the doc_scope check to distinguish an explicitly supplied empty scope
from an omitted scope; only inherit _routed_docs when doc_scope was not
provided.

Comment on lines 20 to 26
register_tool(
"catalog_navigate",
_navigate_schema("catalog_navigate", "Get question-related chunks from the document's catalog (table of contents / page index)"),
catalog_navigate,
"ontology_navigate",
_navigate_schema("ontology_navigate", "Get question-related chunks from the given documents catalog (tree / page index / mind map). It always follows dataset navigation."),
ontology_navigate,
requires_compilation=True,
compilation_type=("toc", "page_index"),
compilation_type=("toc", "page_index", "mindmap"),
)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect _CATALOG_KINDS / _MINDMAP_KINDS and how compilation_map keys are produced.
fd -t f 'navigation.py' rag | xargs rg -n -C2 '_CATALOG_KINDS|_MINDMAP_KINDS\s*='
rg -n -C4 'compilation_map' --type=py -g '!**/tools/gating.py'

Repository: infiniflow/ragflow

Length of output: 890


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate relevant files and inspect the tool registration plus ontology_navigate implementation.
printf 'Relevant files:\n'
fd -t f '__init__.py$|navigation.py$' rag/advanced_rag | sort

printf '\nRegistry registration snippet:\n'
sed -n '1,60p' rag/advanced_rag/harness/tools/__init__.py

printf '\nOntology navigate and compilation loading snippets:\n'
nav="$(fd -t f 'navigation.py' rag/advanced_rag | head -n 1)"
if [ -n "$nav" ]; then
  wc -l "$nav"
  rg -n -C6 '_load_compiled_structure|_navigate_schema|ontology_navigate|_CATALOG_KINDS|_MINDMAP_KINDS|compilation_map|kinds' "$nav"
fi

Repository: infiniflow/ragflow

Length of output: 10975


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'All occurrences of _navigate_schema/register_tool/compilation_available:\n'
rg -n -C3 '_navigate_schema|compilation_available|compile.*available|requires_compilation|compilation_type' rag/advanced_rag --type=py

python3 - <<'PY'
from pathlib import Path

# Programmatic extraction: map the registered compilation_type string to runtime _CATALOG_KINDS and the normalized match set.
# This mirrors the relevant runtime behavior without executing repository code.
nav = Path('rag/advanced_rag/harness/tools/navigation.py').read_text()
cat_kinds = {"tree", "timeline", "raptor", "page_index", "pageindex"}
mind_kinds = {"mindmap", "mind_map"}

def normalize_kind(kind):
    kind = (kind or "").strip().lower().replace("-", "_")
    if kind in {"pageindex", "page_index", "knowledge_graph"}:
        return "timeline"
    return kind

registered = ("toc", "page_index", "mindmap")
normalized_registered = {normalize_kind(k) for k in registered}

print(f"registered_types={registered}")
print(f"runtime_ontology_kinds={cat_kinds}")
print(f"normalized_registered={normalized_registered}")
print(f"mindmap_registered_and_in_ontology_kinds={'mindmap' in cat_kinds}")
print(f"mindmap_registered_but_matches_compiled_kinds={'mindmap' in (cat_kinds | mindset_kinds)}")
print(f"normalized_registered_union_runtime_compilation_type={normalized_registered.difference(cat_kinds)}")

# Check normalizable overlap: these are catalog kinds that will count even though registered strings may differ.
print(f"normalized_overlap_with_runtime_catalog={{"pageindex", "knowledge_graph"}.intersection(cat_kinds)}")
PY

Repository: infiniflow/ragflow

Length of output: 9343


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Toolkit gating:\n'
cat -n rag/advanced_rag/harness/tools/gating.py | sed -n '1,130p'

printf '\nPipeline gating path:\n'
cat -n rag/advanced_rag/harness/pipeline.py | sed -n '120,155p'

printf '\nRegistry schema paths:\n'
cat -n rag/advanced_rag/harness/tools/registry.py | sed -n '1,75p'

Repository: infiniflow/ragflow

Length of output: 10553


Align ontology_navigate’s declared types with the runtime catalog kinds.

ontology_navigate is gated by ("toc", "page_index", "mindmap"), but at runtime it reads _CATALOG_KINDS = {"tree", "timeline", "raptor", "page_index", "pageindex"} via _load_compiled_structure, which normalizes pageindex to timeline. The registered "toc" type won’t match the tree/timeline catalog kinds, and "mindmap" lets a mindmap-only KB use this tool even though mindmap_navigate already owns that path. Update the registration to the actual kinds / runtime-normalized vocabulary.

🤖 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 20 - 26, Update the
ontology_navigate registration’s compilation_type to use the runtime-normalized
catalog kinds accepted by _load_compiled_structure, replacing the mismatched
"toc" and "mindmap" values with the appropriate tree/timeline vocabulary while
retaining "page_index". Keep mindmap_navigate responsible for mindmap-only
catalogs.

Comment on lines 279 to +291
entities: list[dict] = []
relations: list[dict] = []
per_doc: list[tuple[str, list[dict]]] = []
for doc_id in doc_scope:
structure = await _load_compiled_structure(tools, doc_id, kinds)
if structure["entities"] or structure["relations"]:
per_doc.append((doc_id, structure["entities"]))
entities.extend(structure["entities"])
relations.extend(structure["relations"])

if not entities and not relations:
_LOG.info(f"[{label}] These documents have no {noun} — falling back to a normal search.")
return await hybrid_search(tools, query=topic, keywords=keywords, doc_scope=doc_scope)
for e in structure.get("entities") or []:
if isinstance(e, dict) and (e.get("name") or "").strip():
entities.append({**e, "_doc_id": doc_id})
if not entities:
return []

_LOG.info("[%s] Read an outline of %d entity(ies) and %d relation(s).", label, len(entities), len(relations))
# 2. Ask the model which entities are relevant to the question.
selected = await _ask_nav_select(tools, query, entities, "entities", _MAX_ENTITIES)
if not selected:
return []

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n '_ask_structure|_NAV_SYSTEM\b|_render_structure' --type=py

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="rag/advanced_rag/harness/tools/navigation.py"
if [ -f "$file" ]; then
  wc -l "$file"
  sed -n '1,120p' "$file"
  echo '--- lines 200-310 ---'
  sed -n '200,310p' "$file"
  echo '--- call/search symbols ---'
  rg -n '_ask_structure|def _ask_structure|_NAV_SYSTEM\b|_render_structure|_ask_nav_select|_NAV_SELECT_SYSTEM' "$file"
else
  echo "missing $file"
  fd -a navigation.py .
fi

Repository: infiniflow/ragflow

Length of output: 10729


🏁 Script executed:

#!/bin/bash
set -euo pipefail
file="rag/advanced_rag/harness/tools/navigation.py"

echo '--- _ask_nav_select and system prompt ---'
sed -n '330,430p' "$file"

echo '--- navigation entrypoints and _ask_nav_select usages ---'
rg -n 'def .*navigate|_ask_nav_select\(|_navigate_within_doc\(|_ask_structure\(' "$file"

Repository: infiniflow/ragflow

Length of output: 5778


Route entity selection with a within-document prompt.

_ask_nav_select_to("entities", ...) uses _NAV_SELECT_SYSTEM, whose first line and numbering are framed as a dataset navigation tree ("question through a dataset's navigation tree"). For within-document compiled entities, use a prompt that names the current doc_id/query and removes dataset-leaf wording, or provide an entity-specific system prompt.

While revising this, _NAV_SYSTEM, _render_structure, and _ask_structure are only called from the Graph exploration path, which appears unused in the tool flow; remove the dead paths rather than keeping them as compatibility shims.

🤖 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 279 - 291, Update
the entity-selection flow around _ask_nav_select so it uses an entity-specific
prompt scoped to the current doc_id and query, without dataset-navigation or
dataset-leaf wording. Remove the unused Graph exploration paths _NAV_SYSTEM,
_render_structure, and _ask_structure rather than retaining compatibility shims;
preserve the existing selected-entity limits and empty-result handling.

Source: Coding guidelines

Comment on lines 280 to +307
for doc_id in doc_scope:
structure = await _load_compiled_structure(tools, doc_id, kinds)
if structure["entities"] or structure["relations"]:
per_doc.append((doc_id, structure["entities"]))
entities.extend(structure["entities"])
relations.extend(structure["relations"])

if not entities and not relations:
_LOG.info(f"[{label}] These documents have no {noun} — falling back to a normal search.")
return await hybrid_search(tools, query=topic, keywords=keywords, doc_scope=doc_scope)
for e in structure.get("entities") or []:
if isinstance(e, dict) and (e.get("name") or "").strip():
entities.append({**e, "_doc_id": doc_id})
if not entities:
return []

_LOG.info("[%s] Read an outline of %d entity(ies) and %d relation(s).", label, len(entities), len(relations))
# 2. Ask the model which entities are relevant to the question.
selected = await _ask_nav_select(tools, query, entities, "entities", _MAX_ENTITIES)
if not selected:
return []

answer, relevant = await _ask_structure(tools, topic, entities, relations, noun, label)
# 3. Load the chunks attached to the selected entities (grouped by doc).
ids_by_doc: dict[str, list[str]] = {}
seen: set[tuple[str, str]] = set()
for e in selected:
doc_id = e.get("_doc_id")
if not doc_id:
continue
for cid in e.get("source_chunk_ids") or []:
if isinstance(cid, str) and cid and (doc_id, cid) not in seen:
seen.add((doc_id, cid))
ids_by_doc.setdefault(doc_id, []).append(cid)

# Pull the source text behind the relevant entities, per originating doc.
chunks: list[dict] = []
for doc_id, doc_entities in per_doc:
ids = _entity_chunk_ids(doc_entities, relevant)
if ids:
chunks.extend(await _load_chunks_by_ids(tools, doc_id, ids))

if not chunks:
_LOG.info(f"[{label}] No source text behind those entities — falling back to a normal search.")
return await hybrid_search(tools, query=topic, keywords=keywords, doc_scope=doc_scope)

before = len(chunks)
narrowed = _narrow_by_keywords(chunks, keywords)
if narrowed:
chunks = narrowed
_LOG.info("[%s] Pulled %d source passage(s) behind those entities, kept %d after keyword filtering.", label, before, len(chunks))
else:
_LOG.info("[%s] Keyword filtering removed all %d passage(s); restoring unfiltered set.", label, before)

return {"answer": answer, "chunks": chunks, "doc_aggs": _doc_aggs(chunks)}
for doc_id, ids in ids_by_doc.items():
chunks.extend(await _load_chunks_by_ids(tools, doc_id, ids))

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.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Sequential per-document I/O on the request path; evidence cap applies per doc.

Two issues in this loop pair:

  • With _NAV_MAX_DOCS = 8 routed docs, step 1 issues 8 sequential _load_compiled_structure calls (2 doc-store queries each) and step 3 issues up to 8 more sequential chunk fetches. asyncio.gather would collapse this to roughly one round-trip's latency.
  • _load_chunks_by_ids caps at _MAX_EVIDENCE_CHUNKS per document (Line 179/183), so the aggregate here can reach 8 × the intended cap before it reaches the agent.
⚡ Proposed fix
-    entities: list[dict] = []
-    for doc_id in doc_scope:
-        structure = await _load_compiled_structure(tools, doc_id, kinds)
-        for e in structure.get("entities") or []:
-            if isinstance(e, dict) and (e.get("name") or "").strip():
-                entities.append({**e, "_doc_id": doc_id})
+    structures = await asyncio.gather(*(_load_compiled_structure(tools, d, kinds) for d in doc_scope))
+    entities: list[dict] = []
+    for doc_id, structure in zip(doc_scope, structures):
+        for e in structure.get("entities") or []:
+            if isinstance(e, dict) and (e.get("name") or "").strip():
+                entities.append({**e, "_doc_id": doc_id})
-    chunks: list[dict] = []
-    for doc_id, ids in ids_by_doc.items():
-        chunks.extend(await _load_chunks_by_ids(tools, doc_id, ids))
+    per_doc = await asyncio.gather(*(_load_chunks_by_ids(tools, d, ids) for d, ids in ids_by_doc.items()))
+    chunks = [c for batch in per_doc for c in batch][:_MAX_EVIDENCE_CHUNKS]
📝 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.

Suggested change
for doc_id in doc_scope:
structure = await _load_compiled_structure(tools, doc_id, kinds)
if structure["entities"] or structure["relations"]:
per_doc.append((doc_id, structure["entities"]))
entities.extend(structure["entities"])
relations.extend(structure["relations"])
if not entities and not relations:
_LOG.info(f"[{label}] These documents have no {noun} — falling back to a normal search.")
return await hybrid_search(tools, query=topic, keywords=keywords, doc_scope=doc_scope)
for e in structure.get("entities") or []:
if isinstance(e, dict) and (e.get("name") or "").strip():
entities.append({**e, "_doc_id": doc_id})
if not entities:
return []
_LOG.info("[%s] Read an outline of %d entity(ies) and %d relation(s).", label, len(entities), len(relations))
# 2. Ask the model which entities are relevant to the question.
selected = await _ask_nav_select(tools, query, entities, "entities", _MAX_ENTITIES)
if not selected:
return []
answer, relevant = await _ask_structure(tools, topic, entities, relations, noun, label)
# 3. Load the chunks attached to the selected entities (grouped by doc).
ids_by_doc: dict[str, list[str]] = {}
seen: set[tuple[str, str]] = set()
for e in selected:
doc_id = e.get("_doc_id")
if not doc_id:
continue
for cid in e.get("source_chunk_ids") or []:
if isinstance(cid, str) and cid and (doc_id, cid) not in seen:
seen.add((doc_id, cid))
ids_by_doc.setdefault(doc_id, []).append(cid)
# Pull the source text behind the relevant entities, per originating doc.
chunks: list[dict] = []
for doc_id, doc_entities in per_doc:
ids = _entity_chunk_ids(doc_entities, relevant)
if ids:
chunks.extend(await _load_chunks_by_ids(tools, doc_id, ids))
if not chunks:
_LOG.info(f"[{label}] No source text behind those entities — falling back to a normal search.")
return await hybrid_search(tools, query=topic, keywords=keywords, doc_scope=doc_scope)
before = len(chunks)
narrowed = _narrow_by_keywords(chunks, keywords)
if narrowed:
chunks = narrowed
_LOG.info("[%s] Pulled %d source passage(s) behind those entities, kept %d after keyword filtering.", label, before, len(chunks))
else:
_LOG.info("[%s] Keyword filtering removed all %d passage(s); restoring unfiltered set.", label, before)
return {"answer": answer, "chunks": chunks, "doc_aggs": _doc_aggs(chunks)}
for doc_id, ids in ids_by_doc.items():
chunks.extend(await _load_chunks_by_ids(tools, doc_id, ids))
structures = await asyncio.gather(*(_load_compiled_structure(tools, d, kinds) for d in doc_scope))
entities: list[dict] = []
for doc_id, structure in zip(doc_scope, structures):
for e in structure.get("entities") or []:
if isinstance(e, dict) and (e.get("name") or "").strip():
entities.append({**e, "_doc_id": doc_id})
if not entities:
return []
# 2. Ask the model which entities are relevant to the question.
selected = await _ask_nav_select(tools, query, entities, "entities", _MAX_ENTITIES)
if not selected:
return []
# 3. Load the chunks attached to the selected entities (grouped by doc).
ids_by_doc: dict[str, list[str]] = {}
seen: set[tuple[str, str]] = set()
for e in selected:
doc_id = e.get("_doc_id")
if not doc_id:
continue
for cid in e.get("source_chunk_ids") or []:
if isinstance(cid, str) and cid and (doc_id, cid) not in seen:
seen.add((doc_id, cid))
ids_by_doc.setdefault(doc_id, []).append(cid)
per_doc = await asyncio.gather(*(_load_chunks_by_ids(tools, d, ids) for d, ids in ids_by_doc.items()))
chunks = [c for batch in per_doc for c in batch][:_MAX_EVIDENCE_CHUNKS]
🤖 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 280 - 307, Update
the entity-loading and chunk-loading flows around _load_compiled_structure and
_load_chunks_by_ids to run per-document I/O concurrently with asyncio.gather
instead of sequential awaits. Preserve each result’s document association while
flattening gathered results, and enforce _MAX_EVIDENCE_CHUNKS across the
combined chunk collection rather than allowing the per-document caps to
multiply.

Comment on lines 342 to +349
_NAV_MAX_DOCS = 8 # documents the nav tree routes a query to
_NAV_MAX_HITS_PER_KB = 8

# Tree-walk router tunables.
_NAV_MAX_CLUSTERS = 500 # top-level clusters listed / rendered to the LLM
_NAV_CHILDREN_PAGE_SIZE = 1000 # children fetched per node
_NAV_TREE_MAX_DEPTH = 6 # BFS depth cap when descending sub-clusters to leaves
_NAV_TREE_MAX_LEAVES = 300 # document leaves rendered to the doc-select LLM

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n '_NAV_MAX_HITS_PER_KB' --type=py

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="rag/advanced_rag/harness/tools/navigation.py"

echo "== file exists and size =="
wc -l "$FILE"

echo "== outline around relevant symbols =="
ast-grep outline "$FILE" --match '_ask_nav_select' --view expanded || true
ast-grep outline "$FILE" --match 'message_fit_in' --view expanded || true
ast-grep outline "$FILE" --match 'def dataset_navigate' --view expanded || true

echo "== lines 320-440 =="
sed -n '320,460p' "$FILE" | cat -n | sed 's/^/L/' 

echo "== usages of NAV constants and max_items =="
rg -n '_NAV_MAX_(CLUSTERS|HITS_PER_KB|LEAVES)|_ask_nav_select|max_items|message_fit_in' "$FILE" -C 3

Repository: infiniflow/ragflow

Length of output: 11507


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate generator.py =="
fd -a 'generator.py' . | sed 's#^\./##'

GEN="$(fd 'generator.py' | rg 'prompts/generator.py$' | head -1 || true)"
echo "== generator.py path =="
echo "$GEN"
if [ -n "$GEN" ]; then
  echo "== generator.py outline =="
  ast-grep outline "$GEN" --match 'message_fit_in' --view expanded || true
  ast-grep outline "$GEN" --match 'form_message' --view expanded || true
  echo "== relevant generator.py slices =="
  rg -n 'def form_message|def message_fit_in|message_fit_in|form_message|max_length' "$GEN" -C 8
fi

echo "== model max_length references in navigation.py =="
rg -n 'max_length|chat_mdl' rag/advanced_rag/harness/tools/navigation.py -C 2

Repository: infiniflow/ragflow

Length of output: 12490


Don’t let message_fit_in trim after indexing the selection list.

_NAV_MAX_CLUSTERS = 500 and _NAV_TREE_MAX_LEAVES = 300 render a long numbered list, then message_fit_in(..., tools.chat_mdl.max_length) can truncate message content while _ask_nav_select still accepts returned indices in 0 <= idx < len(capped). If capped[50] is the first rendered item after trimming, an accepted index 0 is resolved to capped[0], which the model did not see. Cap the rendered list to safely fit the token budget and validate returned indices against exactly what was sent.

_NAV_MAX_HITS_PER_KB has no remaining Python consumer, so remove 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 `@rag/advanced_rag/harness/tools/navigation.py` around lines 342 - 349, The
navigation selection flow must avoid post-indexing truncation and remove the
unused _NAV_MAX_HITS_PER_KB constant. Update the list-rendering logic used by
_ask_nav_select so the numbered cluster/leaf lists are capped to fit the model’s
token budget before indices are assigned, then validate and resolve returned
indices against exactly that rendered list; do not apply message_fit_in after
indexing.

Source: Coding guidelines

Comment on lines +431 to +453
while frontier and len(leaves) < _NAV_TREE_MAX_LEAVES:
kb, name, depth = frontier.pop(0)
node_key = (kb.id, name)
if node_key in seen_nodes:
continue
seen_nodes.add(node_key)
try:
hits = await search_dataset_nav(
kb.tenant_id,
kb.id,
query,
embd_mdl=getattr(tools, "embed_mdl", None),
top_k=_NAV_MAX_HITS_PER_KB,
)
ok, data = await dataset_api_service.list_nav_children(kb.id, kb.tenant_id, name, page=1, page_size=_NAV_CHILDREN_PAGE_SIZE)
except Exception:
_LOG.exception("[Dataset navigation] nav-tree search failed for kb=%s", kb.id)
_LOG.exception("[Dataset navigation] list_nav_children failed for kb=%s node=%s", kb.id, name)
continue
for h in hits:
score = float(h.get("score") or 0.0)
node_name = str(h.get("name") or "")
if node_name and node_name not in seen_nodes:
seen_nodes.add(node_name)
nav_entities.append(
{
"name": node_name,
"type": h.get("type") or "dataset_nav",
"description": h.get("description") or "",
}
)
for did in h.get("doc_ids") or []:
if did and did not in seen:
seen.add(did)
candidates.append((score, did))

candidates.sort(key=lambda item: item[0], reverse=True)
routed = [did for _, did in candidates[:_NAV_MAX_DOCS]]
if not routed:
_LOG.info("[Dataset navigation] No dataset map here — falling back to a normal search.")
return await hybrid_search(tools, query=query, keywords=keywords)

_LOG.info("[Dataset navigation] Routed to %d document(s); searching within them.", len(routed))
answer = ""
if nav_entities:
answer, _ = await _ask_structure(tools, query, nav_entities, [], "dataset map", "Dataset navigation")
result = await hybrid_search(tools, query=query, keywords=keywords, doc_scope=routed)
result["answer"] = answer
return result
if not ok or not isinstance(data, dict):
continue
for item in data.get("items") or []:
if item.get("type") == "doc":
did = str(item.get("doc_id") or "").strip()
if did and did not in seen_docs:
seen_docs.add(did)
leaves.append({**item, "kb": kb})
if len(leaves) >= _NAV_TREE_MAX_LEAVES:
break
elif item.get("type") == "cluster" and item.get("name") and depth + 1 < _NAV_TREE_MAX_DEPTH:
frontier.append((kb, item["name"], depth + 1))

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 | 🟠 Major | ⚡ Quick win

BFS is leaf- and depth-capped but not node-capped — unbounded list_nav_children calls.

_NAV_TREE_MAX_LEAVES only stops the walk once document leaves accumulate. A subtree that is all sub-clusters down to depth 6 never increments leaves, so the frontier can grow to (selected clusters × _NAV_CHILDREN_PAGE_SIZE) nodes, each costing a sequential awaited doc-store query on the request path. Add a visited-node/expansion budget.

frontier.pop(0) on a list is also O(n); collections.deque is the right structure here.

⚡ Proposed fix
-    frontier: list[tuple] = [(c["kb"], c["name"], 0) for c in clusters if c.get("name")]
+    frontier = deque((c["kb"], c["name"], 0) for c in clusters if c.get("name"))
 
-    while frontier and len(leaves) < _NAV_TREE_MAX_LEAVES:
-        kb, name, depth = frontier.pop(0)
+    while frontier and len(leaves) < _NAV_TREE_MAX_LEAVES and len(seen_nodes) < _NAV_TREE_MAX_NODES:
+        kb, name, depth = frontier.popleft()
🧰 Tools
🪛 Ruff (0.15.21)

[warning] 439-439: Do not catch blind exception: Exception

(BLE001)

🤖 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 431 - 453, Update
the navigation traversal around the frontier loop to use collections.deque with
popleft() instead of list.pop(0), and add a bounded node-expansion budget
independent of document leaves. Enforce the budget before each list_nav_children
call, incrementing it only for nodes actually expanded, while preserving
seen_nodes deduplication and existing depth/leaf limits.

Comment thread rag/advanced_rag/harness/types.py Resolved

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
rag/advanced_rag/harness/tools/navigation.py (1)

108-108: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Keep shared-loader log labels caller-aware.

These helpers serve both ontology_navigate and mindmap_navigate, but both failure paths hard-code ontology_navigate; mindmap failures will be misattributed. Pass the operation name into the helper or use a neutral compiled-navigation label.

Also applies to: 189-189

🤖 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` at line 108, The shared
navigation helpers currently hard-code the “ontology_navigate” label in failure
logs, misattributing mindmap operations. Update the helper’s logging path and
its callers to pass and use the current operation name, or replace the label
with a neutral compiled-navigation label, including both reported failure paths.
🧹 Nitpick comments (1)
rag/advanced_rag/harness/tools/navigation.py (1)

457-459: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Bound the cluster-name log payload.

_nav_cluster_names joins every selected name; with up to _NAV_MAX_CLUSTERS candidates and unconstrained labels, these INFO logs can expose excessive dataset metadata and create unnecessarily large log entries. Log the count plus a small, length-limited sample.

Also applies to: 517-523

🤖 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 457 - 459, Update
_nav_cluster_names to return the total selected-cluster count plus only a small,
length-limited sample of non-empty names, rather than joining every label.
Preserve trimming and the “none” behavior when no usable names exist, and ensure
callers such as the related logging path use this bounded summary.
🤖 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.

Outside diff comments:
In `@rag/advanced_rag/harness/tools/navigation.py`:
- Line 108: The shared navigation helpers currently hard-code the
“ontology_navigate” label in failure logs, misattributing mindmap operations.
Update the helper’s logging path and its callers to pass and use the current
operation name, or replace the label with a neutral compiled-navigation label,
including both reported failure paths.

---

Nitpick comments:
In `@rag/advanced_rag/harness/tools/navigation.py`:
- Around line 457-459: Update _nav_cluster_names to return the total
selected-cluster count plus only a small, length-limited sample of non-empty
names, rather than joining every label. Preserve trimming and the “none”
behavior when no usable names exist, and ensure callers such as the related
logging path use this bounded summary.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d241be54-5875-4f6e-86c3-192f5e950e3c

📥 Commits

Reviewing files that changed from the base of the PR and between 0950607 and 551632a.

📒 Files selected for processing (5)
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/pipeline.py
  • rag/advanced_rag/harness/tools/gating.py
  • rag/advanced_rag/harness/tools/navigation.py
  • rag/advanced_rag/harness/types.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • rag/advanced_rag/harness/types.py
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/tools/gating.py
  • rag/advanced_rag/harness/pipeline.py

@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (8b793ee) to head (22fec5f).
⚠️ Report is 50 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #17490      +/-   ##
==========================================
- Coverage   94.56%   90.65%   -3.91%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      650      -28     
- Misses         25       39      +14     
- Partials       14       28      +14     

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

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 29, 2026

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/advanced_rag/harness/agent.py`:
- Line 91: Update the sufficiency-check logging around the navigation verdict to
use _LOG.debug or _LOG.info instead of _LOG.exception for successful checks,
while retaining _LOG.exception only in the failure handler.
- Line 87: Update the sufficiency-judge call in the agent’s pipeline flow to
enforce a short timeout around pipeline.tools.chat_mdl.async_chat. If the
request times out or otherwise cannot complete, fail open by continuing with
broader search rather than blocking the research-agent loop.
🪄 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: 21c5f2db-55a7-4e74-8299-ce69dc6a6634

📥 Commits

Reviewing files that changed from the base of the PR and between 551632a and 22fec5f.

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

return False
system = "Judge whether the passages already contain enough information to answer the task. Reply with a single word: YES or NO."
user = f"Task:\n{self.claim.description}\n\nPassages:\n{passages}\n\nAnswer (YES or NO):"
ans = await self.pipeline.tools.chat_mdl.async_chat(system, [{"role": "user", "content": user}], {"temperature": 0.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 | 🟠 Major | ⚡ Quick win

Bound the sufficiency-judge request.

This new external model call has no timeout; a stalled provider can hold the research-agent loop indefinitely. Fail open to broader search after a short deadline.

Proposed fix
+import asyncio
...
-            ans = await self.pipeline.tools.chat_mdl.async_chat(system, [{"role": "user", "content": user}], {"temperature": 0.0})
+            ans = await asyncio.wait_for(
+                self.pipeline.tools.chat_mdl.async_chat(
+                    system,
+                    [{"role": "user", "content": user}],
+                    {"temperature": 0.0},
+                ),
+                timeout=15,
+            )
📝 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.

Suggested change
ans = await self.pipeline.tools.chat_mdl.async_chat(system, [{"role": "user", "content": user}], {"temperature": 0.0})
ans = await asyncio.wait_for(
self.pipeline.tools.chat_mdl.async_chat(
system,
[{"role": "user", "content": user}],
{"temperature": 0.0},
),
timeout=15,
)
🤖 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/agent.py` at line 87, Update the sufficiency-judge
call in the agent’s pipeline flow to enforce a short timeout around
pipeline.tools.chat_mdl.async_chat. If the request times out or otherwise cannot
complete, fail open by continuing with broader search rather than blocking the
research-agent loop.

if isinstance(ans, tuple):
ans = ans[0]
ans = re.sub(r"^.*</think>", "", ans or "", flags=re.DOTALL)
_LOG.exception("[Navigation] sufficiency check: %s", ans)

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 | 🟡 Minor | ⚡ Quick win

Do not log successful verdicts as exceptions.

_LOG.exception emits an error-level traceback (NoneType: None) on every completed check, polluting error monitoring. Use debug or info; retain exception for the failure handler.

-            _LOG.exception("[Navigation] sufficiency check: %s", ans)
+            _LOG.debug("[Navigation] sufficiency check: %s", ans)
📝 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.

Suggested change
_LOG.exception("[Navigation] sufficiency check: %s", ans)
_LOG.debug("[Navigation] sufficiency check: %s", ans)
🤖 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/agent.py` at line 91, Update the sufficiency-check
logging around the navigation verdict to use _LOG.debug or _LOG.info instead of
_LOG.exception for successful checks, while retaining _LOG.exception only in the
failure handler.

@yingfeng yingfeng added ci Continue Integration and removed ci Continue Integration labels Jul 29, 2026
@yingfeng
yingfeng merged commit 06562cb into infiniflow:main Jul 29, 2026
11 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 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