Repository navigation
fix: refine structure graph keyword search - #18181
Conversation
📝 WalkthroughWalkthroughThe 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. ChangesKeyword graph search
Estimated code review effort: 4 (Complex) | ~45 minutes Mergeability Score: 🔵 Low · up to 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
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
wangq8
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
api/apps/services/structure_graph_common.py (1)
416-441: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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,
**/*.pyfiles 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
📒 Files selected for processing (2)
api/apps/services/structure_graph_common.pytest/unit_test/api/apps/services/test_structure_graph_common.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 winAdd 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
📒 Files selected for processing (2)
api/apps/services/structure_graph_common.pytest/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
What problem does this PR solve?
Fixes structure graph keyword search accuracy and incomplete tree paths.
Type of change