Skip to content

fix: refine structure graph keyword search - #18181

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b157
Aug 13, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b157

Conversation

@buua436

@buua436 buua436 commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes structure graph keyword search accuracy and incomplete tree paths.

  • Prioritizes exact entity-name matching before lexical or semantic fallback.
  • Tokenizes BM25 queries consistently with indexed structure content.
  • Limits KNN fallback to one semantic match to avoid unrelated sibling nodes.
  • Returns the matched tree or page-index node with its complete ancestor path and relations up to the root.
  • Handles relation endpoint casing consistently across document- and dataset-level structures.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Aug 12, 2026
@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The keyword subgraph search now prioritizes exact normalized names, tokenizes BM25 queries, and limits KNN fallback to one candidate. Tree traversal collects ancestor entities and returns matched paths with their relations. Unit tests cover each behavior.

Changes

Keyword graph search

Layer / File(s) Summary
Keyword matching and fallback
api/apps/services/structure_graph_common.py, test/unit_test/api/apps/services/test_structure_graph_common.py
Exact normalized name lookup runs before tokenized BM25 matching. Semantic fallback uses one KNN candidate. Tests validate query construction and fallback behavior.
Tree ancestor expansion
api/apps/services/structure_graph_common.py, test/unit_test/api/apps/services/test_structure_graph_common.py
Tree traversal checks endpoint spellings individually, collects ancestors, and returns matching ancestor paths and relations.

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

Mergeability Score: 🔵 Low · up to e075f

The PR refines keyword matching and tree-path results; the remaining bounded risk is that new search branches lack structured debug logging, which could make production diagnosis harder without indicating a correctness or availability failure. The PR is mergeable with owner awareness or a follow-up to add non-sensitive debug logging.

Sequence Diagram(s)

sequenceDiagram
  participant keyword_subgraph
  participant BM25Search
  participant KNNSearch
  participant TreeTraversal
  keyword_subgraph->>BM25Search: normalized exact and tokenized query
  BM25Search-->>keyword_subgraph: keyword matches
  keyword_subgraph->>KNNSearch: one-candidate fallback query
  KNNSearch-->>keyword_subgraph: semantic match
  keyword_subgraph->>TreeTraversal: matched endpoints
  TreeTraversal-->>keyword_subgraph: ancestors and path relations
Loading

Possibly related PRs

  • infiniflow/ragflow#18055: Both changes refine keyword subgraph search and tree ancestor handling in structure_graph_common.py.

Suggested reviewers: kevinhush, wangq8

Poem

A rabbit checks each name with care,
Then sends tokenized queries there.
One KNN leaf returns the prize,
Ancestors rise in linked replies.
The graph comes home, complete and wise.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change to structure graph keyword search.
Description check ✅ Passed The description clearly explains the problem and lists the main fixes, although it uses an alternate heading instead of the template's Summary heading.
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.

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.

@buua436 buua436 added the ci Continue Integration label Aug 12, 2026
@buua436
buua436 requested a review from wangq8 August 12, 2026 12:11

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this PR — the approach of prioritizing exact entity-name matching before BM25 and limiting KNN fallback to a single candidate is well-reasoned and addresses real quality issues in structure graph keyword search.

A few observations:

1. Ancestor traversal now one-by-one per casing variant
The old code batched ancestor lookups with to_entity_kwd=sorted(ancestor_frontier). The new code iterates ancestor_frontier.values() (original-case names) and for each, tries both original-case and lower-case via _endpoint_terms in separate queries. This is N×2 queries per tree level instead of 1. For deeply nested structures with many matched leaves this could be noticeably slower. A comment acknowledging the tradeoff would be helpful for future readers. How deep do real-world trees typically go?

2. tokenize_for_search import
The import from rag.advanced_rag.knowlege_compile._common import tokenize_for_search is fine — the function exists and returns a (coarse, fine) tuple. But the result is joined with a simple " ".join(dict.fromkeys(...)), which deduplicates by insertion order. If coarse and fine produce identical tokens this is a no-op, but worth confirming this is always the intended behavior.

3. exact_name empty-string guard
exact_name = str(keywords).strip().lower() — if keywords is None, str(None) gives "None" which would trigger a spurious exact-name search. Suggest str(keywords or "").strip().lower().

4. tree_entities only populated for tree/page_index
The tree_entities list is declared but only populated inside the if structure_kind in {"tree", "page_index", "pageindex"} block. For non-tree structures tree_entities remains [] and entities = list(matched_nodes) + tree_entities is just matched_nodes — correct, but the neighbor entity fetch also gained and structure_kind not in {"tree", ...} guard which avoids double-fetching. Looks right.

