Repository navigation
Description
Backend: Ratify and harden the node deletion strategy (atomic subtree CASCADE over has_child edges)
Problem
Node deletion performs a CASCADE — deleting a node deletes its entire subtree — but this has never been an explicit, documented decision, and the current implementation has correctness gaps under the edge-based hierarchy and OCC write model.
Correction to the original draft. The earlier draft framed the fix around a self-referential
parent_idcolumn and a SQLFOREIGN KEY (parent_id) REFERENCES nodes(id) ON DELETE CASCADE, plus an "ORPHAN/PROMOTE to root viaparentId = null" alternative. None of that matches the current architecture. Per ADR-024 (Parent-Child as Operation Parameters) there is NOparent_idcolumn on thenodetable — hierarchy ishas_childrows in therelationshiptable. The draft's SQL-FK framing is obsolete; this rewrite replaces it.
What actually happens today (verified)
- The
nodetable (packages/core/src/db/schema.sql) has no parent column. Parent→child is arelationshiprow withrelationship_type = 'has_child'. - The
relationshipandembeddingtables DO haveON DELETE CASCADEFKs onnode(id)— so deleting onenoderow auto-cleans that node's edges/embeddings, per row, not for a subtree. - Subtree cascade is application-level recursion:
NodeService::delete_node(crud.rs:~1242) doesget_children(node_id)(ahas_childquery) then recursivelydelete_node(child)per child, then deletes the node viadelete_with_version_check(OCC). Each level emits its ownNodeDeletedevent. delete_node_cascade_atomic(sqlite_store.rs:~769) is misnamed — it just calls single-nodedelete_node; it is NOT atomic over a subtree.
So this is NOT "undefined behavior" — it's CASCADE-by-app-recursion, never ratified, and not transactionally atomic.
The real defects
- Non-atomic subtree delete (TOCTOU / partial-failure). N separate writes across N recursion levels, not one transaction. A mid-cascade failure or version conflict on any descendant aborts after some descendants are gone — a partially-deleted subtree. Same class as the B8 bug (fix(core): close TOCTOU in bulk_update via SQL COALESCE, document bulk_create_hierarchy contract #1262); fix with the atomic-transaction pattern (C3c C3c: Atomic child-transfer-on-split — single MoveChildrenToParent RPC (all-or-nothing) #1275,
update_nodes_bulk_atomic). - OCC is per-descendant, which is wrong for a cascade. Every recursive
delete_nodere-checks each child'sversion; a concurrent edit to any descendant raisesVersionConflictand aborts mid-subtree. Per ADR-026, OCC should guard the user-initiated target at its expected version, not impose an independent check on every descendant the user never read. - No confirmation, no descendant count (verified). No frontend delete path (
reactive-node-service.svelte.ts:645/1278→shared-node-store.deleteNode:1703→backendAdapter.deleteNode) shows a "delete N descendants" prompt. The store drops only the target; descendants are cleaned only as their individualNodeDeletedevents arrive. Permanent, silent, multi-node data loss on one click.
Decision
Default = atomic CASCADE. Deleting a node deletes its entire has_child subtree in a single transaction, gated behind a frontend confirmation showing the descendant count.
Alternative = PROMOTE (re-parent), DEFERRED to a follow-up. "Delete node, keep children" re-parents the target's direct children to the target's parent (grandparent) by rewriting has_child edges — NOT "promote to root / parentId = null" as the old draft said. The Backspace-merge path (reactive-node-service.svelte.ts:~1157, promoteChildren) already implements this re-parenting and is the model to generalize. Out of scope here; track separately.
Rationale
- CASCADE is the least-surprising default for a tree and is already the de-facto behavior — we're ratifying + hardening, not changing semantics.
- A confirmation dialog (with count) mitigates permanent loss; soft-delete/trash is a future enhancement (
node.lifecycle_statusalready exists for it — do NOT build it here). - ADR-024: stay edge-native — cascade walks
has_child, never a column. - ADR-026 (+ C5 amendment): deletion is a versioned write; the daemon is the OCC adjudicator returning structured
VERSION_CONFLICT. OCC guards the target; the subtree delete is all-or-nothing in one transaction so a conflict can't leave a half-deleted tree. - ADR-031: deletion logic lives in daemon/core; the frontend stays thin (confirmation UX + event-driven reconciliation).
Backend work (packages/core)
- Make subtree cascade atomic. Replace the per-child recursive loop in
delete_nodewith a single-transaction subtree delete: collect the full descendant set by walkinghas_childfrom the target before mutating; in onestore.transaction()(mirrorupdate_nodes_bulk_atomic,sqlite_store.rs:~1611), OCC-check the target atexpected_version, thenDELETE FROM node WHERE id IN (target + descendants)— relationship/embedding FK CASCADE cleans every edge/embedding for the set. Commit once. Target version mismatch → roll back, returnVersionConflict(ADR-026 C5 pipeline). Repurpose/renamedelete_node_cascade_atomicso the name is truthful; delete the dead recursive path (no compat shims — greenfield). - Event emission: emit one
NodeDeletedevent per node in the deleted set (target + every descendant) after commit, so every client's store +structureTreereconcile each removed node. (Do NOT collapse to a single event — the frontend keys cleanup off per-node deletions; a single target-only event would orphan descendants in the UI.) - OCC semantics: version-check only the user-initiated target; descendants are removed unconditionally inside the same transaction.
- RPC/daemon: keep the
(node_id, expected_version)delete signature; return the count of deleted nodes.VERSION_CONFLICTvia the establishedCode::Aborted+x-version-conflictpath.
Frontend work (packages/desktop-app)
- Confirmation dialog: before deleting a node with children, fetch the descendant count (
backendAdapter.getDescendants/ store child cache) and show "Delete node and N descendants? This cannot be undone." Default: prompt only whenN > 0. Wire at thereactive-node-servicedelete entry points (645 viewer-driven, 1278 direct) — NOT insideshared-node-store.deleteNode(keep it a pure mutation). - Event-driven cleanup: rely on the per-descendant
NodeDeletedevents throughtauri-sync-listener.ts/browser-sync-service.ts→sharedNodeStore.deleteNode(id, …, skipPersistence=true)to evict every descendant and prunestructureTree. Verify no descendant dangles after a cascade. createLogger, noconsole.*; noany.
ADR deliverable
Add a new ADR — "Node Deletion Strategy" to nodespace-docs on a doc/ branch (new ADR, not an amendment — deletion semantics aren't owned by 024/026/031, though it cites all three). Record: edge-native subtree cascade (ADR-024), atomic single-transaction delete with target-only OCC + conflict pipeline (ADR-026+C5), daemon ownership + thin-client UX (ADR-031), the confirmation mitigation, and PROMOTE + soft-delete as explicitly deferred. Note: branch the new ADR from main in nodespace-docs (git checkout main there first).
Acceptance criteria
-
delete_nodedeletes target + entirehas_childsubtree in a single transaction; relationship/embedding rows for the whole set are gone. - Mid-operation failure or target version conflict leaves the subtree fully intact (no partial deletion) — verified by test.
- OCC guards only the target; concurrent descendant edits do not abort the cascade.
- One
NodeDeletedevent per deleted node; frontend store +structureTreefully reconciled (no orphaned descendants in UI). - Frontend shows "Delete node and N descendants?" when
N > 0; cancel aborts with no mutation. -
delete_node_cascade_atomicis genuinely atomic or removed; no misleading/dead delete paths remain. - New "Node Deletion Strategy" ADR merged in
nodespace-docs.
Testing
- Cascade correctness: delete a multi-level subtree; assert all node/
has_child/embeddingrows for the set removed, nothing outside it. - Atomicity: inject a mid-delete failure or simulate target conflict; assert ZERO rows deleted (no partial subtree).
bun run test:dbfor full SQLite integration + a Rust transaction test in core. - OCC: stale target version →
VERSION_CONFLICT+ intact subtree; concurrent descendant edit → cascade still succeeds. - Confirmation UX: dialog shows correct count; cancel = no-op; confirm = delete. Happy-DOM for logic;
bun run test:browseronly if real click needed. - Event-driven cleanup: after cascade,
structureTree+ store contain none of the deleted ids.
Risks
- Permanent data loss — the point of the confirmation + count. Soft-delete deferred (
lifecycle_statusexists for it). - Hierarchy integrity (Delete obsolete cache management code from SharedNodeStore #557 class) — a botched cascade could strand edges/descendants; single-transaction + FK-CASCADE design + atomicity tests guard it.
- Event volume on large subtrees (one event/node) — acceptable; matches how the frontend reconciles. Batch only if profiling demands (out of scope).
Standard NodeSpace startup / PR sequence
git status + git pull origin main on primary, EnterWorktree({name: "issue-220-node-deletion-strategy"}), bun install, bun run test baseline, gh:comment/gh:assign/gh:status. ADR goes in nodespace-docs on a doc/ branch (branch from main). Before PR: bun run test:all + bun run test:db (atomicity/cascade integration), bun run quality:fix + commit, bun run gh:pr 220, /pragmatic-code-review, then ExitWorktree + gh pr merge --squash --delete-branch.
Activity
refactor: Apply all code review improvements to database persistence …
feat: Session 3 - Section 7: Database Persistence Tests (9 tests, 100…
feat: Session 3 - Section 7: Database Persistence Tests (9 tests, 100…
feat: Session 3 - Section 7: Database Persistence Tests (9 tests, 100…
feat: Session 3 - Section 7: Database Persistence Tests (9 tests, 100…
[-]Backend: Define and document CASCADE deletion strategy for parent nodes[/-][+]Ratify & harden node deletion strategy: atomic subtree CASCADE over has_child edges (+ confirmation + ADR)[/+]malibio commentedon May 30, 2026
Frontend baseline: 132 files, 3833 tests passed (worktree: issue-220-node-deletion-strategy)
Ratify & harden node deletion strategy: atomic subtree CASCADE over h…
Ratify & harden node deletion strategy: atomic subtree CASCADE over h…