Skip to content

fix: delete navigation subtrees correctly - #17434

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b124
Jul 27, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b124

Conversation

@buua436

@buua436 buua436 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fix navigation node deletion for Elasticsearch and Infinity.

  • Use name.keyword for exact Elasticsearch node matching.
  • Recursively collect and delete the selected node’s subtree.
  • Reuse existing document removal logic to update parent clusters and clean empty ancestors.
  • Delete cluster rows by stable IDs to avoid name collisions.
  • Serialize deletion with the dataset navigation lock.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@buua436 buua436 added the ci Continue Integration label Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

delete_nav_node now locks dataset navigation, discovers the target subtree by stable IDs with doc-store-specific name fields, removes document leaves through the shared locked helper, and bulk-deletes cluster rows by ID with consolidated error handling.

Changes

Navigation deletion

Layer / File(s) Summary
Locking and target discovery
api/apps/services/dataset_api_service.py
delete_nav_node acquires a Redis navigation lock, searches rows through the thread pool, and resolves the target using doc-store-specific name fields with a fallback mapping.
Stable subtree collection and removal
api/apps/services/dataset_api_service.py
Descendants are traversed through parent_kwd and keyed by stable IDs; nav_doc rows use _remove_dataset_nav_doc_locked, while nav_cluster rows are bulk-deleted by ID with guarded lock release and error handling.

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

Suggested reviewers: wangq8, euvre, kevinhush

Poem

A rabbit guards the nav-tree gate,
With Redis locks, it waits in state.
IDs hop down each branching track,
Doc leaves vanish, clusters stack.
The lock lets go when work is through—
“A tidy burrow!” squeaks the crew.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title is concise and accurately reflects the main change to navigation subtree deletion.
Description check ✅ Passed It covers the problem, fix, and change type; only the template's Summary heading is named differently.

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 marked this pull request as ready for review July 27, 2026 09:58
@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 27, 2026
@buua436
buua436 requested a review from wangq8 July 27, 2026 09:59
@buua436
buua436 marked this pull request as draft July 27, 2026 09:59
@buua436
buua436 marked this pull request as ready for review July 27, 2026 09:59

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

2724-2777: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add success-path logging for this new locked deletion flow.

The function only logs on exceptions (Lines 2721, 2775, 2780). Given the traversal is bounded (range(64) depth, 10000-row page size per search) and can silently stop expanding without any indication, an info/debug log of rows discovered, depth reached, and final deleted count would materially help diagnose incomplete deletions or truncated traversals in production. As per coding guidelines, "Add logging for new flows" for **/*.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 `@api/apps/services/dataset_api_service.py` around lines 2724 - 2777, Add
success-path logging to the locked deletion flow around the traversal and
deletion logic, recording the number of rows discovered, the traversal depth
reached, and the final deleted count. Track the actual depth completed from the
existing range(64) loop and emit an info/debug log before the successful return,
while preserving the existing exception logging and deletion 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/services/dataset_api_service.py`:
- Around line 2736-2753: Replace the name-only descendant traversal in the
dataset deletion flow with stable parent-ID propagation. Update the row model
and _remove_dataset_nav_doc_locked/search_rows integration so each child records
its parent’s stable ID and the BFS frontier matches that ID, while retaining
parent_kwd only as necessary for lookup compatibility. Ensure rows_by_id is
expanded only from descendants of the resolved target ID, preventing duplicate
names from merging unrelated subtrees.
- Around line 2755-2761: Update _remove_dataset_nav_doc_locked to return whether
a navigation document was actually removed, including false on its missing-row
no-op path, then increment deleted in the rows_by_id loop only when that return
value indicates removal. Preserve the existing cleanup behavior and API response
while preventing counts for nonexistent documents.

---

Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 2724-2777: Add success-path logging to the locked deletion flow
around the traversal and deletion logic, recording the number of rows
discovered, the traversal depth reached, and the final deleted count. Track the
actual depth completed from the existing range(64) loop and emit an info/debug
log before the successful return, while preserving the existing exception
logging and deletion 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: 60b3ada4-e7a3-43a5-b68e-6b0f39eadc2c

📥 Commits

Reviewing files that changed from the base of the PR and between 19d861b and 298f8fa.

📒 Files selected for processing (1)
  • api/apps/services/dataset_api_service.py

Comment on lines +2736 to +2753
# Collect the target and descendants by stable row IDs, not by names.
# Names are display values and may collide across malformed/old data.
rows_by_id = {row.get("id"): row for row in rows if row.get("id")}
frontier = [row.get("name") for row in rows if row.get("name")]
for _ in range(64):
if not frontier:
break
children = await search_rows(
{"compile_kwd": [_NAV_COMPILE_KWD], "parent_kwd": frontier},
[],
OrderByExpr(),
0,
10000,
)
frontier = []
for child in children:
row_id = child.get("id")
child_name = child.get("name")
if row_id and row_id not in rows_by_id:
rows_by_id[row_id] = child
if child_name:
frontier.append(child_name)

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 | 🔴 Critical | 🏗️ Heavy lift

Descendant BFS still keys off name, reintroducing the collision this PR is meant to fix.

frontier is built from row.get("name") and children are discovered via {"parent_kwd": frontier} (Lines 2739, 2743-2745). Per _remove_dataset_nav_doc_locked (cluster_id = _nav_cluster_id(kb_id, parent_name)), parent_kwd stores the parent's name, not a stable id. So if two distinct nodes anywhere in the dataset's nav tree share the same name, searching parent_kwd: [name] will pull in children of both nodes, merging an unrelated subtree into rows_by_id for deletion. The final cluster delete is correctly scoped by id (Lines 2763-2771), but that only protects the last step — the traversal that decides which ids belong to the target subtree is still name-based and can silently delete unrelated content. This directly undermines the PR's stated goal of using stable ids to avoid name collisions.

🛠️ Suggested direction

Store/propagate a stable parent-id alongside parent_kwd (or derive full ancestor id-paths during traversal) so descendant expansion can be scoped to the resolved target id(s) rather than raw names. This likely requires a schema/field addition in dataset_nav.py's row model, so treat as a follow-up hardening task rather than a one-line patch.

🤖 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 2736 - 2753, Replace
the name-only descendant traversal in the dataset deletion flow with stable
parent-ID propagation. Update the row model and
_remove_dataset_nav_doc_locked/search_rows integration so each child records its
parent’s stable ID and the BFS frontier matches that ID, while retaining
parent_kwd only as necessary for lookup compatibility. Ensure rows_by_id is
expanded only from descendants of the resolved target ID, preventing duplicate
names from merging unrelated subtrees.

Comment on lines +2755 to +2761
deleted = 0
# Reuse the existing document-removal path so direct parents are
# updated and empty ancestor clusters are cleaned consistently.
for row in rows_by_id.values():
if row.get("type_kwd") == "nav_doc" and row.get("doc_id"):
await _remove_dataset_nav_doc_locked(tenant_id, dataset_id, row["doc_id"])
deleted += 1

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

deleted count can be inflated when the doc row no longer exists.

_remove_dataset_nav_doc_locked returns None unconditionally, including on its early-return no-op path when doc_row is missing. deleted += 1 here doesn't verify anything was actually removed, so the API's {"deleted": n} response can overstate the real deletion count.

♻️ Suggested fix
-        for row in rows_by_id.values():
-            if row.get("type_kwd") == "nav_doc" and row.get("doc_id"):
-                await _remove_dataset_nav_doc_locked(tenant_id, dataset_id, row["doc_id"])
-                deleted += 1
+        for row in rows_by_id.values():
+            if row.get("type_kwd") == "nav_doc" and row.get("doc_id"):
+                if await _remove_dataset_nav_doc_locked(tenant_id, dataset_id, row["doc_id"]):
+                    deleted += 1

This requires _remove_dataset_nav_doc_locked (in dataset_nav.py) to return a boolean/removed-count instead of None.

🤖 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 2755 - 2761, Update
_remove_dataset_nav_doc_locked to return whether a navigation document was
actually removed, including false on its missing-row no-op path, then increment
deleted in the rows_by_id loop only when that return value indicates removal.
Preserve the existing cleanup behavior and API response while preventing counts
for nonexistent documents.

@codecov

codecov Bot commented Jul 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (19d861b) to head (298f8fa).
⚠️ Report is 2 commits behind head on main.

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

@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 fix — it addresses several real issues in the navigation tree deletion.

What works well:

  1. name.keyword for Elasticsearch/OpenSearch: Correct fix. The name field is text-analyzed in ES, so searching by name would tokenize the value and potentially match partial/substring hits. Using name.keyword ensures exact matching. The fallback for Infinity (scalar varchar) is handled cleanly.

  2. Lock serialization: Reusing _nav_lock_key, _LOCK_TIMEOUT_S, and _LOCK_BLOCKING_TIMEOUT_S from dataset_nav.py follows the existing pattern used by other nav operations. Good.

  3. ID-based collection instead of name-based: Collecting descendants by stable id values (stored in document fields) avoids the risk of name collisions from malformed or legacy data. The parent_kwd traversal still uses names, which is correct since parent_kwd stores parent names, not IDs.

  4. Reusing _remove_dataset_nav_doc_locked for nav_doc rows: Much better than a raw delete — this properly updates parent clusters and cleans empty ancestors.

  5. Cascade cleanup: Cluster rows are deleted by id after processing all child nav_doc entries, which is the right order.

One observation (non-blocking): The rows_by_id filter uses if row.get("id"), which will skip any legacy records missing the id field. The id field has been part of nav documents for a while, so this should be fine in practice, but worth being aware of when deploying to environments with very old nav data.

Overall looks solid.

@wangq8
wangq8 merged commit 5bfd59f into infiniflow:main Jul 27, 2026
3 checks passed
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.

2 participants