Skip to content

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

Closed

Description

@malibio

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_id column and a SQL FOREIGN KEY (parent_id) REFERENCES nodes(id) ON DELETE CASCADE, plus an "ORPHAN/PROMOTE to root via parentId = null" alternative. None of that matches the current architecture. Per ADR-024 (Parent-Child as Operation Parameters) there is NO parent_id column on the node table — hierarchy is has_child rows in the relationship table. The draft's SQL-FK framing is obsolete; this rewrite replaces it.

What actually happens today (verified)

  • The node table (packages/core/src/db/schema.sql) has no parent column. Parent→child is a relationship row with relationship_type = 'has_child'.
  • The relationship and embedding tables DO have ON DELETE CASCADE FKs on node(id) — so deleting one node row 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) does get_children(node_id) (a has_child query) then recursively delete_node(child) per child, then deletes the node via delete_with_version_check (OCC). Each level emits its own NodeDeleted event.
  • delete_node_cascade_atomic (sqlite_store.rs:~769) is misnamed — it just calls single-node delete_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

  1. 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).
  2. OCC is per-descendant, which is wrong for a cascade. Every recursive delete_node re-checks each child's version; a concurrent edit to any descendant raises VersionConflict and 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.
  3. 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 individual NodeDeleted events 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_status already 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)

  1. Make subtree cascade atomic. Replace the per-child recursive loop in delete_node with a single-transaction subtree delete: collect the full descendant set by walking has_child from the target before mutating; in one store.transaction() (mirror update_nodes_bulk_atomic, sqlite_store.rs:~1611), OCC-check the target at expected_version, then DELETE 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, return VersionConflict (ADR-026 C5 pipeline). Repurpose/rename delete_node_cascade_atomic so the name is truthful; delete the dead recursive path (no compat shims — greenfield).
  2. Event emission: emit one NodeDeleted event per node in the deleted set (target + every descendant) after commit, so every client's store + structureTree reconcile 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.)
  3. OCC semantics: version-check only the user-initiated target; descendants are removed unconditionally inside the same transaction.
  4. RPC/daemon: keep the (node_id, expected_version) delete signature; return the count of deleted nodes. VERSION_CONFLICT via the established Code::Aborted + x-version-conflict path.

Frontend work (packages/desktop-app)

  1. 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 when N > 0. Wire at the reactive-node-service delete entry points (645 viewer-driven, 1278 direct) — NOT inside shared-node-store.deleteNode (keep it a pure mutation).
  2. Event-driven cleanup: rely on the per-descendant NodeDeleted events through tauri-sync-listener.ts / browser-sync-service.ts → sharedNodeStore.deleteNode(id, …, skipPersistence=true) to evict every descendant and prune structureTree. Verify no descendant dangles after a cascade.
  3. createLogger, no console.*; no any.

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_node deletes target + entire has_child subtree 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 NodeDeleted event per deleted node; frontend store + structureTree fully reconciled (no orphaned descendants in UI).
  • Frontend shows "Delete node and N descendants?" when N > 0; cancel aborts with no mutation.
  • delete_node_cascade_atomic is 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/embedding rows 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:db for 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:browser only 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_status exists 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

  1. changed the title [-]Backend: Define and document CASCADE deletion strategy for parent nodes[/-] [+]Ratify & harden node deletion strategy: atomic subtree CASCADE over has_child edges (+ confirmation + ADR)[/+] on May 30, 2026
  2. malibio commented on May 30, 2026

    @malibio
    CollaboratorAuthor

    Frontend baseline: 132 files, 3833 tests passed (worktree: issue-220-node-deletion-strategy)

  3. self-assigned this
    on May 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions