Skip to content

fix: stabilize knowledge compilation navigation updates - #17345

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
buua436:b122
Jul 24, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
buua436:b122

Conversation

@buua436

@buua436 buua436 commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

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.

    • Remove the document's nav_doc before deleting all rows with the document's doc_id.
    • Update the parent cluster's doc_ids_kwd and doc_count_int.
    • Delete empty clusters and recursively clean up empty ancestors.
    • Apply the same cleanup to normal document deletion, document reparse, and pipeline rerun paths.
    • This prevents parent clusters from remaining after their child document has been deleted.
  • Serialize navigation updates safely.

    • Perform existing nav_doc lookup and replacement while holding the dataset navigation lock.
    • Prevent concurrent document updates from racing during delete, cluster placement, and parent updates.
    • Add visited-node protection to prevent recursive navigation traversal from entering self-referencing loops.
  • Improve Infinity navigation queries.

    • Preserve and validate compile_kwd in KNN result fields.
    • Add exact matching for compile_kwd, type_kwd, and parent_kwd conditions.
    • Filter and re-rank fallback KNN results after scanning to ensure only navigation rows are selected.
    • Handle empty list values safely during Infinity updates.
    • Run blocking navigation delete/search operations through the thread pool from async APIs.
  • Fix PageIndex navigation generation.

    • Resolve PageIndex structures using the page_index compilation keyword.
    • Keep a fallback to the legacy timeline keyword for existing data generated by older versions.
    • Pass the embedding and chat models into tree and compiler navigation generation so documents can be embedded and clustered correctly.
  • Fix frontend navigation tree rendering.

    • Preserve has_children from the backend.
    • Render expandable navigation nodes even when the current children array is empty.
    • Avoid treating an expandable cluster as a document just because its children have not been loaded yet.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • Refactor (internal concurrency and storage handling)

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9663deb0-1d3a-4b25-8dff-573cf2b0cd3d

📥 Commits

Reviewing files that changed from the base of the PR and between 792ef80 and a867043.

📒 Files selected for processing (1)
  • common/doc_store/infinity_conn_base.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • common/doc_store/infinity_conn_base.py

📝 Walkthrough

Walkthrough

Dataset 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.

Changes

Dataset navigation and storage

Layer / File(s) Summary
Navigation document cleanup
api/apps/restful_apis/..., api/db/services/document_service.py, rag/advanced_rag/knowlege_compile/dataset_nav.py
Document rerun and deletion flows remove dataset-navigation records, while locked cascade cleanup updates parent clusters and removes empty ancestors.
Navigation placement and graph rebuilding
rag/advanced_rag/knowlege_compile/dataset_nav.py, rag/advanced_rag/knowlege_compile/runner.py, rag/flow/compiler/compiler.py, rag/svr/task_executor_refactor/chunk_post_processor.py
KNN results are revalidated against filters, cluster traversal avoids revisits, page-index summaries fall back to timeline summaries, and model handles are passed into navigation upserts.
Navigation deletion and query predicates
api/apps/services/dataset_api_service.py, common/doc_store/infinity_conn_base.py
Navigation type values are normalized, doc-store searches and deletes run through the thread pool, and navigation fields generate escaped exact-match predicates.
Infinity operation resilience
common/doc_store/infinity_conn_base.py, rag/utils/infinity_conn.py
Resource-busy metadata operations use bounded exponential retries, and empty-list update values are converted or omitted by field type.
Navigation tree rendering
web/src/components/ui/tree-view.tsx, web/src/pages/dataset/compilation/utils/nav-tree.ts
Tree data carries explicit child-state metadata, and rendering honors hasChildren with normalized child arrays.

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
Loading

Possibly related PRs

Suggested labels: 🌈 python, ☯️ refactor, ♾️infinity

Poem

I’m a rabbit guarding the navigation tree,
Locking each branch quite carefully.
Empty lists hop safely away,
Old docs vanish before rerun day.
New leaves know when children hide—
Binky, binky, data-wide! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 69.23% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: stabilizing knowledge compilation navigation updates.
Description check ✅ Passed The description covers the problem, key fixes, and change type, which is sufficient despite using a different heading than the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@buua436
buua436 requested a review from wangq8 July 24, 2026 08:17
@buua436
buua436 marked this pull request as ready for review July 24, 2026 08:17
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 24, 2026
@yingfeng yingfeng added the ci Continue Integration label Jul 24, 2026

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this comprehensive fix! I reviewed the diff carefully and the changes look solid overall. A few observations:

✅ Good changes

  1. 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.

  2. visited_names protection in _find_best_cluster — prevents infinite recursion when cluster parent references form a cycle. Clean and minimal.

  3. _remove_dataset_nav_doc_locked extraction — reduces duplication between the async remove_dataset_nav_doc and the inline removal inside upsert_dataset_nav_doc. Both callers hold the lock as documented.

  4. PageIndex keyword fix in runner.py — trying page_index first, falling back to timeline for legacy data is the right approach for backward compatibility.

  5. Empty list handling in infinity_conn.py update() — the Infinity Python client indeed crashes on empty lists during value inspection. Converting to empty JSON/empty string for known field types is correct.

  6. _store_knn re-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_condition helper is focused on the simple equality filters used by nav queries.

  7. Exact matching for compile_kwd, type_kwd, parent_kwd in infinity_conn_base.py — these keyword fields need = comparison, not json_contains, and this is also more efficient.

  8. Frontend hasChildren — differentiating "no children loaded yet" from "leaf node" is the correct fix for expandable clusters showing as documents.

  9. remove_dataset_nav_doc_sync before chunk deletion in document_service.py — the nav_doc row needs to exist for the parent cluster lookup, so it must be processed before the broad doc_id delete.

  10. Passing embd_mdl/chat_mdl in compiler.py and chunk_post_processor.py — these call sites were missing the model parameters needed for doc embedding and cluster summary generation.

⚠️ Minor suggestions (non-blocking)

  • _matches_condition string comparison: comparing via str(value) == str(item) is a bit loose but works for the controlled nav field values. Not a blocker.

  • _store_knn fallback 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! 🚀

@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

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 win

Validate retry bounds before entering the retry loop.

_int_env accepts INFINITY_META_RETRY_MAX=0 or negative values, causing _retry_on_meta_contention to skip the operation and fail at the assertion. Negative delay values can also make time.sleep raise, 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 win

Add focused tests for the hasChildren contract.

Cover parent and child nodes with: has_children: true and 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 win

Log 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

📥 Commits

Reviewing files that changed from the base of the PR and between 008fa3e and 792ef80.

📒 Files selected for processing (12)
  • api/apps/restful_apis/agent_api.py
  • api/apps/restful_apis/document_api.py
  • api/apps/services/dataset_api_service.py
  • api/db/services/document_service.py
  • common/doc_store/infinity_conn_base.py
  • rag/advanced_rag/knowlege_compile/dataset_nav.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/flow/compiler/compiler.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py
  • rag/utils/infinity_conn.py
  • web/src/components/ui/tree-view.tsx
  • web/src/pages/dataset/compilation/utils/nav-tree.ts

Comment on lines +1138 to +1140
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"])

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 | 🟠 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.

Suggested change
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.

Comment on lines +470 to 473
best_name = child_name
best_parent = best.get("parent_kwd", best_parent)
sim = child_sim
best = child

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 | 🟠 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.

Suggested change
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

codecov Bot commented Jul 24, 2026

Copy link
Copy Markdown

Codecov Report

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

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.
📢 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants