Skip to content

Ratify & harden node deletion strategy: atomic subtree CASCADE over has_child edges (+ confirmation + ADR) - #1280

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-220-node-deletion-strategy
May 30, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-220-node-deletion-strategy

Conversation

@malibio

@malibio malibio commented May 30, 2026

Copy link
Copy Markdown
Collaborator

Closes #220

Backend (packages/core, packages/daemon, packages/proto):
- Replace per-child recursive delete loop with SqliteStore::delete_subtree_atomic:
  single transaction, WITH RECURSIVE descendant collection, OCC check on target
  only, DELETE FROM node WHERE id IN (...), FK CASCADE cleans edges/embeddings,
  emits one NodeDeleted notification per deleted node after commit
- delete_node_cascade_atomic removed (was never atomic — dead stub)
- NodeService::delete_node now returns DeleteResult { existed, deleted_count }
- Proto DeleteNodeResponse gains deleted_count: uint64
- Daemon and Tauri command propagate deleted_count through
- 4 new Rust tests: cascade correctness, atomicity on version conflict, OCC guards
  target-only, idempotent missing-node

Frontend (packages/desktop-app):
- DeleteResult interface updated to { existed, deletedCount }
- delete-confirmation.svelte.ts: promise-based confirmation service using $state
- delete-confirmation-modal.svelte: "Delete N descendants?" modal, mounted globally
  in +layout.svelte
- ReactiveNodeService::deleteNode now async: fetches descendant count, shows
  confirmation for N > 0, aborts on cancel
- Tests updated: deleteNode calls awaited, DeleteResult mock shape updated

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 30, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

PR #1280 is a well-scoped, architecturally sound change that delivers on the core promise: replace non-atomic recursive deletion with a single-transaction subtree CASCADE, gate it behind a frontend confirmation dialog, and document the decision in an ADR. The Rust backend work is particularly solid — the dual OCC check (pre-check + re-check inside the transaction) is the correct pattern, the test suite covers all four acceptance-criteria scenarios, and the proto field addition is backward-compatible. This is a net improvement and approaches merge-ready, with two issues to address before landing.


Findings

[Improvement] Modal keyboard shortcuts broken: inner onkeydown stops Escape/Enter from reaching the overlay handler

packages/desktop-app/src/lib/components/delete-confirmation-modal.svelte lines 17–27

The handleKeydown listener that maps Escape → cancel and Enter → confirm is attached to the overlay backdrop (which has tabindex="-1"). The inner modal <div> has onkeydown={(e) => e.stopPropagation()}, so any keydown event fired while the modal itself has focus never bubbles to the overlay. Since neither element receives autofocus, keyboard shortcuts are silently inert in the common case. Fix: move handleKeydown to the inner modal <div> (replacing the stopPropagation-only handler there), and keep stopPropagation on the outer overlay so underlying editor shortcuts don't fire through the backdrop.

[Improvement] Test gap: the confirmation dialog path (descendants > 0) and the cancel path are untested

packages/desktop-app/src/tests/services/reactive-node-service.test.ts

The mock for backendAdapter.getDescendants always returns [], so confirmNodeDeletion is always called with 0 and returns true immediately — the dialog is never shown in any test. The cancel branch (confirmed === false) is also never reached. The acceptance criterion explicitly calls for a "Cancel = no-op" test. Two tests are needed:

  1. Mock getDescendants to return [fakeNode]; mock confirmNodeDeletion (or the delete-confirmation.svelte module) to resolve false; assert events.nodeDeleted is not called.
  2. Same setup, resolve true; assert deletion proceeds normally.

[Improvement] Module-level _pending singleton drops a concurrent Promise

packages/desktop-app/src/lib/services/delete-confirmation.svelte.ts lines 24–26

If two deleteNode calls with descendantCount > 0 are in-flight simultaneously (e.g., rapid keyboard triggers before the first dialog dismisses), the second call overwrites _pending, permanently orphaning the first Promise's resolve callback. The first deletion hangs forever (a microtask-level memory leak). For a single-user desktop app this is an edge case, but the fix is cheap: guard with an early return if _pending !== null:

export async function confirmNodeDeletion(descendantCount: number): Promise<boolean> {
  if (descendantCount === 0) return true;
  if (_pending !== null) return false; // second concurrent call: abort silently
  ...
}

[Improvement] getDescendants in TauriAdapter is O(depth) serial IPC calls

packages/desktop-app/src/lib/services/backend-adapter.ts lines 197–211

The count fetch before showing the dialog uses a BFS that fires one get_children IPC round-trip per level of the tree. The backend already walks the full subtree with WITH RECURSIVE inside delete_subtree_atomic. A dedicated get_descendant_count or get_descendants Tauri command backed by the same CTE would collapse this to one IPC call. This is a latency concern for deep trees (e.g., large imported outlines), not a correctness issue. Acceptable to track as a follow-up issue.


Nitpicks

  • Nit delete-confirmation-modal.svelte line 18: tabindex="-1" on the overlay means it won't receive focus via Tab, so keyboard dismiss only works if the user manually clicks the backdrop first. Adding autofocus to the Cancel button (or the modal div) would make keyboard flow work naturally after the dialog appears.

  • Nit packages/core/src/services/node_service/crud.rs line 1228: splitn(3, ':') on rest (which is <uuid>:<expected>:<actual>) is correct because UUIDs contain only hex and hyphens. The comment says the format is version_conflict:<id>:<expected>:<actual> — this is accurate, but the sentinel ID parsed into parts[0] is immediately discarded in favour of the node_id function parameter. A brief inline note ("id field extracted but not used; we use the caller-supplied node_id for the error") would prevent future confusion.

  • Nit packages/core/src/db/sqlite_store.rs ~line 811: The CTE subtree collection and the SELECT * FROM node WHERE id IN (...) fetch both execute outside the transaction, before tx.begin. A concurrent create of a child node in this window would leave that child orphaned (its has_child edge is removed when the parent is deleted, but the child row itself is not). In a single-user embedded SQLite app this is a theoretical-only concern. The in-transaction version re-check correctly closes the version-conflict TOCTOU. Acceptable as-is; worth a short comment acknowledging the window.


Acceptance Criteria Check

Criterion Status
Single-transaction subtree delete PASS — delete_subtree_atomic with one tx.execute
Mid-operation failure leaves subtree intact PASS — test_delete_node_version_conflict_leaves_subtree_intact
OCC guards only target PASS — test_delete_node_occ_guards_only_target_not_descendants
One NodeDeleted event per deleted node PASS — post-commit notify loop in sqlite_store.rs
Frontend shows "Delete N descendants?" when N > 0 PARTIAL — dialog wording is correct; keyboard dismiss is broken (see above)
delete_node_cascade_atomic dead stub removed PASS — renamed and genuinely implemented
ADR merged in nodespace-docs PASS — ADR-036 committed to nodespace-docs main
Cancel = no-op (untested) MISSING — no test for cancel path

Decision: Request Changes — the keyboard handler inversion in the modal is a behavioural bug (not just a nit), and the cancel-path test gap leaves an acceptance criterion untested. Both are small fixes. Once those two items land the PR is good to merge.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review status: CHANGES REQUESTED. Two items to address before merge: (1) the modal keyboard handler is inverted — the inner modal div's onkeydown stops propagation before Escape/Enter can reach the overlay's handleKeydown; move handleKeydown to the inner modal div. (2) add a test for the cancel path (mock getDescendants to return a non-empty array, resolve confirmNodeDeletion as false, assert events.nodeDeleted is not called). Full findings in the detailed comment above.

…ests, guard concurrent confirmations

- Move onkeydown handler from overlay to inner modal div (was blocked by stopPropagation)
- Guard confirmNodeDeletion against concurrent calls (second call returns false immediately)
- Add mock for delete-confirmation.svelte in reactive-node-service tests
- Add 3 new tests: shows confirmation with N descendants, cancel aborts deletion (no mutation),
  leaf nodes skip confirmation (descendantCount=0)

Co-Authored-By: Claude <[email protected]>
@malibio
malibio merged commit 1edada1 into main May 30, 2026
@malibio
malibio deleted the worktree-issue-220-node-deletion-strategy branch May 30, 2026 18:32
malibio added a commit that referenced this pull request Jun 22, 2026
…as_child edges (+ confirmation + ADR) (#1280)

* Atomic subtree CASCADE delete with frontend confirmation (#220)

Backend (packages/core, packages/daemon, packages/proto):
- Replace per-child recursive delete loop with SqliteStore::delete_subtree_atomic:
  single transaction, WITH RECURSIVE descendant collection, OCC check on target
  only, DELETE FROM node WHERE id IN (...), FK CASCADE cleans edges/embeddings,
  emits one NodeDeleted notification per deleted node after commit
- delete_node_cascade_atomic removed (was never atomic — dead stub)
- NodeService::delete_node now returns DeleteResult { existed, deleted_count }
- Proto DeleteNodeResponse gains deleted_count: uint64
- Daemon and Tauri command propagate deleted_count through
- 4 new Rust tests: cascade correctness, atomicity on version conflict, OCC guards
  target-only, idempotent missing-node

Frontend (packages/desktop-app):
- DeleteResult interface updated to { existed, deletedCount }
- delete-confirmation.svelte.ts: promise-based confirmation service using $state
- delete-confirmation-modal.svelte: "Delete N descendants?" modal, mounted globally
  in +layout.svelte
- ReactiveNodeService::deleteNode now async: fetches descendant count, shows
  confirmation for N > 0, aborts on cancel
- Tests updated: deleteNode calls awaited, DeleteResult mock shape updated

Co-Authored-By: Claude <[email protected]>

* Address review: fix modal keyboard handling, add cancel/descendants tests, guard concurrent confirmations

- Move onkeydown handler from overlay to inner modal div (was blocked by stopPropagation)
- Guard confirmNodeDeletion against concurrent calls (second call returns false immediately)
- Add mock for delete-confirmation.svelte in reactive-node-service tests
- Add 3 new tests: shows confirmation with N descendants, cancel aborts deletion (no mutation),
  leaf nodes skip confirmation (descendantCount=0)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ratify & harden node deletion strategy: atomic subtree CASCADE over has_child edges (+ confirmation + ADR)

1 participant