Repository navigation
Generate navigation, navigation search - #18096
Conversation
📝 WalkthroughWalkthroughThe PR adds dataset navigation generation and search commands, API endpoints, hybrid retrieval, tree descent, enriched navigation metadata, and web rendering for keywords, entities, and graph content. ChangesDataset navigation
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant DatasetNavigationAPI
participant dataset_api_service
participant dataset_nav
Client->>DatasetNavigationAPI: Request navigation generation or search
DatasetNavigationAPI->>dataset_api_service: Call service workflow
dataset_api_service->>dataset_nav: Rebuild tree or run hybrid search
dataset_nav-->>dataset_api_service: Return progress or results
dataset_api_service-->>DatasetNavigationAPI: Return service response
DatasetNavigationAPI-->>Client: Return API response
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
There was a problem hiding this comment.
Actionable comments posted: 18
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/advanced_rag/knowlege_compile/dataset_nav.py (1)
780-800: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winInclude
graph_contentin the change-detection comparison.
graph_contentnow drives the embedding (Line 799), the tokenizedcontent_ltks, the extracted keywords and entities, and the storedgraph_contentpayload field. The early-return check at Line 821 still compares onlyold_payload.get("description") == summary, anddescriptionholds the title alone. If a document's graph text changes while its title stays the same, the function returns early and leaves the stored graph content, keywords, entities, and vector stale.
generate_navdeletes the whole tree before rebuilding, so it is unaffected. The incremental callers inapi/apps/services/dataset_api_service.pyreuse this function and are affected.🐛 Proposed fix for the staleness check
existing_doc = await _store_get(tenant_id, kb_id, _nav_doc_id(doc_id)) if existing_doc: old_payload = json.loads(existing_doc.get("content_with_weight") or "{}") - if old_payload.get("description") == summary: + if old_payload.get("description") == summary and (old_payload.get("graph_content") or "") == graph_content: return await _remove_dataset_nav_doc_locked(tenant_id, kb_id, doc_id)🤖 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/knowlege_compile/dataset_nav.py` around lines 780 - 800, Update the change-detection logic in the document-processing function to compare the stored graph_content payload against the current graph_content in addition to comparing description with summary. Prevent the early return when graph content changes, while preserving the existing skip behavior when both the title and graph content are unchanged.
🧹 Nitpick comments (10)
admin/client/parser.py (1)
202-202: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
EXPLOREis declared but no rule uses it.No grammar rule in
GRAMMARreferences theEXPLOREterminal, and no transformer method consumes it. Remove it until a command needs it.♻️ Proposed cleanup
SEARCH: "SEARCH"i -EXPLORE: "EXPLORE"i CURRENT: "CURRENT"iAs per coding guidelines: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@admin/client/parser.py` at line 202, Remove the unused EXPLORE terminal declaration from the parser grammar definitions, leaving GRAMMAR and transformer behavior unchanged since no rule or transformer method references it.Source: Coding guidelines
api/apps/services/dataset_api_service.py (3)
3743-3753: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff
allmode embeds the same query three times.
_search_layers_nav_docs,_search_layers_nav_clusters, and_search_layers_navigation_treeeach call_embed(embd_mdl, query)internally on the identical query string. Oneallrequest therefore issues three embedding calls plus the chunk retriever's own embedding.Consider embedding once in
search_dataset_layersand passing the vector down, or caching the embedding per request.Also,
import asyncio as _asyncioat Line 3745 aliases a stdlib module inside the function body. A plain module-levelimport asynciois clearer.🤖 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 3743 - 3753, Update _search_layers_all and the related navigation search functions to compute the query embedding once per request and reuse that vector across _search_layers_nav_docs, _search_layers_nav_clusters, and _search_layers_navigation_tree, while preserving the chunk retriever’s behavior. Replace the function-local “import asyncio as _asyncio” with a clear module-level asyncio import and use it directly.
3701-3709: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the unused
kbparameter and the redundant local import.
kbis accepted but never read in the body._search_layers_allandsearch_dataset_layersboth pass it, so three call sites carry a value that has no effect.Line 3702 also re-imports
settings, which this module already imports at Line 32.♻️ Proposed cleanup
-async def _search_layers_chunks(tenant_id, dataset_id, query, top_k, embd_mdl, kb): - from common import settings +async def _search_layers_chunks(tenant_id, dataset_id, query, top_k, embd_mdl): tenant_ids = [tenant_id]Update the two call sites accordingly.
As per coding guidelines: "Reduce public surface area when a helper can be made private or internal" and "Remove dead ... code".
🤖 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 3701 - 3709, Remove the unused kb parameter from _search_layers_chunks and delete its redundant local settings import, relying on the module-level import. Update both _search_layers_all and search_dataset_layers call sites to stop passing kb while preserving all other arguments and behavior.Source: Coding guidelines
3427-3427: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueFix the
raptor_summariestype annotation.The annotation says
dict[str, str]. Line 3503 assigns a dict value:{"title": ..., "graph_text": ...}.♻️ Proposed fix
- raptor_summaries: dict[str, str] = {} + raptor_summaries: dict[str, dict[str, str]] = {}🤖 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` at line 3427, Update the raptor_summaries annotation in the surrounding dataset service method to reflect that its values are dictionaries containing fields such as title and graph_text, rather than strings. Keep the existing raptor_summaries assignments and key type unchanged, using the appropriate structured value type already established in the codebase if available.admin/client/ragflow_client.py (2)
1810-1813: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the duplicate "not found" message.
_get_dataset_id(Line 2027) already printsDataset {dataset_name} not foundbefore returningNone. Line 1812 prints a second, near-identical message, so the user sees the same error twice.♻️ Proposed cleanup
dataset_id = self._get_dataset_id(dataset_name) if dataset_id is None: - print(f"Dataset not found: {dataset_name}") return🤖 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 `@admin/client/ragflow_client.py` around lines 1810 - 1813, Remove the redundant print call from the dataset lookup handling in the method containing _get_dataset_id usage, while preserving the dataset_id is None early return. Let _get_dataset_id remain the sole source of the dataset-not-found message.
1815-1821: 🩺 Stability & Availability | 🔵 TrivialConsider a request timeout for this long-running call.
generate_navrebuilds the whole navigation tree. It runs an LLM merge or summary call for each document, so the request can take many minutes.HttpClient.requestdoes not pass atimeouttorequests; thetimeouttuple is present but commented out inadmin/client/http_client.py. A stalled connection leaves the CLI hanging with no output and no way to distinguish it from slow progress.Consider passing an explicit long read timeout for this command, or printing a progress hint before the call.
🤖 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 `@admin/client/ragflow_client.py` around lines 1815 - 1821, Update the navigation-tree request in generate_nav to use an explicit timeout suitable for its potentially multi-minute LLM processing, ensuring HttpClient.request forwards that timeout to the underlying HTTP request; alternatively, emit a progress hint before the call if that is the established approach.rag/advanced_rag/knowlege_compile/dataset_nav.py (4)
1324-1332: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove or populate
doc_titleandsource_type.No writer sets
doc_titleorsource_typein the nav payload._make_nav_doc_rowwritestype,description,keywords,entities, and optionallygraph_content._make_nav_cluster_rowwritestype,description,keywords, andentities. Both fields therefore always resolve to"".Either persist them in
_make_nav_doc_row, or drop them from the result shape and from thegenerate_navdocstring inapi/apps/services/dataset_api_service.py.🤖 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/knowlege_compile/dataset_nav.py` around lines 1324 - 1332, Remove the always-empty doc_title and source_type fields from the navigation result shape in the shown row construction, and update the generate_nav docstring in api/apps/services/dataset_api_service.py accordingly. Keep the existing fields populated by _make_nav_doc_row and _make_nav_cluster_row unchanged.
1537-1553: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the fusion key scheme.
The
knn:/text:key prefixes add a three-way branch that resolves to a single behaviour: merge a node into its existing entry, otherwise insert it. A plainrkkey gives the same result with less code.♻️ Proposed simplification
# Text leg. for r in text_rows: rk = r.get("name") or r.get("doc_id") or "" if not rk: continue ts = _nav_text_score(query, r) if ts <= 0: continue - key = f"text:{rk}" - if key in fused: - fused[key] = (fused[key][0], fused[key][1] + text_w * ts) - else: - key_knn = f"knn:{rk}" - if key_knn in fused: - fused[key_knn] = (fused[key_knn][0], fused[key_knn][1] + text_w * ts) - else: - fused[key] = (r, text_w * ts) + if rk in fused: + fused[rk] = (fused[rk][0], fused[rk][1] + text_w * ts) + else: + fused[rk] = (r, text_w * ts)Apply the same un-prefixed key in the KNN leg above.
🤖 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/knowlege_compile/dataset_nav.py` around lines 1537 - 1553, Update the fusion logic in the text leg and corresponding KNN leg to use the plain rk value as the dictionary key, removing the knn:/text: prefixes and fallback branch. Merge scores into the existing fused[rk] entry when present; otherwise insert the row under rk while preserving the current score calculations and weights.
1463-1472: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueConsider running the two child lookups concurrently.
Each expanded node issues a KNN call and then a text-search call sequentially. With
beam_width = 5and several levels this serialises up to ten round trips per level. Both calls are independent.Use
asyncio.gatherto overlap them, and optionally gather across the nodes incurrent_level.🤖 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/knowlege_compile/dataset_nav.py` around lines 1463 - 1472, The child KNN and text-search calls in the node expansion flow should run concurrently because they are independent. Update the logic around _store_knn and _store_text_search to use asyncio.gather, then pass both results to _hybrid_fuse in the existing order; if practical, preserve the same behavior while also batching lookups across current_level.
1576-1588: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueSubstring matching over the enlarged haystack raises false positives.
Line 1592 tests
term in haystack, which matches inside words. Addinggraph_contentmakes the haystack much larger, so more query terms match by coincidence and every node's score drifts upward.Consider tokenising the haystack once and comparing token sets, so the score reflects whole-word matches.
🤖 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/knowlege_compile/dataset_nav.py` around lines 1576 - 1588, Replace substring checks against the enlarged haystack in the node-scoring logic with whole-word token matching: tokenize the normalized haystack once, build a token set, and compare each query term as a normalized token. Preserve the existing keyword/entity scoring flow while ensuring only exact tokens contribute to the score.
🤖 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 `@admin/client/parser.py`:
- Around line 803-826: Simplify topk extraction in navigation_search by removing
the unreachable wrapper branch and exception handling. When len(items) > 9,
parse the NUMBER token directly from items[9] with int; otherwise leave topk as
None.
In `@admin/client/ragflow_client.py`:
- Around line 1842-1850: Update the dataset lookup flow in the relevant client
method to validate mode against valid_modes before calling _get_dataset_id,
avoiding any HTTP request for invalid modes. Use a silent lookup or equivalent
suppression when resolving dataset_name so an ID fallback does not emit the
misleading “Dataset ... not found” message, while preserving name and ID
resolution behavior.
- Around line 2366-2367: Correct the two navigation help entries: in the
`NAVIGATION SEARCH` usage text, document the grammar token as `TOPK` rather than
`TOP_K`; in the `GENERATE NAVIGATION OF DATASET` entry, indicate that the
argument is the dataset name, matching `generate_nav_for_dataset` and its
`_get_dataset_id` lookup behavior.
- Around line 1852-1860: Update the navigation search URL construction in the
relevant client method to encode query, mode, and optional topk values with
urllib.parse.urlencode, and encode dataset_id as a path segment using
urllib.parse.quote with safe="". Keep the existing request flow and web
authentication options unchanged.
In `@api/apps/restful_apis/dataset_api.py`:
- Around line 1016-1018: Update the search_dataset_layers route handling so an
invalid mode is not mapped to RetCode.AUTHENTICATION_ERROR. Validate mode before
invoking the service and return get_error_argument_result for unknown modes,
while preserving the authentication error response for authorization failures.
- Around line 1006-1007: The dataset API’s top_k parsing must reject non-numeric
values with the existing argument-error response and clamp valid values to an
explicit maximum before passing them downstream; update the top_k handling near
search_dataset_layers/search_dataset_nav in
api/apps/restful_apis/dataset_api.py:1006-1007. Independently update _store_knn
in rag/utils/es_conn.py:261 so k is clamped alongside num_candidates, preserving
the invariant that num_candidates is always at least k for every caller-provided
topn.
- Around line 1107-1115: Update the request parsing in the dataset navigation
endpoint to use silent JSON loading, default empty bodies to an object, and
validate that the top-level value is an object with a list-valued documents
field. In the surrounding generate_nav response handling, map only the "no
authorization" service result to RetCode.AUTHENTICATION_ERROR and preserve
dataset/data failure messages and their appropriate service error codes.
In `@api/apps/services/dataset_api_service.py`:
- Around line 3710-3723: In api/apps/services/dataset_api_service.py, update the
exception handler around lines 3710-3723 in the chunk-retrieval flow to call
logging.exception before returning "chunk retrieval failed"; narrow the handler
around lines 3450-3453 to TypeError and ValueError and log a warning including
the document id before continuing; and update the all-search handling around
lines 3755-3761 to log gathered exceptions and any ok=False results so partial
failures are observable.
- Around line 3582-3588: Refactor the layer-search dispatch around
`_LAYERS_HANDLERS` and the method containing the current mode `if`/`elif` chain
so the mapping is the single source of truth: either dispatch through its
handler-name values or reduce it to a mode set used for validation. Remove the
duplicated mode checks and the unreachable trailing `else`, while preserving
each existing mode-to-handler behavior.
- Around line 3402-3412: Update the async generate_nav flow to run all
identified blocking operations through the existing thread_pool_exec helper: the
peewee query within DB.connection_context(),
DocMetadataService.get_metadata_for_documents(), and
settings.docStoreConn.search(..., limit=10000). Preserve their current inputs
and result handling, matching the established usage elsewhere in generate_nav
and get_dataset_structure.
- Around line 3553-3575: Update the navigation rebuild loop around
upsert_dataset_nav_doc so a per-document exception cannot return success after
deleting the existing tree. Continue processing remaining documents while
recording failed document IDs, then return a failure status (or otherwise ensure
the caller does not report successful creation) whenever any upsert fails; add
the required logging for this flow.
- Around line 3685-3698: Update _nav_search_result to expand each result’s
doc_ids into a separate output item, while retaining the single doc_id behavior
for ordinary hits. Skip results with no usable document IDs, including empty
doc_ids lists and missing or blank doc_id values, so no empty entries are
appended or counted.
- Around line 3711-3721: Update the settings.retriever.retrieval call to pass
fetch_k as the top argument instead of top_k, so backend candidate retrieval
uses the intended fetch_k = 3 * max(top_k, 10) window while preserving the
existing page-size behavior.
- Around line 3434-3444: Update the tree-graph search flow in the surrounding
method using the settings.docStoreConn.search call so it retrieves all matching
rows in batches rather than stopping at limit=10000. Use the search result’s
get_total() to determine pagination, repeatedly advance offset while preserving
the existing fields and filters, and combine each batch before writing the
graph; only retain a fixed limit if it is explicitly documented as an
intentional ceiling.
In `@rag/advanced_rag/knowlege_compile/dataset_nav.py`:
- Around line 1376-1379: In the dataset navigation function, replace the dense_w
assignment based on _RECURSE_THRESHOLD with the existing _NAV_HYBRID_DENSE_W
fusion-weight constant so it matches search_dataset_nav. Remove the unused
text_w assignment, since _hybrid_fuse derives the complementary weight itself.
- Around line 1439-1443: Update the root-cluster ranking in the branch using
roots_knn to compute each row’s _score with _cosine_sim(vec, r.get(vf)) before
sorting, matching the scoring pattern in the fallback branch. Sort by the
computed scores in descending order, then retain those scores when selecting
current_level so parent_score reflects actual root similarity.
- Around line 1529-1535: Remove the per-parent ds_scale normalization from the
KNN fusion logic and score each child using its raw cosine similarity multiplied
by dense_w. Update the fused assignment in search_nav_tree_descent while
preserving the existing row-key construction and beam ordering behavior.
In `@web/src/locales/en.ts`:
- Line 2405: Update the graphContent English localization label from title case
to sentence case, using “Full graph content” while preserving the existing key
and translation structure.
---
Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/dataset_nav.py`:
- Around line 780-800: Update the change-detection logic in the
document-processing function to compare the stored graph_content payload against
the current graph_content in addition to comparing description with summary.
Prevent the early return when graph content changes, while preserving the
existing skip behavior when both the title and graph content are unchanged.
---
Nitpick comments:
In `@admin/client/parser.py`:
- Line 202: Remove the unused EXPLORE terminal declaration from the parser
grammar definitions, leaving GRAMMAR and transformer behavior unchanged since no
rule or transformer method references it.
In `@admin/client/ragflow_client.py`:
- Around line 1810-1813: Remove the redundant print call from the dataset lookup
handling in the method containing _get_dataset_id usage, while preserving the
dataset_id is None early return. Let _get_dataset_id remain the sole source of
the dataset-not-found message.
- Around line 1815-1821: Update the navigation-tree request in generate_nav to
use an explicit timeout suitable for its potentially multi-minute LLM
processing, ensuring HttpClient.request forwards that timeout to the underlying
HTTP request; alternatively, emit a progress hint before the call if that is the
established approach.
In `@api/apps/services/dataset_api_service.py`:
- Around line 3743-3753: Update _search_layers_all and the related navigation
search functions to compute the query embedding once per request and reuse that
vector across _search_layers_nav_docs, _search_layers_nav_clusters, and
_search_layers_navigation_tree, while preserving the chunk retriever’s behavior.
Replace the function-local “import asyncio as _asyncio” with a clear
module-level asyncio import and use it directly.
- Around line 3701-3709: Remove the unused kb parameter from
_search_layers_chunks and delete its redundant local settings import, relying on
the module-level import. Update both _search_layers_all and
search_dataset_layers call sites to stop passing kb while preserving all other
arguments and behavior.
- Line 3427: Update the raptor_summaries annotation in the surrounding dataset
service method to reflect that its values are dictionaries containing fields
such as title and graph_text, rather than strings. Keep the existing
raptor_summaries assignments and key type unchanged, using the appropriate
structured value type already established in the codebase if available.
In `@rag/advanced_rag/knowlege_compile/dataset_nav.py`:
- Around line 1324-1332: Remove the always-empty doc_title and source_type
fields from the navigation result shape in the shown row construction, and
update the generate_nav docstring in api/apps/services/dataset_api_service.py
accordingly. Keep the existing fields populated by _make_nav_doc_row and
_make_nav_cluster_row unchanged.
- Around line 1537-1553: Update the fusion logic in the text leg and
corresponding KNN leg to use the plain rk value as the dictionary key, removing
the knn:/text: prefixes and fallback branch. Merge scores into the existing
fused[rk] entry when present; otherwise insert the row under rk while preserving
the current score calculations and weights.
- Around line 1463-1472: The child KNN and text-search calls in the node
expansion flow should run concurrently because they are independent. Update the
logic around _store_knn and _store_text_search to use asyncio.gather, then pass
both results to _hybrid_fuse in the existing order; if practical, preserve the
same behavior while also batching lookups across current_level.
- Around line 1576-1588: Replace substring checks against the enlarged haystack
in the node-scoring logic with whole-word token matching: tokenize the
normalized haystack once, build a token set, and compare each query term as a
normalized token. Preserve the existing keyword/entity scoring flow while
ensuring only exact tokens contribute to the score.
🪄 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: 71a500d3-49c9-4ab6-899f-13c9128d3ec2
📒 Files selected for processing (12)
admin/client/parser.pyadmin/client/ragflow_client.pyapi/apps/restful_apis/dataset_api.pyapi/apps/services/dataset_api_service.pyrag/advanced_rag/harness/tools/navigation.pyrag/advanced_rag/knowlege_compile/dataset_nav.pyrag/utils/es_conn.pyweb/src/interfaces/database/dataset-nav.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/dataset/compilation/hooks/use-compilation-nav.tsweb/src/pages/dataset/compilation/nav-tree-view.tsx
| def navigation_search(self, items): | ||
| query = items[2].children[0].strip("'\"") | ||
| dataset_name = items[5].children[0].strip("'\"") | ||
| mode = items[7].children[0].strip("'\"") | ||
| topk = None | ||
| # If TOPK was specified, items will be longer. | ||
| if len(items) > 9: | ||
| try: | ||
| extra = items[8] | ||
| if hasattr(extra, "data"): | ||
| # group wrapper: extra.children = [TOPK, NUMBER] | ||
| topk = int(extra.children[1]) | ||
| else: | ||
| # flattened: items[8] = TOPK, items[9] = NUMBER | ||
| topk = int(items[9]) | ||
| except (ValueError, IndexError): | ||
| topk = None | ||
| return { | ||
| "type": "navigation_search", | ||
| "query": query, | ||
| "dataset_id": dataset_name, | ||
| "mode": mode, | ||
| "topk": topk, | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Simplify the topk extraction; both fallback paths are unreachable.
The grammar at Line 383 uses an inline (TOPK NUMBER)? group. Lark does not wrap an anonymous inline group in a Tree, so items[8] is always the TOPK token and hasattr(extra, "data") is always false. The group-wrapper branch never runs.
NUMBER is /[0-9]+/, so int(items[9]) cannot raise ValueError, and the index is guaranteed present by the len(items) > 9 guard. The except (ValueError, IndexError) clause is also unreachable.
♻️ Proposed simplification
def navigation_search(self, items):
query = items[2].children[0].strip("'\"")
dataset_name = items[5].children[0].strip("'\"")
mode = items[7].children[0].strip("'\"")
topk = None
- # If TOPK was specified, items will be longer.
- if len(items) > 9:
- try:
- extra = items[8]
- if hasattr(extra, "data"):
- # group wrapper: extra.children = [TOPK, NUMBER]
- topk = int(extra.children[1])
- else:
- # flattened: items[8] = TOPK, items[9] = NUMBER
- topk = int(items[9])
- except (ValueError, IndexError):
- topk = None
+ # The optional `(TOPK NUMBER)` group adds two tokens before the ";".
+ if len(items) > 9:
+ topk = int(items[9])
return {As per coding guidelines: "When old and new implementations coexist, converge on one implementation path unless an external contract requires compatibility."
📝 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.
| def navigation_search(self, items): | |
| query = items[2].children[0].strip("'\"") | |
| dataset_name = items[5].children[0].strip("'\"") | |
| mode = items[7].children[0].strip("'\"") | |
| topk = None | |
| # If TOPK was specified, items will be longer. | |
| if len(items) > 9: | |
| try: | |
| extra = items[8] | |
| if hasattr(extra, "data"): | |
| # group wrapper: extra.children = [TOPK, NUMBER] | |
| topk = int(extra.children[1]) | |
| else: | |
| # flattened: items[8] = TOPK, items[9] = NUMBER | |
| topk = int(items[9]) | |
| except (ValueError, IndexError): | |
| topk = None | |
| return { | |
| "type": "navigation_search", | |
| "query": query, | |
| "dataset_id": dataset_name, | |
| "mode": mode, | |
| "topk": topk, | |
| } | |
| def navigation_search(self, items): | |
| query = items[2].children[0].strip("'\"") | |
| dataset_name = items[5].children[0].strip("'\"") | |
| mode = items[7].children[0].strip("'\"") | |
| topk = None | |
| # The optional `(TOPK NUMBER)` group adds two tokens before the ";". | |
| if len(items) > 9: | |
| topk = int(items[9]) | |
| return { | |
| "type": "navigation_search", | |
| "query": query, | |
| "dataset_id": dataset_name, | |
| "mode": mode, | |
| "topk": topk, | |
| } |
🤖 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 `@admin/client/parser.py` around lines 803 - 826, Simplify topk extraction in
navigation_search by removing the unreachable wrapper branch and exception
handling. When len(items) > 9, parse the NUMBER token directly from items[9]
with int; otherwise leave topk as None.
Source: Coding guidelines
| # Try name lookup; fall back to using the value directly as an ID. | ||
| dataset_id = self._get_dataset_id(dataset_name) | ||
| if dataset_id is None: | ||
| dataset_id = dataset_name | ||
|
|
||
| valid_modes = {"nav_doc", "nav_cluster", "navigation_tree", "chunk", "all"} | ||
| if mode not in valid_modes: | ||
| print(f"Invalid mode: {mode}, expected one of {valid_modes}") | ||
| return |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
The dataset-ID fallback prints a misleading error, and mode validation runs too late.
Two issues.
_get_dataset_id prints Dataset {name} not found at Line 2027 before it returns None. When the user passes a dataset ID rather than a name, the fallback at Line 1845 succeeds, but the user has already seen a "not found" error. The help text at Line 2367 advertises '<name or id>', so this path is expected.
The mode check at Lines 1847-1850 runs after the dataset lookup, which already issued an HTTP request. Validate mode first.
🐛 Proposed fix
+ valid_modes = {"nav_doc", "nav_cluster", "navigation_tree", "chunk", "all"}
+ if mode not in valid_modes:
+ print(f"Invalid mode: {mode}, expected one of {sorted(valid_modes)}")
+ return
+
# Try name lookup; fall back to using the value directly as an ID.
dataset_id = self._get_dataset_id(dataset_name)
if dataset_id is None:
dataset_id = dataset_name
-
- valid_modes = {"nav_doc", "nav_cluster", "navigation_tree", "chunk", "all"}
- if mode not in valid_modes:
- print(f"Invalid mode: {mode}, expected one of {valid_modes}")
- returnAdd a silent variant of the lookup, or suppress the message when the caller intends to fall back.
🤖 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 `@admin/client/ragflow_client.py` around lines 1842 - 1850, Update the dataset
lookup flow in the relevant client method to validate mode against valid_modes
before calling _get_dataset_id, avoiding any HTTP request for invalid modes. Use
a silent lookup or equivalent suppression when resolving dataset_name so an ID
fallback does not emit the misleading “Dataset ... not found” message, while
preserving name and ID resolution behavior.
| url = f"/datasets/{dataset_id}/navigation/search?q={query}&mode={mode}" | ||
| if topk is not None: | ||
| url += f"&top_k={topk}" | ||
| response = self.http_client.request( | ||
| "GET", | ||
| url, | ||
| use_api_base=True, | ||
| auth_kind="web", | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check whether HttpClient.request forwards `params` to the underlying requests call.
set -euo pipefail
# Test: Show the request() body. Expect: params passed through to http_function.
fd -t f 'http_client.py' | xargs -I{} rg -nP -A 60 'def request\(' {}Repository: infiniflow/ragflow
Length of output: 4988
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- matching http_client.py files ---'
fd -t f 'http_client.py' -x sh -c 'echo "FILE: $1"; rg -n -A 75 -B 8 "def request\\(" "$1"' sh {}
echo '--- ragflow_client imports and class context ---'
fd -t f 'ragflow_client.py' -x sh -c 'echo "FILE: $1"; rg -n -A 12 -B 12 "HttpClient|urllib|navigation/search|def .*search" "$1"' sh {}
echo '--- all HttpClient definitions and imports ---'
rg -n "^(class HttpClient|from .*http_client|import .*http_client)" --glob '*.py' .Repository: infiniflow/ragflow
Length of output: 6480
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -t f -a 'ragflow_client.py' | head -n 1)"
echo "FILE: $file"
sed -n '1,80p' "$file"
sed -n '1815,1880p' "$file"
echo '--- URL encoding patterns in admin client ---'
rg -n -C 3 'urllib|urlencode|quote\\(' admin/client/ragflow_client.py admin/client/http_client.py
echo '--- call sites and tests for navigation search ---'
rg -n -C 5 'navigation/search|search_dataset|top_k|topk' admin test --glob '*.py'Repository: infiniflow/ragflow
Length of output: 6291
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from urllib.parse import quote, urlencode, urlsplit, parse_qs
dataset_id = "dataset/42?x=1"
query = "alpha &top_k=1#frag+term"
mode = "nav_doc"
topk = 5
raw = f"/datasets/{dataset_id}/navigation/search?q={query}&mode={mode}&top_k={topk}"
encoded = (
f"/datasets/{quote(dataset_id, safe='')}/navigation/search?"
+ urlencode({"q": query, "mode": mode, "top_k": topk})
)
print("raw:", raw)
print("raw_query:", parse_qs(urlsplit(raw).query, keep_blank_values=True))
print("encoded:", encoded)
print("encoded_query:", parse_qs(urlsplit(encoded).query, keep_blank_values=True))
PYRepository: infiniflow/ragflow
Length of output: 521
Encode the navigation-search URL values.
query can inject or corrupt query parameters, and dataset_id can alter the path when it contains reserved characters. admin/client/http_client.py does not forward its params argument, so encode the values explicitly with urllib.parse.urlencode and urllib.parse.quote(..., safe="").
🤖 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 `@admin/client/ragflow_client.py` around lines 1852 - 1860, Update the
navigation search URL construction in the relevant client method to encode
query, mode, and optional topk values with urllib.parse.urlencode, and encode
dataset_id as a path segment using urllib.parse.quote with safe="". Keep the
existing request flow and web authentication options unchanged.
| GENERATE NAVIGATION OF DATASET '<id>' | ||
| NAVIGATION SEARCH '<query>' IN DATASET '<name or id>' MODE '<mode>' [TOP_K <n>] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Correct the two help entries.
Line 2367 documents TOP_K. The grammar terminal is TOPK (admin/client/parser.py Line 178) and the rule is (TOPK NUMBER)? (Line 383). A user who types TOP_K 20 gets a parse error.
Line 2366 documents '<id>'. generate_nav_for_dataset resolves the value through _get_dataset_id, which matches on the dataset name and returns None for an id. Unlike navigation_search, this method has no id fallback.
🐛 Proposed fix
-GENERATE NAVIGATION OF DATASET '<id>'
-NAVIGATION SEARCH '<query>' IN DATASET '<name or id>' MODE '<mode>' [TOP_K <n>]
+GENERATE NAVIGATION OF DATASET '<name>'
+NAVIGATION SEARCH '<query>' IN DATASET '<name or id>' MODE '<mode>' [TOPK <n>]
+ <mode>: nav_doc | nav_cluster | navigation_tree | chunk | all📝 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.
| GENERATE NAVIGATION OF DATASET '<id>' | |
| NAVIGATION SEARCH '<query>' IN DATASET '<name or id>' MODE '<mode>' [TOP_K <n>] | |
| GENERATE NAVIGATION OF DATASET '<name>' | |
| NAVIGATION SEARCH '<query>' IN DATASET '<name or id>' MODE '<mode>' [TOPK <n>] | |
| <mode>: nav_doc | nav_cluster | navigation_tree | chunk | all |
🤖 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 `@admin/client/ragflow_client.py` around lines 2366 - 2367, Correct the two
navigation help entries: in the `NAVIGATION SEARCH` usage text, document the
grammar token as `TOPK` rather than `TOP_K`; in the `GENERATE NAVIGATION OF
DATASET` entry, indicate that the argument is the dataset name, matching
`generate_nav_for_dataset` and its `_get_dataset_id` lookup behavior.
| ranks = await settings.retriever.retrieval( | ||
| query, | ||
| embd_mdl, | ||
| tenant_ids, | ||
| [dataset_id], | ||
| 1, | ||
| fetch_k, | ||
| 0.0, | ||
| 0.3, | ||
| **kwargs, | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Resolve the retrieval() signature and compare with other call sites.
set -euo pipefail
# Test: Locate the retrieval definition. Expect: a clear parameter order for page/page_size/similarity/top.
ast-grep run --pattern 'async def retrieval($$$) { $$$ }' --lang python . 2>/dev/null \
|| rg -nP -A 25 'def retrieval\s*\(' --type=py
# Test: Compare with existing callers. Expect: consistent argument ordering.
rg -nP -C 6 'retriever\.retrieval\(' --type=pyRepository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- retrieval definitions ---'
rg -n -P -A 35 -B 5 '^\s*(async\s+)?def\s+retrieval\s*\(' --type=py .
printf '%s\n' '--- retrieval call sites ---'
rg -n -P -C 8 'retriever\.retrieval\s*\(' --type=py .Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- target caller ---'
sed -n '3688,3730p' api/apps/services/dataset_api_service.py
printf '%s\n' '--- non-test callers of rag.nlp.search retrieval ---'
rg -n -P -C 5 'settings\.retriever\.retrieval\s*\(' --type=py --glob '!test/**' --glob '!tests/**' .
printf '%s\n' '--- retrieval implementation body ---'
sed -n '549,680p' rag/nlp/search.pyRepository: infiniflow/ragflow
Length of output: 19231
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- candidate-window helper and result slicing ---'
sed -n '515,555p' rag/nlp/search.py
sed -n '675,735p' rag/nlp/search.py
printf '%s\n' '--- complete nearby callers with argument names ---'
sed -n '1118,1155p' api/apps/services/dataset_api_service.py
sed -n '1515,1552p' api/apps/services/dataset_api_service.py
sed -n '1852,1880p' api/db/services/dialog_service.py
printf '%s\n' '--- target helper consumers ---'
rg -n -C 8 '_search_layers_chunks|fetch_k|top_k' api/apps/services/dataset_api_service.pyRepository: infiniflow/ragflow
Length of output: 20854
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- retrieval search path and topk/size handling ---'
rg -n -P -A 70 -B 8 '^\s*(async\s+)?def\s+search\s*\(' rag/nlp/search.py
rg -n -C 5 '"topk"|topk|req\["size"\]|req\.get\("size"' rag/nlp/search.py rag -g '*.py' | head -n 240
printf '%s\n' '--- exact positional-call shape ---'
python3 - <<'PY'
import ast
from pathlib import Path
path = Path("api/apps/services/dataset_api_service.py")
tree = ast.parse(path.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "retrieval":
if isinstance(node.func.value, ast.Attribute) and node.func.value.attr == "retriever":
print(
f"line={node.lineno} positional={len(node.args)} "
f"keywords={[kw.arg for kw in node.keywords]}"
)
PYRepository: infiniflow/ragflow
Length of output: 13096
Pass fetch_k as top
page_size controls the returned chunk window, but top becomes the backend topk and caps vector candidates. Passing top_k limits retrieval before the intended fetch_k = 3 * max(top_k, 10) window is used. Use top=fetch_k for this call.
🤖 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 3711 - 3721, Update
the settings.retriever.retrieval call to pass fetch_k as the top argument
instead of top_k, so backend candidate retrieval uses the intended fetch_k = 3 *
max(top_k, 10) window while preserving the existing page-size behavior.
| description: 'Description', | ||
| keywords: 'Keywords', | ||
| entities: 'Entities', | ||
| graphContent: 'Full Graph Content', |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Use sentence case for the English label.
Line 2405 uses title case in Full Graph Content. Change it to Full graph content.
As per coding guidelines: “For en.ts, use sentence case while preserving proper nouns.”
Proposed fix
- graphContent: 'Full Graph Content',
+ graphContent: 'Full graph content',📝 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.
| graphContent: 'Full Graph Content', | |
| graphContent: 'Full graph content', |
🤖 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 `@web/src/locales/en.ts` at line 2405, Update the graphContent English
localization label from title case to sentence case, using “Full graph content”
while preserving the existing key and translation structure.
Source: Coding guidelines
fb99a54 to
5c40c26
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
api/apps/services/dataset_api_service.py (1)
3431-3431: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueFix the
raptor_summariestype annotation. The annotation isdict[str, str], but Line 3507 stores adictwithtitleandgraph_textkeys. The consumer at Line 3520 andupsert_dataset_nav_docboth expect the dict form.♻️ Proposed fix
- raptor_summaries: dict[str, str] = {} + raptor_summaries: dict[str, dict[str, str]] = {}Note: the declaration is at Line 3431, outside the
if pack is not Noneblock shown above.🤖 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` at line 3431, Update the raptor_summaries annotation to represent string keys mapped to dictionaries containing the title and graph_text fields, matching the values stored later and the expectations of the consumer and upsert_dataset_nav_doc.rag/advanced_rag/knowlege_compile/dataset_nav.py (1)
1526-1553: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the fusion key scheme. The map uses two prefixes,
knn:andtext:, for the same node. The code then needs a second lookup onkey_knnto merge the legs. A single key per node makes the dedup explicit and matchessearch_dataset_nav, which keys byrkalone.♻️ Proposed refactor
- key = f"knn:{rk}" - fused[key] = (r, _cosine_sim(vec, r.get(vf, [])) * dense_w) + fused[rk] = (r, _cosine_sim(vec, r.get(vf, [])) * dense_w) @@ - key = f"text:{rk}" - if key in fused: - fused[key] = (fused[key][0], fused[key][1] + text_w * ts) - else: - key_knn = f"knn:{rk}" - if key_knn in fused: - fused[key_knn] = (fused[key_knn][0], fused[key_knn][1] + text_w * ts) - else: - fused[key] = (r, text_w * ts) + row, score = fused.get(rk, (r, 0.0)) + fused[rk] = (row, score + text_w * ts)🤖 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/knowlege_compile/dataset_nav.py` around lines 1526 - 1553, Simplify the fused map in the fusion logic by using each node identifier rk directly as the key instead of separate knn: and text: prefixes. Update both KNN and text insertion paths to merge entries through that single key, preserving the existing score accumulation and deduplication 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.
Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Line 3431: Update the raptor_summaries annotation to represent string keys
mapped to dictionaries containing the title and graph_text fields, matching the
values stored later and the expectations of the consumer and
upsert_dataset_nav_doc.
In `@rag/advanced_rag/knowlege_compile/dataset_nav.py`:
- Around line 1526-1553: Simplify the fused map in the fusion logic by using
each node identifier rk directly as the key instead of separate knn: and text:
prefixes. Update both KNN and text insertion paths to merge entries through that
single key, preserving the existing score accumulation and deduplication
behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 5875651d-1d97-4832-9ecc-2cec667a25e1
📒 Files selected for processing (7)
admin/client/ragflow_client.pyapi/apps/restful_apis/dataset_api.pyapi/apps/services/dataset_api_service.pyrag/advanced_rag/knowlege_compile/dataset_nav.pyrag/utils/es_conn.pyweb/src/locales/en.tsweb/src/locales/zh.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- web/src/locales/en.ts
- web/src/locales/zh.ts
- rag/utils/es_conn.py
- admin/client/ragflow_client.py
- api/apps/restful_apis/dataset_api.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #18096 +/- ##
=======================================
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:
|
Summary
2 API
POST /api/v1/datasets/{dataset_id}/navigation
GET /api/v1/datasets/{dataset_id}/navigation/search?q={query}&mode={mode}&top_k={topk}
2 cli
uv run --no-sync python3 admin/client/ragflow_cli.py -h 127.0.0.1 -p 9380 -t user
ragflow> GENERATE NAVIGATION OF DATASET 'frames tree';
ragflow> NAVIGATION SEARCH 'Christie introduced blockchain-based digital passports' IN DATASET 'frames tree' MODE 'all' topk 20;
(mode: chunk, nav_cluster, nav_doc, navigation_tree, all)