Repository navigation
fix: delete navigation subtrees correctly - #17434
Conversation
📝 WalkthroughWalkthrough
ChangesNavigation deletion
Estimated code review effort: 4 (Complex) | ~45 minutes Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 2
🧹 Nitpick comments (1)
api/apps/services/dataset_api_service.py (1)
2724-2777: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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 finaldeletedcount 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
📒 Files selected for processing (1)
api/apps/services/dataset_api_service.py
| # 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) |
There was a problem hiding this comment.
🗄️ 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.
| 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 |
There was a problem hiding this comment.
🎯 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 += 1This 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
wangq8
left a comment
There was a problem hiding this comment.
Thanks for this fix — it addresses several real issues in the navigation tree deletion.
What works well:
-
name.keywordfor Elasticsearch/OpenSearch: Correct fix. Thenamefield is text-analyzed in ES, so searching bynamewould tokenize the value and potentially match partial/substring hits. Usingname.keywordensures exact matching. The fallback for Infinity (scalar varchar) is handled cleanly. -
Lock serialization: Reusing
_nav_lock_key,_LOCK_TIMEOUT_S, and_LOCK_BLOCKING_TIMEOUT_Sfromdataset_nav.pyfollows the existing pattern used by other nav operations. Good. -
ID-based collection instead of name-based: Collecting descendants by stable
idvalues (stored in document fields) avoids the risk of name collisions from malformed or legacy data. Theparent_kwdtraversal still uses names, which is correct sinceparent_kwdstores parent names, not IDs. -
Reusing
_remove_dataset_nav_doc_lockedfornav_docrows: Much better than a raw delete — this properly updates parent clusters and cleans empty ancestors. -
Cascade cleanup: Cluster rows are deleted by
idafter processing all childnav_docentries, 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.
What problem does this PR solve?
Fix navigation node deletion for Elasticsearch and Infinity.
name.keywordfor exact Elasticsearch node matching.Type of change