5. Tests
The unit tests are thorough and cover the key scenarios: tree path resolution, BM25 tokenization, and KNN limit. The monkeypatch approach is pragmatic given the deep dependency chain. Consider adding a test for the keywords=None edge case.

Overall the logic is solid and the tests give confidence. Minor nits above, none blocking.

@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)
api/apps/services/structure_graph_common.py (1)

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

Add diagnostic logging for the new retrieval flows.

The exact-name, BM25, and ancestor-expansion paths have no success-path diagnostics. Add debug logs that record the selected match mode, candidate count, ancestor count, relation count, and non-sensitive log_ctx. Do not log raw keywords.

As per coding guidelines, **/*.py files must add logging for new flows.

Also applies to: 531-590

🤖 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 `@api/apps/services/structure_graph_common.py` around lines 416 - 441, Add
debug logging to the retrieval flow around _valid_top_nodes and the subsequent
BM25 and ancestor-expansion handling, covering successful exact-name, BM25, and
ancestor paths. Each diagnostic should record the selected match mode, candidate
count, ancestor count, relation count, and non-sensitive log_ctx, while
excluding raw keywords. Reuse the module’s existing logging convention and emit
logs after the corresponding results are available.

Source: Coding guidelines

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

Inline comments:
In `@api/apps/services/structure_graph_common.py`:
- Around line 416-420: Update the comment near the exact normalized entity-name
lookup to remove the claim that KNN returns several related siblings, and
describe that it returns one approximate result instead. Preserve the
surrounding explanation of exact-name matching and BM25 behavior.

In `@test/unit_test/api/apps/services/test_structure_graph_common.py`:
- Around line 104-115: Update the graph_search stub and its test to record every
match_expressions invocation, then assert that an exact Leaf lookup completes
without any BM25 or KNN search requests. Preserve the existing leaf response and
normal condition-based lookup behavior, while making the test fail if fallback
search runs before or alongside the exact match.

---

Nitpick comments:
In `@api/apps/services/structure_graph_common.py`:
- Around line 416-441: Add debug logging to the retrieval flow around
_valid_top_nodes and the subsequent BM25 and ancestor-expansion handling,
covering successful exact-name, BM25, and ancestor paths. Each diagnostic should
record the selected match mode, candidate count, ancestor count, relation count,
and non-sensitive log_ctx, while excluding raw keywords. Reuse the module’s
existing logging convention and emit logs after the corresponding results are
available.
🪄 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: 0e135a0f-7679-4cae-804a-162517480eac

📥 Commits

Reviewing files that changed from the base of the PR and between 207e2ea and 517d196.

📒 Files selected for processing (2)
  • api/apps/services/structure_graph_common.py
  • test/unit_test/api/apps/services/test_structure_graph_common.py

@codecov

codecov Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (401f943) to head (39bee55).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #18181   +/-   ##
=======================================
  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.

@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)
api/apps/services/structure_graph_common.py (1)

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

Add logging for the new search and ancestor-expansion flows.

The exact-name, BM25, KNN, and tree traversal branches currently log only embedding failures. Add structured debug logs for the selected match mode, candidate count, ancestor count, and relation count. Do not log raw keywords.

As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 470-473, 531-590

🤖 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 `@api/apps/services/structure_graph_common.py` around lines 416 - 441, Add
structured debug logging around the search and ancestor-expansion flow,
including the selected match mode (exact-name, BM25, or KNN), candidate count,
ancestor count, and relation count; cover the tree traversal branches near the
related logic. Do not log raw keywords, and preserve the existing
embedding-failure logging while using the module’s established logger.

Source: Coding guidelines

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

Outside diff comments:
In `@api/apps/services/structure_graph_common.py`:
- Around line 416-441: Add structured debug logging around the search and
ancestor-expansion flow, including the selected match mode (exact-name, BM25, or
KNN), candidate count, ancestor count, and relation count; cover the tree
traversal branches near the related logic. Do not log raw keywords, and preserve
the existing embedding-failure logging while using the module’s established
logger.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 90803c02-d359-4620-8598-572d8137d5ed

📥 Commits

Reviewing files that changed from the base of the PR and between 517d196 and e075f9b.

📒 Files selected for processing (2)
  • api/apps/services/structure_graph_common.py
  • test/unit_test/api/apps/services/test_structure_graph_common.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/unit_test/api/apps/services/test_structure_graph_common.py

@wangq8
wangq8 merged commit c10371d into infiniflow:main Aug 13, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 🌈 python Pull requests that update Python code size:L This PR changes 100-499 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants