Repository navigation
fix: stabilize knowledge compilation navigation updates - #17345
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughDataset navigation cleanup, placement, deletion, storage handling, and tree rendering were updated. Document rerun and deletion paths now remove navigation records, Infinity operations add retry and value handling, and tree-template compilation passes model context during navigation upserts. ChangesDataset navigation and storage
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Compiler
participant upsert_dataset_nav_doc
participant EmbeddingModel
participant RedisLock
participant DatasetNavStore
Compiler->>upsert_dataset_nav_doc: pass tree and model handles
upsert_dataset_nav_doc->>EmbeddingModel: compute document embedding
upsert_dataset_nav_doc->>RedisLock: acquire navigation lock
upsert_dataset_nav_doc->>DatasetNavStore: inspect, replace, and place navigation document
RedisLock-->>upsert_dataset_nav_doc: release navigation lock
Possibly related PRs
Suggested labels: 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 |
wangq8
left a comment
There was a problem hiding this comment.
Thanks for this comprehensive fix! I reviewed the diff carefully and the changes look solid overall. A few observations:
✅ Good changes
-
Lock serialization in
upsert_dataset_nav_doc— moving the existing-doc check and removal under the same lock that handles placement is the right fix for concurrent update races. Embedding is correctly done outside the lock. -
visited_namesprotection in_find_best_cluster— prevents infinite recursion when cluster parent references form a cycle. Clean and minimal. -
_remove_dataset_nav_doc_lockedextraction — reduces duplication between the asyncremove_dataset_nav_docand the inline removal insideupsert_dataset_nav_doc. Both callers hold the lock as documented. -
PageIndex keyword fix in
runner.py— tryingpage_indexfirst, falling back totimelinefor legacy data is the right approach for backward compatibility. -
Empty list handling in
infinity_conn.pyupdate()— the Infinity Python client indeed crashes on empty lists during value inspection. Converting to empty JSON/empty string for known field types is correct. -
_store_knnre-ranking fallback — some Infinity deployments return vector results that don't respect filters well. Falling back to a full scan + filter + rerank when mismatches are detected is a reasonable safety net. The_matches_conditionhelper is focused on the simple equality filters used by nav queries. -
Exact matching for
compile_kwd,type_kwd,parent_kwdininfinity_conn_base.py— these keyword fields need=comparison, notjson_contains, and this is also more efficient. -
Frontend
hasChildren— differentiating "no children loaded yet" from "leaf node" is the correct fix for expandable clusters showing as documents. -
remove_dataset_nav_doc_syncbefore chunk deletion indocument_service.py— the nav_doc row needs to exist for the parent cluster lookup, so it must be processed before the broaddoc_iddelete. -
Passing
embd_mdl/chat_mdlincompiler.pyandchunk_post_processor.py— these call sites were missing the model parameters needed for doc embedding and cluster summary generation.
⚠️ Minor suggestions (non-blocking)
-
_matches_conditionstring comparison: comparing viastr(value) == str(item)is a bit loose but works for the controlled nav field values. Not a blocker. -
_store_knnfallback threshold: the fallback triggers on any mismatch in the KNN results. For very large navigation graphs this may add a full scan on every query. Consider adding a mismatch ratio threshold if perf becomes an issue, but it's fine for now. -
Infinity delete log: you removed the debug log line for the delete filter (
self.logger.debug(f"INFINITY delete table ...")). Might want to keep it at trace level instead of removing entirely, but minor.
Overall this looks solid. Thanks for the thorough fix! 🚀
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
common/doc_store/infinity_conn_base.py (1)
61-85: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winValidate retry bounds before entering the retry loop.
_int_envacceptsINFINITY_META_RETRY_MAX=0or negative values, causing_retry_on_meta_contentionto skip the operation and fail at the assertion. Negative delay values can also maketime.sleepraise, while very large values defeat the stated bounded retry budget. Enforce valid minimums (and a reasonable maximum) for both settings, with the existing warning fallback.Also applies to: 108-151
🤖 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 `@common/doc_store/infinity_conn_base.py` around lines 61 - 85, Update _int_env and the _META_RETRY_MAX/_META_RETRY_BASE_DELAY_MS configuration to validate retry bounds before _retry_on_meta_contention runs: require a positive retry count and non-negative delay, and cap both settings at a reasonable maximum. Preserve the existing warning-and-default fallback behavior for empty, non-numeric, or out-of-range values, ensuring invalid configuration cannot reach the retry loop or time.sleep.
🧹 Nitpick comments (2)
web/src/pages/dataset/compilation/utils/nav-tree.ts (1)
29-32: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd focused tests for the
hasChildrencontract.Cover parent and child nodes with:
has_children: trueand no children, fetched empty children, and populated children. These cases ensure the navigation tree preserves expandable empty branches without regressing leaf rendering.Also applies to: 40-43
🤖 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/pages/dataset/compilation/utils/nav-tree.ts` around lines 29 - 32, Add focused tests for the navigation tree builder around the TreeDataItem.hasChildren assignment: cover parent and child nodes with has_children true and no children, fetched empty children, and populated children. Verify expandable empty branches retain hasChildren while populated and leaf nodes render correctly, using the existing test utilities and the nav-tree construction symbol.Source: Coding guidelines
rag/utils/infinity_conn.py (1)
658-666: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog fields affected by the new sanitization flow.
The new logic can silently drop persisted updates. Add a debug log containing the table and field names whenever empty-list fields are normalized or removed, without logging their values.
As per coding guidelines:
**/*.py: Add logging for new flows.🤖 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/utils/infinity_conn.py` around lines 658 - 666, Add debug logging to the empty-list handling in the sanitization loop around _JSON_LIST_FIELDS and field_keyword(k), recording the table and field names whenever a field is normalized or deleted. Do not include field values, and preserve the existing normalization and removal behavior.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1138-1140: Update the async rerun_agent flow to import
remove_dataset_nav_doc instead of remove_dataset_nav_doc_sync, then await
remove_dataset_nav_doc with the existing tenant_id, doc["kb_id"], and doc["id"]
arguments so cleanup runs on Quart’s active event loop.
In `@rag/advanced_rag/knowlege_compile/dataset_nav.py`:
- Around line 470-473: Update the child-selection assignment in the descent
logic so best_parent is taken from the selected child rather than the previous
best node. In the block assigning best_name, best_parent, sim, and best, read
child’s parent_kwd with the existing fallback behavior before or while updating
best, ensuring _MIN_SIM creates the cluster under the child’s actual parent at
every nesting level.
---
Outside diff comments:
In `@common/doc_store/infinity_conn_base.py`:
- Around line 61-85: Update _int_env and the
_META_RETRY_MAX/_META_RETRY_BASE_DELAY_MS configuration to validate retry bounds
before _retry_on_meta_contention runs: require a positive retry count and
non-negative delay, and cap both settings at a reasonable maximum. Preserve the
existing warning-and-default fallback behavior for empty, non-numeric, or
out-of-range values, ensuring invalid configuration cannot reach the retry loop
or time.sleep.
---
Nitpick comments:
In `@rag/utils/infinity_conn.py`:
- Around line 658-666: Add debug logging to the empty-list handling in the
sanitization loop around _JSON_LIST_FIELDS and field_keyword(k), recording the
table and field names whenever a field is normalized or deleted. Do not include
field values, and preserve the existing normalization and removal behavior.
In `@web/src/pages/dataset/compilation/utils/nav-tree.ts`:
- Around line 29-32: Add focused tests for the navigation tree builder around
the TreeDataItem.hasChildren assignment: cover parent and child nodes with
has_children true and no children, fetched empty children, and populated
children. Verify expandable empty branches retain hasChildren while populated
and leaf nodes render correctly, using the existing test utilities and the
nav-tree construction symbol.
🪄 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: c74f8f98-1c2b-44fe-8ea7-0a4492c26b46
📒 Files selected for processing (12)
api/apps/restful_apis/agent_api.pyapi/apps/restful_apis/document_api.pyapi/apps/services/dataset_api_service.pyapi/db/services/document_service.pycommon/doc_store/infinity_conn_base.pyrag/advanced_rag/knowlege_compile/dataset_nav.pyrag/advanced_rag/knowlege_compile/runner.pyrag/flow/compiler/compiler.pyrag/svr/task_executor_refactor/chunk_post_processor.pyrag/utils/infinity_conn.pyweb/src/components/ui/tree-view.tsxweb/src/pages/dataset/compilation/utils/nav-tree.ts
| from rag.advanced_rag.knowlege_compile.dataset_nav import remove_dataset_nav_doc_sync | ||
|
|
||
| remove_dataset_nav_doc_sync(tenant_id, doc["kb_id"], doc["id"]) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Await navigation cleanup instead of starting a nested event loop.
Line 1140 calls a sync wrapper from async def rerun_agent; its run_until_complete() fails under Quart’s active event loop and is swallowed, leaving stale navigation records. Import remove_dataset_nav_doc and await it directly.
Proposed fix
-from rag.advanced_rag.knowlege_compile.dataset_nav import remove_dataset_nav_doc_sync
+from rag.advanced_rag.knowlege_compile.dataset_nav import remove_dataset_nav_doc
-remove_dataset_nav_doc_sync(tenant_id, doc["kb_id"], doc["id"])
+await remove_dataset_nav_doc(tenant_id, doc["kb_id"], doc["id"])📝 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.
| from rag.advanced_rag.knowlege_compile.dataset_nav import remove_dataset_nav_doc_sync | |
| remove_dataset_nav_doc_sync(tenant_id, doc["kb_id"], doc["id"]) | |
| from rag.advanced_rag.knowlege_compile.dataset_nav import remove_dataset_nav_doc | |
| await remove_dataset_nav_doc(tenant_id, doc["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 `@api/apps/restful_apis/agent_api.py` around lines 1138 - 1140, Update the
async rerun_agent flow to import remove_dataset_nav_doc instead of
remove_dataset_nav_doc_sync, then await remove_dataset_nav_doc with the existing
tenant_id, doc["kb_id"], and doc["id"] arguments so cleanup runs on Quart’s
active event loop.
| best_name = child_name | ||
| best_parent = best.get("parent_kwd", best_parent) | ||
| sim = child_sim | ||
| best = child |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Keep the selected child’s actual parent.
Line 471 reads best before it is updated to child, so it stores the grandparent after a multi-level descent. The _MIN_SIM path then creates the new cluster under that wrong ancestor.
Proposed fix
- best_name = child_name
- best_parent = best.get("parent_kwd", best_parent)
+ best_parent = child.get("parent_kwd") or best_name
+ best_name = child_name
sim = child_sim
best = child📝 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.
| best_name = child_name | |
| best_parent = best.get("parent_kwd", best_parent) | |
| sim = child_sim | |
| best = child | |
| best_parent = child.get("parent_kwd") or best_name | |
| best_name = child_name | |
| sim = child_sim | |
| best = child |
🤖 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 470 - 473,
Update the child-selection assignment in the descent logic so best_parent is
taken from the selected child rather than the previous best node. In the block
assigning best_name, best_parent, sim, and best, read child’s parent_kwd with
the existing fallback behavior before or while updating best, ensuring _MIN_SIM
creates the cluster under the child’s actual parent at every nesting level.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17345 +/- ##
=======================================
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:
|
What problem does this PR solve?
This PR fixes several issues in knowledge compilation navigation, especially stale navigation nodes after document reparse, incorrect PageIndex navigation generation, Infinity compatibility problems, and frontend rendering of empty navigation branches.
Detailed fixes
Fix stale parent clusters after document deletion or reparse.
nav_docbefore deleting all rows with the document'sdoc_id.doc_ids_kwdanddoc_count_int.Serialize navigation updates safely.
nav_doclookup and replacement while holding the dataset navigation lock.Improve Infinity navigation queries.
compile_kwdin KNN result fields.compile_kwd,type_kwd, andparent_kwdconditions.Fix PageIndex navigation generation.
page_indexcompilation keyword.timelinekeyword for existing data generated by older versions.Fix frontend navigation tree rendering.
has_childrenfrom the backend.Type of change