Skip to content

Fix: graph explore bug. - #17829

Merged
KevinHuSh merged 1 commit into
infiniflow:mainfrom
KevinHuSh:refine/agentic_search1
Aug 5, 2026
Merged

KevinHuSh merged 1 commit into
infiniflow:mainfrom
KevinHuSh:refine/agentic_search1

Conversation

@KevinHuSh

Copy link
Copy Markdown
Contributor

Summary

Fix: graph explore bug.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 5, 2026
@KevinHuSh KevinHuSh added ci Continue Integration and removed 🐞 bug Something isn't working, pull request that fix bug. size:M This PR changes 30-99 lines, ignoring generated files. labels Aug 5, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft August 5, 2026 02:53
@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The orchestrator now tracks discovered entities from gathered chunks or document names. The context preserves valid entity names for later eligibility checks. LiteLLM tool results remove closing </think> markers before history storage.

Changes

Orchestration Entity Tracking

Layer / File(s) Summary
Discover and record orchestration entities
rag/advanced_rag/harness/orchestrator/agentic.py, rag/advanced_rag/harness/types.py
The orchestrator extracts the first non-empty entity, keyword, or document name. OrchestratorContext.note_entity stores valid trimmed values before sufficiency evaluation.

Tool History Cleanup

Layer / File(s) Summary
Clean LiteLLM tool results
rag/llm/chat_model.py
_append_history_batch removes closing </think> markers from LiteLLM tool result content before appending it to conversation history.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested labels: 🐞 bug, 🌈 python

Poem

I’m a rabbit, tracking names with care,
From chunks and documents everywhere.
Think markers leave the history stream,
Clean paths now support the graph’s next dream.
Hop, hop—context stays bright and clear!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly identifies the graph exploration bug fix, which matches the primary objective and changes.
Description check ✅ Passed The description includes the required Summary section and briefly states that the graph exploration bug is fixed.

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

🧹 Nitpick comments (1)
rag/llm/chat_model.py (1)

2002-2002: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add regression tests for tool-result cleanup.

Test string results, dictionary results, and error results. Verify that </think> is removed and all other content remains unchanged.

🤖 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/llm/chat_model.py` at line 2002, Add regression tests covering the
tool-result cleanup in the history-building flow around the tool-result append
logic. Test string, dictionary, and error results, verifying that each removes
every </think> marker while preserving all other content unchanged.
🤖 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/orchestrator/agentic.py`:
- Around line 120-123: Update the Step A.5 flow around ctx.note_entity and
_discovered_entity to log the eligibility transition, including the current
round and whether the candidate and resulting context contain an entity. Redact
entity values rather than logging raw entities, and emit the log after updating
the context so both states are represented.
- Around line 38-45: Update the first discovered-tag selection in
_discovered_entity to iterate array values and return the first non-empty string
after trimming, ignoring None and blank items so they cannot become "None" or
block later valid tags. Preserve the existing string-value handling and
graph_explore gating behavior for valid tags.

---

Nitpick comments:
In `@rag/llm/chat_model.py`:
- Line 2002: Add regression tests covering the tool-result cleanup in the
history-building flow around the tool-result append logic. Test string,
dictionary, and error results, verifying that each removes every </think> marker
while preserving all other content unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 39cc729f-96d6-4f12-b2ba-76a67cb888da

📥 Commits

Reviewing files that changed from the base of the PR and between f063cfd and effebda.

📒 Files selected for processing (3)
  • rag/advanced_rag/harness/orchestrator/agentic.py
  • rag/advanced_rag/harness/types.py
  • rag/llm/chat_model.py

Comment on lines +38 to +45
for key in ("entities_kwd", "important_kwd"):
val = c.get(key)
if isinstance(val, list) and val:
first = str(val[0]).strip()
if first:
return first
if isinstance(val, str) and val.strip():
return val.strip().split()[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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Expect: producers and tests guarantee non-empty string list items,
# or the helper is updated to validate each item.
rg -n -C 6 '\b(entities_kwd|important_kwd|docnm_kwd)\b' --glob '*.py'

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "repo files count:"
git ls-files | wc -l

echo "target file presence:"
git ls-files | rg '(^|/)agentic\.py$|\.py$' | head -100

echo "search all tracked files for keywords:"
git grep -n -C 3 '\b(entities_kwd|important_kwd|docnm_kwd)\b' -- '*.py' 2>/dev/null || true

echo "search all tracked files around discovered_entity/graph_explore:"
git grep -n -C 3 '_discovered_entity|graph_explore|note_entity|OrchestratorContext' -- '*.py' 2>/dev/null || true

Repository: infiniflow/ragflow

Length of output: 3434


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "list files matching agentic.py:"
git ls-files | rg '(^|/)agentic\.py$' || true

echo "target file stat:"
if git ls-files | rg -q '(^|/)rag/advanced_rag/harness/orchestrator/agentic\.py$'; then
  wc -l rag/advanced_rag/harness/orchestrator/agentic.py
  sed -n '1,140p' rag/advanced_rag/harness/orchestrator/agentic.py
else
  echo "target file missing"
fi

echo "search repository for exact keyword strings even if Python-only result empty:"
find . -type f \( -name '*.py' -o -name '*.pyi' -o -name '*.md' -o -name '*.json' -o -name '*.yaml' -o -name '*.yml' \) -print0 \
  | xargs -0 grep -n -C 3 'entities_kwd\|important_kwd\|docnm_kwd' 2>/dev/null || true

Repository: infiniflow/ragflow

Length of output: 50377


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "target file exists?"
test -f rag/advanced_rag/harness/orchestrator/agentic.py && echo yes || echo no

echo "tracked target file:"
git ls-files -z | awk 'BEGIN{RS="\0"} $0=="rag/advanced_rag/harness/orchestrator/agentic.py"' || true

echo "target direct contents with cat -n:"
if test -f rag/advanced_rag/harness/orchestrator/agentic.py; then
  wc -l rag/advanced_rag/harness/orchestrator/agentic.py
  cat -n rag/advanced_rag/harness/orchestrator/agentic.py | sed -n '1,160p'
else
  echo "file missing in working tree"
fi

echo "focused search for orchestrator/agentic.py and helpers in files that exist:"
for file in $(git ls-files | grep 'agentic.py\|orchestrator' | grep '\.py$'); do
  if rg -q '_discovered_entity|entities_kwd|important_kwd|graph_explore|OrchestratorContext' "$file"; then
    echo "---- $file ----"
    wc -l "$file"
    rg -n -C 4 '_discovered_entity|entities_kwd|important_kwd|graph_explore|OrchestratorContext' "$file"
  fi
done

Repository: infiniflow/ragflow

Length of output: 12421


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "types.py:"
wc -l rag/advanced_rag/harness/types.py
cat -n rag/advanced_rag/harness/types.py | sed -n '1,220p'

echo "search orchestrator tests and fixtures for graph_explore/entities_kwd/importants:"
rg -n -C 4 'graph_explore|entities_kwd|important_kwd|note_entity|OrchestratorContext|graph_explore' test rag/advanced_rag/harness --glob '*.py' | head -300

Repository: infiniflow/ragflow

Length of output: 30787


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "search for assignments to entities_kwd/important_kwd in orchestrator sources:"
rg -n -C 4 'entities_kwd|important_kwd' rag/advanced_rag/harness test --glob '*.py' --glob '*.json' --glob '*.yaml' --glob '*.yml' 2>/dev/null | head -250

echo "inspect hybrid_search/vector_search chunk construction if present:"
find rag/advanced_rag/harness -type f -name '*.py' | xargs rg -n -C 4 'kbinfos|chunks|docnm_kwd|important|entity' || true

echo "run a small behavioral probe for current _discovered_entity semantics from the file text:"
python3 - <<'PY'
def current_discovered_entity(kbinfos):
    chunks = (kbinfos or {}).get("chunks", []) or []
    for c in chunks:
        for key in ("entities_kwd", "important_kwd"):
            val = c.get(key)
            if isinstance(val, list) and val:
                first = str(val[0]).strip()
                if first:
                    return first
            if isinstance(val, str) and val.strip():
                return val.strip().split()[0]
    for c in chunks:
        name = str(c.get("docnm_kwd") or "").strip()
        if name:
            return name
    return None

def improved_discovered_entity(kbinfos):
    chunks = (kbinfos or {}).get("chunks", []) or []
    for c in chunks:
        for key in ("entities_kwd", "important_kwd"):
            val = c.get(key) or []
            if isinstance(val, list):
                for item in val:
                    s = str(item).strip() if item is not None else ""
                    if s:
                        return s
            elif isinstance(val, str) and val.strip():
                return val.strip().split()[0]
    for c in chunks:
        name = str(c.get("docnm_kwd") or "").strip()
        if name:
            return name
    return None

cases = {
    "list_with_None_first": {"chunks": [{"entities_kwd": [None, "valid_entity"]}], "docnm_kwd": ""},
    "list_with_blank_first": {"chunks": [{"entities_kwd": ["", "   ", "valid_entity"]}], "docnm_kwd": ""},
    "string_first": {"chunks": [{"entities_kwd": ["first"]}], "docnm_kwd": ""},
    "all_blank_valid_only_docnm": {"chunks": [{"entities_kwd": [], "important_kwd": ["  "], "docnm_kwd": "Doc name"}]},
}
for name, kbinfos in cases.items():
    print(name, "current=", current_discovered_entity(kbinfos), "improved=", improved_discovered_entity(kbinfos))
PY

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "schema migration fields around entities_kwd/important_kwd:"
sed -n '30,70p' tools/es-to-oceanbase-migration/src/es_ob_migration/schema.py

echo "behavioral probe from target code:"
python3 - <<'PY'
def current_discovered_entity(kbinfos):
    chunks = (kbinfos or {}).get("chunks", []) or []
    for c in chunks:
        for key in ("entities_kwd", "important_kwd"):
            val = c.get(key)
            if isinstance(val, list) and val:
                first = str(val[0]).strip()
                if first:
                    return first
            if isinstance(val, str) and val.strip():
                return val.strip().split()[0]
    for c in chunks:
        name = str(c.get("docnm_kwd") or "").strip()
        if name:
            return name
    return None

cases = {
    "None_first": {"chunks": [{"entities_kwd": [None, "valid_entity"]}], "docnm_kwd": ""},
    "blank_first": {"chunks": [{"entities_kwd": ["", "   ", "valid_entity"]}], "docnm_kwd": ""},
    "non_empty_first": {"chunks": [{"entities_kwd": ["first", "second"]}], "docnm_kwd": ""},
    "all_blank_docnm_fallback": {"chunks": [{"entities_kwd": ["  "], "docnm_kwd": "Doc name"}]},
}
for name, kbinfos in cases.items():
    print(f"{name}: {current_discovered_entity(kbinfos)!r}")
PY

Repository: infiniflow/ragflow

Length of output: 3004


Sanitize the first discovered chunk tag before gating graph_explore.

entities_kwd and important_kwd are nullable string arrays, and the current selector converts val[0] with str(...), so a None item stores "None" as context.last_entity and makes graph_explore eligible. A blank first item also skips later valid items. Validate each array item and pick the first non-empty string, or enforce that these fields contain only non-empty strings before _discovered_entity is used.

🤖 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/orchestrator/agentic.py` around lines 38 - 45,
Update the first discovered-tag selection in _discovered_entity to iterate array
values and return the first non-empty string after trimming, ignoring None and
blank items so they cannot become "None" or block later valid tags. Preserve the
existing string-value handling and graph_explore gating behavior for valid tags.

Comment on lines +120 to +123
# ── Step A.5: note a discovered entity so graph_explore becomes eligible
# in the next round (its context gate requires context.last_entity). ──
ctx.note_entity(_discovered_entity(tools))

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

Add logging for the new eligibility transition.

This call changes whether graph_explore is offered in the next round. Record the round and whether the candidate and resulting context contain an entity. Do not log the raw entity without redaction.

Based on coding guidelines: **/*.py: Add logging for new flows.

Proposed logging change
-        ctx.note_entity(_discovered_entity(tools))
+        discovered_entity = _discovered_entity(tools)
+        ctx.note_entity(discovered_entity)
+        _LOG.info(
+            "[Agentic research] Round %d: entity candidate=%s, graph_explore eligible=%s",
+            cycle + 1,
+            bool(discovered_entity),
+            bool(ctx.last_entity),
+        )
📝 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
# ── Step A.5: note a discovered entity so graph_explore becomes eligible
# in the next round (its context gate requires context.last_entity). ──
ctx.note_entity(_discovered_entity(tools))
# ── Step A.5: note a discovered entity so graph_explore becomes eligible
# in the next round (its context gate requires context.last_entity). ──
discovered_entity = _discovered_entity(tools)
ctx.note_entity(discovered_entity)
_LOG.info(
"[Agentic research] Round %d: entity candidate=%s, graph_explore eligible=%s",
cycle + 1,
bool(discovered_entity),
bool(ctx.last_entity),
)
🤖 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/orchestrator/agentic.py` around lines 120 - 123,
Update the Step A.5 flow around ctx.note_entity and _discovered_entity to log
the eligibility transition, including the current round and whether the
candidate and resulting context contain an entity. Redact entity values rather
than logging raw entities, and emit the log after updating the context so both
states are represented.

Source: Coding guidelines

@KevinHuSh
KevinHuSh marked this pull request as ready for review August 5, 2026 03:00
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Aug 5, 2026
@codecov

codecov Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (f063cfd) to head (effebda).
⚠️ Report is 6 commits behind head on main.

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

☔ 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 added ci Continue Integration and removed ci Continue Integration labels Aug 5, 2026
@KevinHuSh
KevinHuSh merged commit 510e119 into infiniflow:main Aug 5, 2026
15 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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants