Skip to content

Feat: Compilation benefit naive rag. - #17555

Merged
KevinHuSh merged 11 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search9
Jul 30, 2026
Merged

KevinHuSh merged 11 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search9

Conversation

@KevinHuSh

@KevinHuSh KevinHuSh commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Compilation benifit naive rag

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Jul 30, 2026
@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Dataset and document template scopes are resolved separately, wiki templates replace artifacts in compilation routing, graph exploration uses scoped KG traversal, and hybrid search can optionally expand results through compiled entities, relations, and synthesis pages.

Changes

Wiki template kind routing

Layer / File(s) Summary
Wiki template kind routing
api/db/init_data/..., api/apps/restful_apis/..., api/db/services/..., rag/...
Template initialization, validation, scope derivation, active-template loading, wiki generation, and structure graph selection now use wiki instead of artifacts.

Scoped Knowledge Graph Search

Layer / File(s) Summary
Dataset and document scope discovery
api/apps/services/dataset_api_service.py
Template metadata is paged by dataset and document scope, mapped to compilation kinds, and applied during keyword and normal graph construction.
Knowledge graph search controls
rag/advanced_rag/harness/tools/navigation.py
KG search gains scope, ordering, dense-retrieval controls, traversal tuning, and additional endpoint metadata.
Scoped graph traversal and evidence results
rag/advanced_rag/harness/tools/navigation.py
Traversal expands normalized endpoints and returns empty, direct-answer, or keyword-narrowed evidence results without hybrid-search fallback.

Compiled Search Expansion

Layer / File(s) Summary
Compiled product expansion
rag/advanced_rag/harness/tools/search.py, rag/advanced_rag/harness/orchestrator/direct.py
hybrid_search optionally expands retrieved chunks through compiled KG and synthesis-page rows, while direct_search enables the option.

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

Sequence Diagram(s)

sequenceDiagram
  participant direct_search
  participant hybrid_search
  participant compiled_KG
  participant doc_store
  direct_search->>hybrid_search: enable compiled expansion
  hybrid_search->>compiled_KG: search entities, relations, and synthesis pages
  compiled_KG-->>hybrid_search: return related chunk ids
  hybrid_search->>doc_store: load deduplicated chunks
  doc_store-->>hybrid_search: return expanded evidence
Loading

Possibly related PRs

Suggested labels: 💞 feature, 🌈 python, 🐖api

Poem

I’m a rabbit who follows each scope,
Through wiki trails where relations elope.
Chunks bloom from entities bright,
Empty paths fade into night.
Search hops onward by moonlight.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the PR but too vague to describe the main change clearly. Use a concise, specific title that names the primary change, such as the wiki/compiled-RAG update.
Description check ❓ Inconclusive The description only repeats a vague phrase and lacks the required summary context and purpose. Expand the Summary with the problem, background, and what this PR changes in the compilation/RAG flow.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

@KevinHuSh KevinHuSh changed the title Feat: Feat: Compilation benifit naive rag. Jul 30, 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: 1

🤖 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/knowlege_compile/structure.py`:
- Line 2628: Remove the placeholder `#####` inline comment from the
`bad_edge_set = set(bad_edges)` assignment, leaving the assignment unchanged.
🪄 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: 321778e3-4129-4168-8b86-7f9426d67d8e

📥 Commits

Reviewing files that changed from the base of the PR and between cb908d1 and 4c6fe6d.

📒 Files selected for processing (1)
  • rag/advanced_rag/knowlege_compile/structure.py

@JinHai-CN JinHai-CN changed the title Feat: Compilation benifit naive rag. Feat: Compilation benefit naive rag. Jul 30, 2026
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jul 30, 2026
@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 30, 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

🧹 Nitpick comments (3)
api/apps/services/dataset_api_service.py (1)

1844-1900: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Two full paginated scans where one could suffice.

_discover_scope_templates is called twice sequentially (once per scope_kwd), each independently paging through all entity/relation metadata rows for the dataset. Since the two calls are independent, either merge them into a single query (add scope_kwd to meta_fields and query scope_kwd: ["dataset", "doc"] once) or at least run the two calls concurrently with asyncio.gather to cut round-trip latency in half.

⚡ Option: parallelize the two independent discovery calls
-    dataset_template_ids, has_templateless, dataset_pages = await _discover_scope_templates("dataset")
+    (dataset_template_ids, has_templateless, dataset_pages), (doc_template_ids, doc_has_templateless, doc_pages) = await asyncio.gather(
+        _discover_scope_templates("dataset"), _discover_scope_templates("doc")
+    )
     kind_template_ids: list[str] = list(dataset_template_ids)
     template_scope_by_id: dict[str, str] = {tid: "dataset" for tid in dataset_template_ids}
-
-    doc_template_ids, _, doc_pages = await _discover_scope_templates("doc")
     for tid in doc_template_ids:
🤖 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/dataset_api_service.py` around lines 1844 - 1900,
Parallelize the independent dataset and doc discovery scans by starting both
_discover_scope_templates calls together with asyncio.gather, then unpack their
results while preserving the existing template ID deduplication and scope
mapping logic. Ensure the asyncio dependency is available in the module and
retain each scan’s existing pagination and error behavior.
rag/advanced_rag/harness/tools/navigation.py (2)

812-813: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Sequential from/to relation searches could run concurrently.

The two _kg_search calls for from_entity_kwd and to_entity_kwd are independent I/O calls, awaited sequentially each hop. Running them with asyncio.gather halves this part of the per-hop latency.

⚡ Parallelize the two relation lookups
-            rel_rows: dict = {}
-            rel_rows.update(await _kg_search(tools, kb_id, tenant_id, doc_ids, "relation", top_n=_KG_REL_LIMIT, scope_kwd=scope_kwd, extra={"from_entity_kwd": terms}))
-            rel_rows.update(await _kg_search(tools, kb_id, tenant_id, doc_ids, "relation", top_n=_KG_REL_LIMIT, scope_kwd=scope_kwd, extra={"to_entity_kwd": terms}))
+            from_rows, to_rows = await asyncio.gather(
+                _kg_search(tools, kb_id, tenant_id, doc_ids, "relation", top_n=_KG_REL_LIMIT, scope_kwd=scope_kwd, extra={"from_entity_kwd": terms}),
+                _kg_search(tools, kb_id, tenant_id, doc_ids, "relation", top_n=_KG_REL_LIMIT, scope_kwd=scope_kwd, extra={"to_entity_kwd": terms}),
+            )
+            rel_rows: dict = {**from_rows, **to_rows}
🤖 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 812 - 813, Update
the relation-search section around the two _kg_search calls to start both
from_entity_kwd and to_entity_kwd lookups concurrently with asyncio.gather, then
merge each completed result into rel_rows while preserving both searches’
existing parameters and behavior.

811-815: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Relations accumulate duplicates across hops.

rel_rows is deduped by row id within a single hop, but relations.extend(hop_relations) has no cross-hop dedup. If a relation touches an entity that only becomes part of the frontier in a later hop, the same underlying relation row can be re-fetched and appended again, inflating relations passed to _ask_structure and duplicating evidence work downstream.

♻️ Track seen relation ids across hops
     entities: list[dict] = []
     relations: list[dict] = []
+    seen_relation_ids: set[str] = set()
     ent_names: set[str] = set()
             rel_rows: dict = {}
             rel_rows.update(await _kg_search(tools, kb_id, tenant_id, doc_ids, "relation", top_n=_KG_REL_LIMIT, scope_kwd=scope_kwd, extra={"from_entity_kwd": terms}))
             rel_rows.update(await _kg_search(tools, kb_id, tenant_id, doc_ids, "relation", top_n=_KG_REL_LIMIT, scope_kwd=scope_kwd, extra={"to_entity_kwd": terms}))
-            hop_relations = [r for r in (_kg_parse_relation(x) for x in rel_rows.values()) if r]
+            new_ids = [rid for rid in rel_rows if rid not in seen_relation_ids]
+            seen_relation_ids.update(new_ids)
+            hop_relations = [r for r in (_kg_parse_relation(rel_rows[rid]) for rid in new_ids) if r]
             relations.extend(hop_relations)
🤖 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 811 - 815, Track
relation row identifiers across hops in the navigation flow surrounding
_kg_parse_relation and relations.extend, and only append relations whose
underlying IDs have not already been seen. Preserve fetching and within-hop
deduplication, while preventing the same relation from being added to relations
more than once across successive hops before _ask_structure.
🤖 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/dataset_api_service.py`:
- Around line 1945-1960: Fix _scope_for_template by using the locally assigned
stamped value when normalizing compilation_template_kind_kwd lists, rather than
referencing the undefined stamped_kind closure variable. Preserve the existing
first-element and whitespace-stripping behavior used by the corresponding
keyword and legacy-row handling.
- Around line 1892-1900: Preserve the templateless result from
_discover_scope_templates("doc") and combine it with the dataset-scope
has_templateless flag before the legacy discovery checks. Use the combined flag
for both the not kind_template_ids and not has_templateless guard and the final
has_templateless fallback, while leaving template ID and scope mapping behavior
unchanged.

---

Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1844-1900: Parallelize the independent dataset and doc discovery
scans by starting both _discover_scope_templates calls together with
asyncio.gather, then unpack their results while preserving the existing template
ID deduplication and scope mapping logic. Ensure the asyncio dependency is
available in the module and retain each scan’s existing pagination and error
behavior.

In `@rag/advanced_rag/harness/tools/navigation.py`:
- Around line 812-813: Update the relation-search section around the two
_kg_search calls to start both from_entity_kwd and to_entity_kwd lookups
concurrently with asyncio.gather, then merge each completed result into rel_rows
while preserving both searches’ existing parameters and behavior.
- Around line 811-815: Track relation row identifiers across hops in the
navigation flow surrounding _kg_parse_relation and relations.extend, and only
append relations whose underlying IDs have not already been seen. Preserve
fetching and within-hop deduplication, while preventing the same relation from
being added to relations more than once across successive hops before
_ask_structure.
🪄 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: 87c43637-70c4-45b4-99c2-4f25aa62e978

📥 Commits

Reviewing files that changed from the base of the PR and between 4c6fe6d and df263c6.

📒 Files selected for processing (2)
  • api/apps/services/dataset_api_service.py
  • rag/advanced_rag/harness/tools/navigation.py

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

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

352-355: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Hoist these imports to module level.

settings is already imported at module scope (used at Line 205), and MatchTextExpr/OrderByExpr/thread_pool_exec/search are re-imported inside three separate helpers. Unless there is a circular-import reason, move them to the top of the file.

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

In `@rag/advanced_rag/harness/tools/search.py` around lines 352 - 355, Move the
imports for MatchTextExpr, OrderByExpr, thread_pool_exec, and search from the
helper functions to module scope alongside the existing settings import, then
remove the duplicate local imports while preserving each helper’s behavior.
rag/advanced_rag/harness/orchestrator/direct.py (1)

14-16: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

use_compiled=True is hard-coded, making the expansion fan-out unconditional here.

The direct path is the only caller enabling compiled expansion, and it does so with no way to turn it off if the extra doc-store round trips (see rag/advanced_rag/harness/tools/search.py Lines 300-315) hurt latency. Consider gating it on a tools/state setting so it can be disabled without a code change.

🤖 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/direct.py` around lines 14 - 16, Update
the direct search flow around hybrid_search to derive use_compiled from an
existing tools or state configuration setting instead of hard-coding it to true.
Preserve the current enabled behavior by default, while allowing callers to
disable compiled expansion without modifying code.
🤖 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/tools/search.py`:
- Around line 300-315: Make the compiled expansion in the scope loop concurrent
by scheduling each kb_id/tenant_id/doc_ids and compile_kwd combination with
asyncio.gather, while bounding total work to avoid unbounded fan-out (for
example, cap scopes or skip page_index/tree once the KG pass reaches
max_chunks). Preserve chunk aggregation in kbinfos["chunks"] and the existing
strategy labels/logging, and ensure failures are handled consistently with the
current request path.
- Around line 549-562: Make the chunk selection in the load-and-return loop
deterministic by ordering each document’s cids before applying the max_chunks
limit. Update the list(cids)[:limit] expression in the flow around
_load_chunks_for_doc to sort the IDs (or use a preserved source order), while
keeping the existing deduplication and result limits unchanged.
- Around line 223-225: Update the compiled expansion flow and
_expand_with_compiled signature to accept doc_scope, remove the unused keywords
parameter, and pass doc_scope into _compiled_scopes(tools, doc_scope). Update
the call site guarded by use_compiled and kbinfos.get("chunks") to forward the
caller’s document scope, preserving scoped retrieval and cache behavior.
- Around line 410-440: Update _load_chunks_for_doc to reflect that get_fields
returns a mapping: iterate over its values and attach each mapping key as the
chunk_id, while including the required id field in the search projection.
Preserve the empty-result behavior, and add contextual exception logging
consistent with sibling helpers before returning an empty list.

---

Nitpick comments:
In `@rag/advanced_rag/harness/orchestrator/direct.py`:
- Around line 14-16: Update the direct search flow around hybrid_search to
derive use_compiled from an existing tools or state configuration setting
instead of hard-coding it to true. Preserve the current enabled behavior by
default, while allowing callers to disable compiled expansion without modifying
code.

In `@rag/advanced_rag/harness/tools/search.py`:
- Around line 352-355: Move the imports for MatchTextExpr, OrderByExpr,
thread_pool_exec, and search from the helper functions to module scope alongside
the existing settings import, then remove the duplicate local imports while
preserving each helper’s behavior.
🪄 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: 87c43637-70c4-45b4-99c2-4f25aa62e978

📥 Commits

Reviewing files that changed from the base of the PR and between df263c6 and 1bdad93.

📒 Files selected for processing (2)
  • rag/advanced_rag/harness/orchestrator/direct.py
  • rag/advanced_rag/harness/tools/search.py

Comment on lines +300 to +315
for kb_id, tenant_id, doc_ids in scopes:
for compile_kwd in ("page_index", "tree", None): # None = all compiled (KG)
label = compile_kwd or "kg"
chunks = await _expand_compiled_strategy(
tools,
kb_id,
tenant_id,
doc_ids,
query,
seen_ids,
compile_kwd=compile_kwd,
max_chunks=5,
)
if chunks:
kbinfos.setdefault("chunks", []).extend(chunks)
_LOG.debug("[Compiled expand] %s: +%d chunks", label, len(chunks))

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

Serial fan-out on the request path: 3 strategies × every bound KB, each doing 4+ doc-store round trips.

For K bound KBs this issues ~12K sequential searches plus per-doc chunk loads before returning, and each thread_pool_exec call spins up a fresh ThreadPoolExecutor. Consider running the per-scope/per-strategy expansions concurrently with asyncio.gather and bounding total work (e.g. cap scopes, or skip page_index/tree when the KG pass already met max_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/search.py` around lines 300 - 315, Make the
compiled expansion in the scope loop concurrent by scheduling each
kb_id/tenant_id/doc_ids and compile_kwd combination with asyncio.gather, while
bounding total work to avoid unbounded fan-out (for example, cap scopes or skip
page_index/tree once the KG pass reaches max_chunks). Preserve chunk aggregation
in kbinfos["chunks"] and the existing strategy labels/logging, and ensure
failures are handled consistently with the current request path.

Comment on lines +549 to +562
# -- 5. Load and return --
new_chunks: list[dict] = []
for doc_id, cids in by_doc.items():
if len(new_chunks) >= max_chunks:
break
limit = max_chunks - len(new_chunks)
chunks = await _load_chunks_for_doc(tools, doc_id, list(cids)[:limit])
for c in chunks:
cid = c.get("chunk_id") or c.get("id")
if cid and cid not in seen_ids:
seen_ids.add(cid)
new_chunks.append(c)

return new_chunks

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

max_chunks truncation over a set is nondeterministic.

list(cids)[:limit] picks an arbitrary subset per run, so identical queries return different expanded passages (and the result is cached). Sort the ids (or preserve source order) before slicing.

♻️ Proposed change
-        chunks = await _load_chunks_for_doc(tools, doc_id, list(cids)[:limit])
+        chunks = await _load_chunks_for_doc(tools, doc_id, sorted(cids)[:limit])
📝 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
# -- 5. Load and return --
new_chunks: list[dict] = []
for doc_id, cids in by_doc.items():
if len(new_chunks) >= max_chunks:
break
limit = max_chunks - len(new_chunks)
chunks = await _load_chunks_for_doc(tools, doc_id, list(cids)[:limit])
for c in chunks:
cid = c.get("chunk_id") or c.get("id")
if cid and cid not in seen_ids:
seen_ids.add(cid)
new_chunks.append(c)
return new_chunks
# -- 5. Load and return --
new_chunks: list[dict] = []
for doc_id, cids in by_doc.items():
if len(new_chunks) >= max_chunks:
break
limit = max_chunks - len(new_chunks)
chunks = await _load_chunks_for_doc(tools, doc_id, sorted(cids)[:limit])
for c in chunks:
cid = c.get("chunk_id") or c.get("id")
if cid and cid not in seen_ids:
seen_ids.add(cid)
new_chunks.append(c)
return new_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/search.py` around lines 549 - 562, Make the
chunk selection in the load-and-return loop deterministic by ordering each
document’s cids before applying the max_chunks limit. Update the
list(cids)[:limit] expression in the flow around _load_chunks_for_doc to sort
the IDs (or use a preserved source order), while keeping the existing
deduplication and result limits unchanged.

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

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

626-631: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the unreachable except around order_by.desc.

OrderByExpr.desc only appends a tuple to a list, so it cannot raise; the fallback re-assignment is dead defensive code.

♻️ Proposed simplification
     order_by = OrderByExpr()
     if order_desc:
-        try:
-            order_by.desc(order_desc)
-        except Exception:
-            order_by = OrderByExpr()
+        order_by.desc(order_desc)
🤖 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 626 - 631, Remove
the try/except wrapper around OrderByExpr.desc in the order_by construction
path, and call order_by.desc(order_desc) directly when order_desc is set.
Preserve the existing OrderByExpr initialization and conditional behavior
without the dead fallback reassignment.
🤖 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/tools/navigation.py`:
- Around line 579-592: Update the return annotation of _kg_search to dict[str,
dict] to match get_fields and its {} failure result. Preserve the existing
dictionary return behavior and callers’ .values() consumption, including the
corresponding annotation at the additional referenced declaration.
- Around line 817-830: Compiled KG traversal loses matches by querying only one
case variant of entity names. In rag/advanced_rag/harness/tools/navigation.py
lines 817-830, update the neighboring-entity lookup to pass
_endpoint_terms(neigh_names) as name_kwd instead of the lowercased set. In
rag/advanced_rag/harness/tools/search.py lines 491-511, build seed_list from
both original and lowercased seed names via _endpoint_terms before applying
from_entity_kwd/to_entity_kwd filters, and make the endpoint comparisons at
lines 517-522 case-insensitive.

In `@rag/advanced_rag/harness/tools/search.py`:
- Around line 335-408: Consolidate the duplicated compiled-KG access layer: in
rag/advanced_rag/harness/tools/search.py lines 335-408, remove
_search_compiled_rows and use navigation._kg_search with the required extra
fields and scope_kwd; in rag/advanced_rag/harness/tools/search.py lines 321-332,
remove _compiled_scopes and import/use navigation._kg_scopes; in
rag/advanced_rag/harness/tools/navigation.py lines 579-592, expose or promote
_kg_search and _kg_scopes as the shared implementation so both callers follow
one path.
- Around line 479-488: Update the payload parsing exception handler in the
seed-processing loop to log the parse failure, including the exception and
enough context to identify the affected seed row, before continuing. Reuse the
module’s existing logger and preserve the current skip behavior for malformed
content and the subsequent empty-seed return.
- Around line 357-363: Update the condition construction in
_search_compiled_rows so compile_kwd is passed as a list-based filter, matching
the indexed compiled-row filters used elsewhere; preserve the existing behavior
when compile_kwd is absent.
- Around line 286-294: Update _expand_with_compiled so newly appended
compiled-expansion chunks undergo the same keyword narrowing as graph_explore
evidence before they are cached or returned. Apply _narrow_by_keywords only to
the chunks added during this function, preserving existing chunks and the
current expansion flow.

---

Nitpick comments:
In `@rag/advanced_rag/harness/tools/navigation.py`:
- Around line 626-631: Remove the try/except wrapper around OrderByExpr.desc in
the order_by construction path, and call order_by.desc(order_desc) directly when
order_desc is set. Preserve the existing OrderByExpr initialization and
conditional behavior without the dead fallback reassignment.
🪄 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: 854a7628-cc35-498c-a059-a25861633f15

📥 Commits

Reviewing files that changed from the base of the PR and between cb908d1 and 1bdad93.

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

Comment on lines +579 to +592
async def _kg_search(
tools,
kb_id: str,
tenant_id: str,
doc_ids,
kind: str,
text: str = "",
top_n: int = 8,
extra: dict | None = None,
scope_kwd: str | None = None,
order_desc: str | None = None,
pool: int | None = None,
similarity: float = 0.6,
) -> list[dict]:

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

Return annotation contradicts the actual return value.

get_fields is declared dict[str, dict] (common/doc_store/doc_store_base.py:257), the failure path returns {}, and every caller consumes .values(). The list[dict] annotation is wrong.

🔧 Proposed fix
-    similarity: float = 0.6,
-) -> list[dict]:
+    similarity: float = 0.6,
+) -> dict[str, dict]:

Also applies to: 646-650

🤖 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 579 - 592, Update
the return annotation of _kg_search to dict[str, dict] to match get_fields and
its {} failure result. Preserve the existing dictionary return behavior and
callers’ .values() consumption, including the corresponding annotation at the
additional referenced declaration.

Comment on lines +286 to +294
async def _expand_with_compiled(tools, query: str, keywords: str, kbinfos: dict) -> None:
"""Zero-LLM compiled-product expansion: page_index → tree → KG.

For each bound KB, searches compiled entity rows matching the query,
hops 1-hop via relations to find neighbour entities, then appends
their source passages to ``kbinfos["chunks"]``.
"""
before = len(kbinfos.get("chunks", []))
seen_ids = {c.get("chunk_id") or c.get("id") for c in kbinfos.get("chunks", [])}

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

Expanded chunks bypass keyword narrowing.

_expand_with_compiled runs after _narrow_by_keywords (Line 221), so compiled-expansion chunks are appended un-narrowed and get cached that way — the same result set mixes narrowed and full-content passages. graph_explore narrows its evidence chunks before returning; do the same here.

🐛 Proposed fix
             if chunks:
+                if keywords:
+                    chunks = _narrow_by_keywords(chunks, keywords)
                 kbinfos.setdefault("chunks", []).extend(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/search.py` around lines 286 - 294, Update
_expand_with_compiled so newly appended compiled-expansion chunks undergo the
same keyword narrowing as graph_explore evidence before they are cached or
returned. Apply _narrow_by_keywords only to the chunks added during this
function, preserving existing chunks and the current expansion flow.

Comment on lines +357 to +363
condition: dict = {"knowledge_graph_kwd": [kind]}
if compile_kwd:
condition["compile_kwd"] = compile_kwd
if doc_ids:
condition["doc_id"] = list(doc_ids)
if extra:
condition.update(extra)

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n --type=py -C2 '\b(compile_kwd|scope_kwd)\b' -g '!**/test*/**'

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files matching search.py:"
fd -a 'search\.py$' . | sed 's#^\./##' | head -50

echo
echo "Occurrences around navigation/search mentions (narrow):"
rg -n -C3 'compile_kwd|scope_kwd|knowledge_graph_kwd|from_entity_kwd|name_kwd|doc_id\]' . 2>/dev/null | head -300

echo
echo "Candidate files:"
git ls-files '*.py' | rg '(^|/)(search|navigation)\.py$|advanced_rag|harness' | head -200

Repository: infiniflow/ragflow

Length of output: 27276


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "search.py 320-415"
sed -n '320,415p' rag/advanced_rag/harness/tools/search.py | cat -n -v | awk '{printf "%6d  %s\n", NR+319, $0}'

echo
echo "navigation.py occurrences outline around _kg_scopes/_kg_search/_compiled_scopes/_search_compiled_rows"
sed -n '520,700p' rag/advanced_rag/harness/tools/navigation.py | cat -n -v | awk '{printf "%6d  %s\n", NR+519, $0}'

echo
echo "compile_kwd exact occurrences excluding tests:"
rg -n -C2 '^\s*compile_kwd|compile_kwd(' rag/advanced_rag/harness/tools/search.py rag/advanced_rag/harness/tools/navigation.py api/apps/restful_apis/chunk_api.py internal/ingestion/task -g '!**/test*/**'

echo
echo "docStoreConn keyword handling:"
sed -n '40,90p' rag/utils/infinity_conn.py
rg -n -C3 'endswith\("%_kwd"\)|\%_kwd|multi-valued|keyword lists' rag/utils -g '*.py'

Repository: infiniflow/ragflow

Length of output: 14979


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "compile_kwd exact occurrences excluding tests:"
rg -n -C2 '^\s*compile_kwd[:\[]|compile_kwd[:\[])|compile_kwd' rag/advanced_rag/harness/tools/search.py rag/advanced_rag/harness/tools/navigation.py api/apps/restful_apis/chunk_api.py internal/ingestion/task -g '!**/test*/**'

echo
echo "scope_kwd exact occurrences excluding tests:"
rg -n -C2 '^\s*scope_kwd[:\[]|scope_kwd[:\[])|scope_kwd' rag api internal -g '!**/test*/**'

echo
echo "docStoreConn search/filter helpers relevant to keyword lists:"
rg -n -C4 '_keyword|keyword|_kwds|_kwd|match|filter|docStoreConn\.search' rag/utils rag/nlp common -g '*.py' | head -400

Repository: infiniflow/ragflow

Length of output: 366


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "compile_kwd occurrences excluding tests:"
rg -n -C2 '\bcompile_kwd\b' rag/advanced_rag/harness/tools/search.py rag/advanced_rag/harness/tools/navigation.py api/apps/restful_apis/chunk_api.py internal/ingestion/task -g '!**/test*/**'

echo
echo "scope_kwd occurrences excluding tests:"
rg -n -C2 '\bscope_kwd\b' rag api internal -g '!**/test*/**'

echo
echo "docStoreConn search/filter helpers relevant to keyword lists:"
rg -n -C3 '_word|keyword|_kwds|_kwd|docStoreConn\.search|search_.*keyword|keyword_search|MatchKeyword' rag/utils rag/nlp common -g '*.py' | head -600

Repository: infiniflow/ragflow

Length of output: 50374


Keep the _search_compiled_rows condition consistent.

compile_kwd is an indexed discriminator on compiled rows, but using a scalar here is at odds with the list-based filters used for the same rows throughout navigation.py, chunk_api.py, and the dataset merge paths. Pass it as a list so the query stays consistent with the compiled graph/index usage.

🔧 Proposed fix
     if compile_kwd:
-        condition["compile_kwd"] = compile_kwd
+        condition["compile_kwd"] = [compile_kwd]
📝 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
condition: dict = {"knowledge_graph_kwd": [kind]}
if compile_kwd:
condition["compile_kwd"] = compile_kwd
if doc_ids:
condition["doc_id"] = list(doc_ids)
if extra:
condition.update(extra)
condition: dict = {"knowledge_graph_kwd": [kind]}
if compile_kwd:
condition["compile_kwd"] = [compile_kwd]
if doc_ids:
condition["doc_id"] = list(doc_ids)
if extra:
condition.update(extra)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/search.py` around lines 357 - 363, Update the
condition construction in _search_compiled_rows so compile_kwd is passed as a
list-based filter, matching the indexed compiled-row filters used elsewhere;
preserve the existing behavior when compile_kwd is absent.

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

182-200: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Partition the retrieval cache by use_compiled.

Line 196 omits the new flag, so a cached non-compiled result suppresses expansion for a later compiled request; the reverse leaks expanded chunks into a non-compiled request.

Proposed fix
-def _search_cache_key(effective_query: str, target_ids, top_n: int, doc_scope) -> tuple:
+def _search_cache_key(
+    effective_query: str, target_ids, top_n: int, doc_scope, use_compiled: bool
+) -> tuple:
     return (
         " ".join((effective_query or "").split()).lower(),
         tuple(sorted(target_ids or ())),
         int(top_n),
         tuple(sorted(doc_scope or ())),
+        bool(use_compiled),
     )

-    cache_key = _search_cache_key(effective_query, target_ids, top_n, doc_scope)
+    cache_key = _search_cache_key(
+        effective_query, target_ids, top_n, doc_scope, use_compiled
+    )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/search.py` around lines 182 - 200, Update the
_search_cache_key call in hybrid_search to include use_compiled as part of the
cache key. Ensure compiled and non-compiled requests use separate cache entries
while preserving the existing query, scope, and result reuse behavior.
api/apps/restful_apis/utils/compilation_template_validation.py (1)

59-64: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Normalize the template kind before selecting wiki validation.

validate_template_payload() selects claim/concept field validation with exact string comparisons, but downstream runtime paths route Wiki/WIKI/wiki-wiki as wiki templates via kind.strip().lower().replace("-", "_"). Normalize req.get("kind") and any config.get("kind") value before comparing to "wiki" to prevent canonical/non-canonical kind mismatches.

🤖 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/restful_apis/utils/compilation_template_validation.py` around lines
59 - 64, Update validate_template_payload() to normalize both req.get("kind")
and config.get("kind") using the same strip/lowercase/hyphen-to-underscore
canonicalization used by downstream routing, then compare the normalized values
to "wiki" for claim validation. Preserve the existing field checks and error
messages.
🧹 Nitpick comments (2)
api/apps/services/dataset_api_service.py (1)

1844-1900: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy lift

Add regression tests for dataset/document scope isolation.

This change introduces multiple scope-dependent paths—discovery, keyword mode, empty-result fallback, and legacy-row kind filtering. Add focused tests proving that dataset templates do not consume document rows, document templates remain discoverable, and unrelated legacy kinds are excluded.

Also applies to: 1947-1960, 1979-1990, 2023-2026

🤖 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/dataset_api_service.py` around lines 1844 - 1900, Add
focused regression tests for the scope-dependent dataset structure flow around
_discover_scope_templates and its related keyword-mode, empty-result fallback,
and legacy-row kind-filtering paths. Verify dataset template discovery ignores
document rows, document templates remain discoverable, empty results do not
cross scopes, and unrelated legacy template kinds are excluded; cover the
additional referenced branches as well.

Source: Coding guidelines

api/db/services/compilation_template_group_service.py (1)

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

Remove stale artifact terminology after the wiki routing change.

The implementation now consistently routes wiki, but nearby names, docstrings, and comments still describe artifacts. Update the owning documentation and local variable names so future maintenance does not infer the wrong behavior.

  • api/db/services/compilation_template_group_service.py#L42-L45: rename artifact_count to wiki_count and update _derive_scope() documentation.
  • rag/advanced_rag/knowlege_compile/runner.py#L138: update load_active_templates() documentation from artifacts to wiki.
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py#L1031: update run_wiki() documentation/comments from artifact compilation to wiki compilation.
  • api/apps/restful_apis/chunk_api.py#L640-L641: update the document-graph filtering comment to say wiki templates.
🤖 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/db/services/compilation_template_group_service.py` around lines 42 - 45,
Replace artifact terminology with wiki terminology throughout the affected
documentation and local names: in
api/db/services/compilation_template_group_service.py lines 42-45, rename
artifact_count to wiki_count and update _derive_scope() documentation; update
load_active_templates() documentation in
rag/advanced_rag/knowlege_compile/runner.py line 138, run_wiki()
documentation/comments in
rag/svr/task_executor_refactor/dataset_wiki_generator.py line 1031, and the
document-graph filtering comment in api/apps/restful_apis/chunk_api.py lines
640-641 to refer to wiki templates or wiki compilation.

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/restful_apis/utils/compilation_template_validation.py`:
- Around line 59-64: Update validate_template_payload() to normalize both
req.get("kind") and config.get("kind") using the same
strip/lowercase/hyphen-to-underscore canonicalization used by downstream
routing, then compare the normalized values to "wiki" for claim validation.
Preserve the existing field checks and error messages.

In `@rag/advanced_rag/harness/tools/search.py`:
- Around line 182-200: Update the _search_cache_key call in hybrid_search to
include use_compiled as part of the cache key. Ensure compiled and non-compiled
requests use separate cache entries while preserving the existing query, scope,
and result reuse behavior.

---

Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1844-1900: Add focused regression tests for the scope-dependent
dataset structure flow around _discover_scope_templates and its related
keyword-mode, empty-result fallback, and legacy-row kind-filtering paths. Verify
dataset template discovery ignores document rows, document templates remain
discoverable, empty results do not cross scopes, and unrelated legacy template
kinds are excluded; cover the additional referenced branches as well.

In `@api/db/services/compilation_template_group_service.py`:
- Around line 42-45: Replace artifact terminology with wiki terminology
throughout the affected documentation and local names: in
api/db/services/compilation_template_group_service.py lines 42-45, rename
artifact_count to wiki_count and update _derive_scope() documentation; update
load_active_templates() documentation in
rag/advanced_rag/knowlege_compile/runner.py line 138, run_wiki()
documentation/comments in
rag/svr/task_executor_refactor/dataset_wiki_generator.py line 1031, and the
document-graph filtering comment in api/apps/restful_apis/chunk_api.py lines
640-641 to refer to wiki templates or wiki compilation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9fd13dca-2de1-4507-9871-b893a1edd9ee

📥 Commits

Reviewing files that changed from the base of the PR and between 1bdad93 and 479055b.

📒 Files selected for processing (9)
  • api/apps/restful_apis/chunk_api.py
  • api/apps/restful_apis/utils/compilation_template_validation.py
  • api/apps/services/dataset_api_service.py
  • api/db/init_data/compilation_templates/wiki.yaml
  • api/db/services/compilation_template_group_service.py
  • rag/advanced_rag/harness/orchestrator/agentic.py
  • rag/advanced_rag/harness/tools/search.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py

@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 (4)
api/apps/services/dataset_api_service.py (3)

1854-1870: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Propagate discovery failures instead of returning an empty success.

A datastore exception returns ([], False, pages), so get_dataset_structure continues as though no matching templates exist and can return (True, empty). This silently turns an infrastructure failure into missing graph data; distinguish failure from “no rows” and propagate an error or abort the response.

🤖 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/dataset_api_service.py` around lines 1854 - 1870, Update
the exception handling around the datastore search in get_dataset_structure so
discovery failures are propagated or abort the response instead of returning
([], False, pages). Preserve the existing empty-result behavior only when the
search succeeds and returns no rows, and keep the logging context for the failed
discovery.

1979-1994: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Retry document scope after graph-specific filtering.

The fallback only runs when both raw lists are empty. For graph-like kinds, a dataset bucket containing entities without relations—or relations without usable entities—can be filtered to empty at Lines 1991-1994, but the document-scoped bucket is never attempted. Apply the kind filter before the emptiness check and repeat it after the document fallback.

🤖 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/dataset_api_service.py` around lines 1979 - 1994, The
get_dataset_structure bucket-processing flow should apply the graph-specific
filter before deciding whether the dataset-scoped result is empty, then retry
the document-scoped build when filtering leaves no usable entities. After the
fallback in build_bucket, apply filter_entities_with_relations again and
preserve the final skip when the filtered result remains empty.

2023-2026: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Remove the dataset_graph blob fallback from this PR.

The /dataset/{id}/artifacts_structure route now documents explicit kinds, while this code still expands content_json.kwds/knowledge_graph_kwd="dataset_graph" as a legacy path with no timestamped migration context. If dataset_graph is only old data, delete this compatibility branch and backfill/evict via migration; otherwise expose and version the contract explicitly.

🤖 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/dataset_api_service.py` around lines 2023 - 2026, Remove
the legacy dataset_graph compatibility branch from the artifacts-structure
resolution flow around _resolve_dataset_structure_kind, including expansion from
content_json.kwds or knowledge_graph_kwd. Require the documented explicit
dataset structure kinds instead, and handle existing dataset_graph records
through migration backfill or eviction rather than runtime fallback.

Source: Coding guidelines

rag/advanced_rag/harness/tools/search.py (1)

606-619: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Entity-graph-expanded chunks never get a similarity score, so they always sink in the final blend.

new_chunks returned here (and consumed via _expand_with_compiled, Line 361) never set similarity. The top-level sort chunks.sort(key=lambda c: c.get("similarity", 0.0), reverse=True) (Line 362) therefore always ranks these chunks at 0.0, below virtually every regular hybrid-search result, contradicting the stated intent to "blend by similarity with regular ones." Compare with _expand_wiki_page_strategy, which explicitly assigns similarity=0.9 (Line 745) for the same purpose.

♻️ Proposed fix
             if cid and cid not in seen_ids:
                 seen_ids.add(cid)
+                c.setdefault("similarity", 0.75)
                 new_chunks.append(c)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/search.py` around lines 606 - 619, Assign a
meaningful similarity score to each entity-graph-expanded chunk in the
load-and-return logic that builds new_chunks, before appending it. Preserve
existing deduplication and max_chunks behavior, and use the same score
convention as _expand_wiki_page_strategy so _expand_with_compiled’s final
similarity sort can blend these chunks with regular results.
♻️ Duplicate comments (1)
rag/advanced_rag/harness/tools/search.py (1)

394-398: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

compile_kwd/compilation_template_kind_kwd still filtered as scalars, and the new template_kind field repeats the pattern.

_search_compiled_rows (Line 396) keeps condition["compile_kwd"] = compile_kwd as a scalar (flagged previously, still unresolved), and the new condition["compilation_template_kind_kwd"] = template_kind (Line 398) has the identical issue. _search_synthesis_pages (Line 644) does the same with compile_kwd. Elsewhere in this file _kwd fields are filtered as lists (condition["doc_id"] = list(doc_ids), {"knowledge_graph_kwd": [kind]}), so this is inconsistent with how the doc store expects multi-valued keyword filters here. Since compilation_template_kind_kwd is new and gates the entire template-kind-scoped 1-hop expansion added in this PR (knowledge_graph/mind_map/timeline/page_index), a mismatch here would silently return zero rows for all of it.

🐛 Proposed fix
     condition: dict = {"knowledge_graph_kwd": [kind]}
     if compile_kwd:
-        condition["compile_kwd"] = compile_kwd
+        condition["compile_kwd"] = [compile_kwd]
     if template_kind:
-        condition["compilation_template_kind_kwd"] = template_kind
+        condition["compilation_template_kind_kwd"] = [template_kind]
-    condition: dict = {"compile_kwd": compile_kwd, "available_int": 1}
+    condition: dict = {"compile_kwd": [compile_kwd], "available_int": 1}

Also applies to: 644-644

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

In `@rag/advanced_rag/harness/tools/search.py` around lines 394 - 398, Update the
keyword-filter construction in _search_compiled_rows and _search_synthesis_pages
so compile_kwd is passed as a list, and wrap template_kind in a list when
assigning compilation_template_kind_kwd. Preserve the existing
knowledge_graph_kwd list behavior and ensure template-kind-scoped searches
continue matching rows.
🧹 Nitpick comments (1)
rag/advanced_rag/harness/tools/navigation.py (1)

807-815: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Deduplicate relations across hops.

rel_rows deduplicates the two endpoint searches within one hop, but relations.extend(hop_relations) re-adds the same edge when a later frontier reaches it, especially in cyclic graphs. Keep a cross-hop (from, to, type) set before appending to avoid prompt bloat and duplicated output.

🤖 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 807 - 815, Add a
cross-hop set of relation keys near the traversal state, using each parsed
relation’s from, to, and type values. In the loop around _kg_parse_relation and
relations.extend, append only relations whose (from, to, type) key has not
already been recorded, while preserving the existing within-hop rel_rows
deduplication and traversal behavior.
🤖 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/dataset_api_service.py`:
- Around line 1854-1870: Update the exception handling around the datastore
search in get_dataset_structure so discovery failures are propagated or abort
the response instead of returning ([], False, pages). Preserve the existing
empty-result behavior only when the search succeeds and returns no rows, and
keep the logging context for the failed discovery.
- Around line 1979-1994: The get_dataset_structure bucket-processing flow should
apply the graph-specific filter before deciding whether the dataset-scoped
result is empty, then retry the document-scoped build when filtering leaves no
usable entities. After the fallback in build_bucket, apply
filter_entities_with_relations again and preserve the final skip when the
filtered result remains empty.
- Around line 2023-2026: Remove the legacy dataset_graph compatibility branch
from the artifacts-structure resolution flow around
_resolve_dataset_structure_kind, including expansion from content_json.kwds or
knowledge_graph_kwd. Require the documented explicit dataset structure kinds
instead, and handle existing dataset_graph records through migration backfill or
eviction rather than runtime fallback.

In `@rag/advanced_rag/harness/tools/search.py`:
- Around line 606-619: Assign a meaningful similarity score to each
entity-graph-expanded chunk in the load-and-return logic that builds new_chunks,
before appending it. Preserve existing deduplication and max_chunks behavior,
and use the same score convention as _expand_wiki_page_strategy so
_expand_with_compiled’s final similarity sort can blend these chunks with
regular results.

---

Duplicate comments:
In `@rag/advanced_rag/harness/tools/search.py`:
- Around line 394-398: Update the keyword-filter construction in
_search_compiled_rows and _search_synthesis_pages so compile_kwd is passed as a
list, and wrap template_kind in a list when assigning
compilation_template_kind_kwd. Preserve the existing knowledge_graph_kwd list
behavior and ensure template-kind-scoped searches continue matching rows.

---

Nitpick comments:
In `@rag/advanced_rag/harness/tools/navigation.py`:
- Around line 807-815: Add a cross-hop set of relation keys near the traversal
state, using each parsed relation’s from, to, and type values. In the loop
around _kg_parse_relation and relations.extend, append only relations whose
(from, to, type) key has not already been recorded, while preserving the
existing within-hop rel_rows deduplication and traversal behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f2cdcfbe-4799-432f-a3f1-07cd824375fd

📥 Commits

Reviewing files that changed from the base of the PR and between 479055b and 90e5a19.

📒 Files selected for processing (3)
  • api/apps/services/dataset_api_service.py
  • rag/advanced_rag/harness/tools/navigation.py
  • rag/advanced_rag/harness/tools/search.py

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 30, 2026
@KevinHuSh KevinHuSh added the ci Continue Integration label Jul 30, 2026
@codecov

codecov Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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

@KevinHuSh
KevinHuSh merged commit 3f8a3df into infiniflow:main Jul 30, 2026
3 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:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants