Skip to content

Gate cascade delete on subtree read access (ADR-041) - #1868

Merged
malibio merged 3 commits into
mainfrom
issue-1736-access-gated-cascade-delete
Aug 1, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-1736-access-gated-cascade-delete

Conversation

@malibio

@malibio malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Adds a pre-delete access gate ahead of delete_subtree_atomic: a SubtreeAccessGate trait injected into NodeService, defaulting to AlwaysAllowGate (matches today's unconditional-cascade behavior for community/local installs — no access model exists there).
  • The subtree id walk is computed once (SqliteStore::collect_subtree_ids) and shared between the gate check and the delete itself, so they can never disagree on what's being checked vs. deleted.
  • A denied gate aborts the whole delete — no node removed — and surfaces NodeServiceError::InaccessibleDescendants { inaccessible_count } through OpsError → a distinct gRPC FailedPrecondition status (x-inaccessible-descendants metadata) → a new INACCESSIBLE_DESCENDANTS Tauri CommandError code → a terminal frontend refusal modal (no Delete button, count-only disclosure — never ids/names/types).
  • reactive-node-service's deleteNode is non-optimistic for any node with descendants: it now awaits the backend response before touching local state, so a refusal never causes nodes to flicker out of the UI and come back.

Scope note

This repo (nodespace-core) is the local daemon and has no access-control concept of its own — the real enforcement authority is the Pro tenant schema in nodespace-cloud (ADR-041). That authoritative subtree-read-check RPC doesn't exist yet; a companion issue is open to add it: NodeSpaceAI/nodespace-cloud#103. Until that lands and a Pro daemon (nodespaced-pro, built in nodespace-sync) injects a real gate via NodeService::set_subtree_access_gate, community installs are unaffected — AlwaysAllowGate is the only gate in play, matching current behavior exactly.

Test plan

  • bun run test:all — full workspace (frontend 171 files/4113+ tests, all Rust crates) — 0 failures
  • bun run quality:fix — clean, unrelated formatting drift reverted
  • New Rust tests: subtree with a restricted descendant is refused whole (no partial delete, both parent and descendant survive); fully-readable subtree still deletes unchanged; version conflict still wins/reported correctly with the gate active; OCC on a readable descendant still doesn't abort the cascade with the gate active
  • New frontend tests: refusal modal renders count, singularizes for 1, has no Delete button, resolves on OK
  • Pre-push gate (test:all + cargo build + e2e) passed, including deletes_a_node_and_confirms_it_is_absent (existing single-node delete path unaffected)

Closes #1736.

Adds a pluggable pre-delete access check ahead of delete_subtree_atomic:
a SubtreeAccessGate trait injected into NodeService (AlwaysAllowGate by
default, matching today's behavior for community/local installs). A
synced Pro daemon can inject a real gate once the backing tenant RPC
lands (tracked separately in nodespace-cloud#103). The descendant id
set is computed once and shared between the gate check and the delete
itself so the two can never see different subtrees.

A denied gate aborts the whole delete — no node removed — and surfaces
NodeServiceError::InaccessibleDescendants{count} through OpsError, a
distinct gRPC FailedPrecondition status, and a new frontend refusal
modal state (terminal, no Delete button, count-only disclosure).

Closes #1736.

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

malibio commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Review Type

Initial full-diff review (no prior review comments on this PR).

Requirements Check

Cross-referenced against issue #1736's acceptance criteria, applying both scope caveats from the issue comments (this PR is deliberately daemon-side-only plumbing; the authoritative RLS gate lands separately in nodespace-cloud#103).

AC Status Notes
Delete whose subtree contains unreadable nodes is rejected, no node removed ✅ Verified NodeService::delete_node aborts before the transaction opens; test_delete_node_refused_when_subtree_has_restricted_descendant confirms both target and descendant survive.
Rejection reports count only, no identifying info ✅ Verified Traced full chain — see Disclosure Rule section below.
Fully-readable subtree succeeds unchanged ✅ Verified test_delete_node_succeeds_when_subtree_fully_readable.
Gate enforced server-side in tenant schema, not only daemon/frontend ⚪ Out of scope here (Caveat 1) Deliberately deferred to nodespace-cloud#103; AlwaysAllowGate default matches documented scope. Not flagged as missing.
OCC unchanged: concurrent edit to readable descendant doesn't abort; version mismatch still yields conflict with intact subtree ✅ Verified test_delete_node_occ_on_readable_descendant_unaffected_by_gate and test_delete_node_version_conflict_still_wins_over_access_gate both pass and exercise real precedence (gate configured to allow, version conflict still surfaces on its own).
Adversarial test: restricted descendant survives, parent not deleted ⚪ Simulated correctly (Caveat 2) DenyIfPresentGate stub simulates this; can't be adversarially verified against a live Pro tenant from this repo, which is expected.
Adversarial test: no orphaned descendants reachable by any path ⚪ Simulated correctly (Caveat 2) Same — whole-abort semantics verified via stub; see Critical finding below re: one frontend path where the plumbing does not correctly simulate this for a Pro tenant's own actor UI.
bun run test:all passes ✅ Verified Ran the new Rust tests individually (all pass) and the new/updated frontend test file (6/6 pass, includes 3 new). PR body reports full-suite 0 failures.
bun run quality:fix clean ✅ Verified cargo clippy -p nodespace-core -p nodespace-daemon --all-targets clean; eslint on touched frontend files clean; no console.log, no any types in the diff.

Code Review Findings

Critical Issues

packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts:1288-1323 and shared-node-store.svelte.ts:1960-2025 — the optimistic delete path has no refusal handling, and it's reachable exactly in the scenario this feature exists for.

descendantCount at reactive-node-service.svelte.ts:1293-1294 comes from backendAdapter.getDescendants(nodeId), which walks getChildren over whatever the backend returns for that actor. On a Pro tenant, RLS silently filters rows the actor can't read (this is explicitly established in the issue's own scoping comment re: nodes_delete policy behavior). So a node whose entire set of children is restricted-and-invisible to the actor will report descendantCount === 0 — the non-optimistic branch (if (descendantCount > 0) at line 1302) is skipped, and deletion falls through to the pre-existing optimistic path: sharedNodeStore.deleteNode(nodeId, viewerSource, false).

In that optimistic path, shared-node-store.svelte.ts removes the node from local state synchronously and unconditionally (line 1971, this.nodesDelete(nodeId)) before the backend call is even issued at line 1995. The backend call happens inside a fire-and-forget-style persist operation whose catch block (lines 1996-2008) only logs and tracks the error for test assertions — it has no knowledge of isInaccessibleDescendants and does not restore the optimistically-removed local state on any error, including this one.

Net effect: for a Pro-tenant actor whose target node's visible descendant count happens to be zero (because everything underneath is restricted), a refused delete still makes the node disappear from that actor's own UI, with no refusal modal, and no path back short of a full resync. This directly contradicts the stated design goal ("a refusal never causes nodes to flicker out of the UI and come back") for precisely the case the feature was built to protect — a node whose true subtree has inaccessible descendants the actor can't even see. The doc comment at reactive-node-service.svelte.ts:1279-1281 even hangs the correctness argument on "a leaf node has no subtree to gate," but that's the count as seen by the actor, not the true subtree — those aren't the same thing on a Pro install, which is exactly what the issue text itself calls out as the subtlety to watch for.

This isn't disqualifying under Caveat 1 (it's not "the stub gate doesn't enforce anything," it's a real bug in the injection-point design that a live Pro daemon would hit), and Caveat 2 doesn't cover it either — it doesn't require a live tenant to see; it's reachable today by constructing a stub SubtreeAccessGate that denies while getDescendants-equivalent local test data reports zero children (e.g. children that exist in the DB via has_child but aren't returned by whatever "children" enumeration the frontend test double uses). Recommend: either (a) route deletion through the non-optimistic/awaited path unconditionally regardless of descendantCount, since the backend gate check is unconditional and cheap for AlwaysAllowGate/community installs anyway, or (b) have the optimistic path's catch block also check isInaccessibleDescendants and restore local state + show the refusal modal on that specific error, symmetric with how the non-optimistic path handles it. Option (a) is simpler and removes an entire class of "visible count lies about true subtree" bugs, at the cost of making all cascade deletes non-optimistic (which seems like the right tradeoff for a destructive, access-gated operation — the whole point of ADR-041 is that this operation needs to be conservative).

Suggested Improvements

  • packages/desktop-app/src/lib/services/backend-adapter.ts:280-298 (handleResponse, HTTP/dev-proxy adapter) and its deleteNode at line 343 — the HTTP adapter throws a plain Error on non-OK responses, not a CommandError-shaped object with code/conflictData. isInaccessibleDescendants (and isVersionConflict, which has the identical pre-existing limitation) will always return false against errors from this adapter, so a refusal on the browser/dev-proxy path falls through to the generic log.error + silent return with no modal shown to the user. This is not a regression introduced by this PR — it's inherited from the same gap VERSION_CONFLICT already has — but this PR doubles the surface area relying on that gap. Worth a follow-up to align the dev-proxy error contract with the Tauri CommandError shape (or explicitly document that the refusal UX is Tauri-only for now).

  • packages/core/src/services/node_service/access_gate.rs:179-189 — SubtreeAccessDecision::Denied { inaccessible_count: u64 } has no validation against inaccessible_count: 0. A buggy real gate implementation could return Denied { inaccessible_count: 0 }, which would surface as "This contains 0 items you don't have access to" in the UI — confusing but not unsafe (the delete is still correctly aborted). Consider either a debug_assert on the daemon side or documenting in the trait doc that implementors must not return Denied with a zero count.

Nitpicks

  • Nit: packages/core/src/services/node_service/crud.rs:1246-1247 — self.store.get_node(node_id).await.ok().flatten() swallows the underlying Result error from get_node (e.g. a real DB error becomes indistinguishable from "not found," silently short-circuiting to existed: false instead of propagating the error). This is a narrow window (the same get_node is called again effectively inside delete_subtree_atomic), so it's low-risk, but a real I/O error here would misreport as "already deleted" rather than surfacing as a query failure like the collect_subtree_ids error two lines below does (.map_err(...)) . Consider matching the same error-propagation style for consistency.
  • Nit: packages/core/src/services/node_service/access_gate.rs:227-233 — the static DEFAULT: AlwaysAllowGate inside subtree_access_gate() is a nice touch (avoids allocating an Arc per call on the hot default path), but relies on AlwaysAllowGate staying a zero-sized, Sync-safe unit struct forever; worth a one-line comment noting that constraint if the struct ever grows fields.
  • Nit: packages/desktop-app/src/lib/services/delete-confirmation.svelte.ts:44 — showInaccessibleDescendantsRefusal line exceeds the file's typical line-length convention (unwrapped export async function signature); purely cosmetic, quality:fix would likely reformat it if re-run.

Architectural Assessment

The SubtreeAccessGate trait design is sound and genuinely testable/injectable:

  • Send + Sync bound on the trait plus async_trait gives a real Pro implementation (DB-backed, making a network/RPC call to the tenant) a workable async signature — no blocking-call footgun.
  • The OnceLock<Arc<dyn SubtreeAccessGate>> pattern is a faithful analog of the existing embedding_waker: Arc<OnceLock<EmbeddingWaker>> pattern (node_service/embedding.rs:87-88, mod.rs:836) — same thread-safety properties (interior mutability via OnceLock, shared via Arc so all clones observe a post-construction set()), same idempotent-set-once semantics (let _ = ...set(...) silently ignores a second call), same lifecycle (constructed empty at NodeService::new, optionally populated later). No footgun on double-init (second set_subtree_access_gate call is a documented no-op, matching set_embedding_waker) or on read-before-init (falls back to the static AlwaysAllowGate default rather than panicking). This is a correct, minimal-risk reuse of an established pattern, not a superficial analogy.
  • Computing collect_subtree_ids once and threading it through both the gate check and delete_subtree_atomic (rather than the gate walking the tree independently) is the right call — it structurally prevents the gate and the delete from ever disagreeing about what's in scope, which is exactly the kind of bug class ("gate checked set A, deleted set B") that would be easy to introduce with two independent walks.
  • delete_subtree_atomic's signature change (subtree_ids: &[String] now passed in) is a pure refactor with no correctness regression: I diffed against origin/main and confirmed the subtree walk was already being computed before the transaction opened in the original code — this PR only moves that computation to the caller, it doesn't change when the TOCTOU window opens or closes. The only version re-check that matters for OCC (the target node's version, re-read inside the transaction at the point immediately before the DELETE) is untouched. So: "could a node added to the subtree between collection and transaction start be silently skipped from deletion" — yes, but that was already true before this PR and is not a new regression; it's an existing, narrow, documented-by-omission property of the OCC-scoped-to-target design (ADR-041 explicitly scopes OCC to the target only, not descendants).
  • The early get_node check added in crud.rs:1242-1247 before collect_subtree_ids is not redundant dead code — it's a legitimate short-circuit that avoids invoking the access gate (a call that could hit a real network RPC in a Pro daemon) for a target that's already gone. Worst-case race (node deleted concurrently between this check and delete_subtree_atomic's own internal check) is already handled by delete_subtree_atomic's pre-existing idempotent-absent logic, so there's no new TOCTOU risk, just an optimization that also happens to make the "nothing to delete" case cheaper.

Disclosure Rule (count-only, no identifying information)

Traced every point the inaccessible descendant set touches:

  • NodeServiceError::InaccessibleDescendants { inaccessible_count: u64 } (services/error.rs:120) — count only.
  • OpsError::InaccessibleDescendants { inaccessible_count } (ops/mod.rs:92) — count only, direct passthrough.
  • gRPC status (daemon/src/services/node_service.rs:1690-1706) — message is "This contains {count} items...", metadata payload is {"inaccessible_count": count} only.
  • Tauri CommandError (commands/nodes.rs:118-160) — conflictData deserializes the same count-only JSON; no other field carried through.
  • Frontend InaccessibleDescendantsData (types/errors.ts:139-146) — typed as { inaccessible_count: number } only.
  • Refusal modal copy (delete-confirmation-modal.svelte:720-725) — renders only the count.
  • All log.debug/log.warn calls touching this feature (delete-confirmation.svelte.ts:54,58; reactive-node-service.svelte.ts:1298,1310) — log node id and count only, never descendant ids/names/types. DenyIfPresentGate test stub carries a restricted_id for test setup only, never logged or surfaced.

No leak found anywhere in the diff. This is clean end-to-end.

Security Assessment

Reviewed as access-control-adjacent code per instructions, despite the real predicate being explicitly out of scope here:

  • The trait's Send + Sync + async shape will work for a real Postgres-RPC-backed implementation without redesign — confirmed by the OnceLock/embedding_waker analogy holding.
  • No way found for the plumbing itself to be bypassed within this repo's boundary: delete_node is the single call site for cascade delete, the gate check is unconditional (not behind a feature flag or config that could be silently disabled), and it runs before any mutation. A malicious client that skips the daemon (writes directly to SQLite) is out of scope — same as the issue's own stated threat model ("a client-side or daemon-side check is advisory only").
  • One real design gap found and reported above (Critical): the frontend's own optimistic-UI shortcut can defeat the user-visible guarantee of "nothing disappears on refusal" in exactly the scenario (invisible restricted descendants) the feature targets, even though the backend correctly refuses the write in all cases. This is a UX/consistency bug, not a data-integrity bug — the backend never actually deletes anything it shouldn't; the gap is that the acting user's own client can misrepresent local state until reconciled.

Recommendation: REQUEST CHANGES

The backend plumbing (gate trait, injection pattern, error propagation chain, disclosure discipline, OCC/precedence correctness) is well-designed and thoroughly tested — this is a strong PR on the server/daemon side. The blocking issue is narrower: the frontend's optimistic-delete shortcut (triggered when the actor's own visible descendant count is zero) bypasses the non-optimistic/refusal-aware path entirely, which can show a node as deleted in the acting user's own UI even when the backend correctly refused the delete — precisely in the "invisible restricted descendant" scenario this feature exists to protect. Given this is access-control-adjacent, user-facing-correctness code, recommend fixing this before merge rather than as a fast-follow: either make cascade deletes with descendants unconditionally non-optimistic (simplest), or add refusal handling to the optimistic path's error catch. Everything else in the PR — architecture, error chain, disclosure rule, OCC precedence, test coverage — is solid and requirement-complete for the stated (and correctly caveated) scope.

@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 posted above (GitHub does not allow self-authored PRs to request changes) — recommendation is REQUEST CHANGES per the full report: one Critical finding (optimistic-delete path can hide a UI-visible refusal for actors whose visible descendant count undercounts the true subtree), everything else solid.

…tion

Critical fix: deleteNode conditioned the non-optimistic (await-before-mutate)
path on the locally-visible descendant count. On a synced Pro tenant, RLS
silently filters getDescendants to what the actor can already see — a node
whose entire child set is restricted-and-invisible reported
descendantCount === 0, so the delete fell through to the old optimistic path
and could vanish from the deleting actor's own UI before the backend's
refusal was known. Now the backend call is always awaited first, regardless
of the locally-visible count; this is free on community/local installs where
the gate is AlwaysAllowGate and resolves immediately.

Also addresses two suggestions: propagate get_node's real error instead of
swallowing it via .ok().flatten() in delete_node's early exists-check, and
debug_assert a Denied decision always carries inaccessible_count > 0 so a
buggy real gate can't surface a "0 items" refusal message.

Skipped: HTTP/dev-proxy adapter's plain-Error-on-non-OK gap (isVersionConflict
has the same pre-existing gap; out of scope for this PR, worth a follow-up).

Addresses reviewer recommendations from PR #1868 review.

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

malibio commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback

🔴 Critical (fixed): deleteNode conditioned the non-optimistic await-before-mutate path on the locally-visible descendantCount. On a synced Pro tenant, RLS silently filters getDescendants to what the actor can already see — a node whose entire child set is restricted-and-invisible reported descendantCount === 0, so the delete fell through to the old optimistic path and could vanish from the deleting actor's own UI before the backend's refusal was known. Fixed: the backend call is now always awaited before any local-state mutation, unconditionally. Free on community/local installs (gate is AlwaysAllowGate, resolves immediately).

🟡/🟢 addressed:

  • crud.rs: replaced .ok().flatten() (silently swallowed DB errors on the pre-delete existence check) with proper error propagation.
  • access_gate.rs: added a debug_assert that a Denied decision always carries inaccessible_count > 0, plus a comment on why the static AlwaysAllowGate default is safe as a zero-sized unit struct.

Skipped: the HTTP/dev-proxy adapter's plain-Error-on-non-OK gap (same pre-existing gap as isVersionConflict already has on that path) — out of scope for this PR, worth a follow-up issue.

All tests pass (bun run test:all, full workspace, 0 failures), quality:fix clean, pre-push gate passed.

Re-Review Decision

RE-REVIEW NEEDED — the critical fix changed core delete-flow control logic (removed the descendantCount > 0 conditional entirely), which is exactly the kind of change that warrants independent re-verification.

@malibio

malibio commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Review Type

Re-Review — delta only. Last reviewed at ff6b19f6 (initial review submitted 2026-08-01T00:00:15Z against that SHA). Current HEAD is 78d3b5c3. Graded diff: git diff ff6b19f6..78d3b5c3 — 3 files, +39/-25.

Previous Review Summary

Prior finding Severity Status
deleteNode conditioned the await-before-mutate path on RLS-filtered descendantCount, so a node with an entirely-invisible restricted child set took the optimistic path and could vanish from the deleting actor's own UI despite backend refusal 🔴 Critical ✅ Fixed — verified below
crud.rs .ok().flatten() swallowed real DB errors on the pre-delete existence check 🟡 Improvement ✅ Fixed
Denied { inaccessible_count: 0 } could surface a "0 items" refusal message 🟡 Improvement ✅ Addressed (debug_assert + trait-doc-adjacent comment)
HTTP/dev-proxy adapter throws plain Error, so isInaccessibleDescendants always returns false on that path 🟢 Nit ⚪ Deliberately deferred — see below
static DEFAULT: AlwaysAllowGate relies on the struct staying zero-sized 🟢 Nit ✅ Addressed (comment added)
delete-confirmation.svelte.ts:44 line length 🟢 Nit ⚪ Not addressed; quality:check is clean, so cosmetic-only

Verification of the Critical Fix

(a) Is there any remaining path that mutates local state before the backend resolves?

Traced deleteNode end-to-end at packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts:1291-1334. No — the fix is complete:

  • sharedNodeStore.getNode (1292) and backendAdapter.getDescendants (1295) are reads only.
  • confirmNodeDeletion early-return (1300-1303) — returns before any mutation.
  • await backendAdapter.deleteNode(...) (1308) is now the first operation with any side effect, and it precedes every local mutation.
  • Both catch branches (isInaccessibleDescendants at 1310-1314, generic at 1316-1317) return before reaching cleanupDebouncedOperations. No finally block, no callback registered before the await.
  • Only after a resolved backend call do the mutations run: cleanupDebouncedOperations (1319), sharedNodeStore.deleteNode (1323), delete _uiState (1324), _rootNodeIds reassignment (1327-1329), events.nodeDeleted / events.hierarchyChanged (1332-1333).

I confirmed this empirically rather than by reading alone. Temporarily extending the test file's delete-confirmation.svelte mock (which currently omits showInaccessibleDescendantsRefusal — see 🟡 below) and injecting a rejected deleteNode, a refusal on a leaf node leaves service.findNode('delete-test') non-null and events.nodeDeleted uncalled. Under ff6b19f6 that same case would have removed the node. The Critical is genuinely closed, including for the exact zero-visible-descendants shape that motivated it. (Scratch edits reverted; git status clean.)

(b) Does removing the conditional break the leaf-node case?

No, on all three sub-questions:

  • Is backendAdapter.deleteNode safe for a leaf? Yes. It was already being called for leaf nodes — just indirectly, from inside sharedNodeStore.deleteNode's persist closure (shared-node-store.svelte.ts:1994) with the identical (nodeId, node.version ?? 1) arguments. The fix relocates that same call earlier and awaits it; it does not introduce a new backend call for leaves.

  • Double-write avoided? Yes. skipPersistence=true is consumed by determinePersistenceBehavior at shared-node-store.svelte.ts:751-753, which returns { shouldPersist: false } at Priority 2 — ahead of the options.persist and source.type === 'database' branches — so no store-level path can re-trigger the write regardless of viewerSource. Verified empirically: a leaf delete produces exactly 1 backendAdapter.deleteNode call (asserted after a 50ms drain to catch any deferred PersistenceCoordinator write). No double-write.

  • Latency/UX regression on the common single-leaf delete? Real, and I think correctly accepted. Every cascade delete now awaits a round-trip that a leaf previously fired-and-forgot. But: (i) on community/local installs the "round-trip" is an in-process Tauri IPC call to a local daemon against local SQLite, with AlwaysAllowGate::check_subtree_access returning Allowed without I/O — sub-millisecond, not perceptible; (ii) deleteNode already awaits backendAdapter.getDescendants at line 1295 before it does anything at all, on every single delete including leaves. So the interaction was never synchronous-from-first-keystroke — this adds a second round-trip to a path that already had one, roughly doubling an already-imperceptible local latency rather than introducing a wait where none existed.

    On the deeper question — could a leaf-node delete safely stay optimistic by distinguishing "authoritatively confirmed leaf" from "leaf only because RLS filtered it"? In principle yes, but only with a backend-authoritative signal that does not exist today. getDescendants (backend-adapter.ts:357) is implemented as getDescendantsViaChildren(...) walking getChildren, i.e. exactly the RLS-filtered enumeration that caused the original bug; there is no unfiltered true_descendant_count on the wire. Adding one would mean disclosing "this subtree has N nodes you can't see" pre-delete, which cuts against the count-only-on-refusal disclosure discipline this PR otherwise holds carefully. Given that, the unconditional await is the right call, and correctly matches the "conservative on destructive access-gated operations" posture of ADR-041. I would not ask for the optimization.

(c) Are the two minor fixes correct and regression-free?

  • crud.rs:1244-1255 — correct. .ok().flatten() is replaced with .map_err(...query_failed...)? + .is_some(). The idempotent-absent case is preserved exactly: a successful get_node returning None still yields DeleteResult { existed: false, deleted_count: 0 } rather than an error, so deleting an already-deleted node still behaves sanely. Only a genuine store error now propagates, which is the intended change. test_delete_node_idempotent_for_missing_node passes, confirming the absent-target contract is intact. The error style now matches the collect_subtree_ids call two lines below.
  • crud.rs:1268-1272 — debug_assert! placement is correct: it sits inside the if let ... Denied { inaccessible_count } binding, immediately before the error is constructed, so it fires on the exact value that would reach the UI. I grepped every consumption site of SubtreeAccessDecision::Denied — crud.rs:1263 is the only production one (the others are the trait definition, the AlwaysAllowGate impl, and test stubs), so there's no sibling path that could construct the error while bypassing the assert. debug_assert (vs. a runtime check) is the appropriate mechanism here: the invariant is a contract on gate implementors, not on untrusted input, and the failure mode is a confusing message rather than an unsafe delete — the delete is still correctly aborted either way. Hard-failing a release build over cosmetics would be worse than the symptom.
  • access_gate.rs:65-67 — the comment accurately states the constraint (&'static to a stack-local static is sound only while AlwaysAllowGate stays a zero-sized unit struct) and names the remedy if it ever grows state. Correct and useful.

(d) Tests against current HEAD — all green:

Check Result
cargo test -p nodespace-core --lib delete_node 9/9 pass (incl. all 4 gate/OCC-precedence tests)
cargo test -p nodespace-core --lib access_gate / cascade 3/3, 2/2 pass
cargo test -p nodespace-core --lib (full) 1075 passed, 0 failed
cargo clippy -p nodespace-core --all-targets clean, 0 warnings
bun run quality:check (eslint + svelte-check) 1869 files, 0 errors, 0 warnings
bun run test (full frontend) 171 files, 4116 tests, 0 failures

Code Review Findings

🔴 Critical Issues

None. The prior Critical is closed and independently verified.

🟡 Suggested Improvements

  • packages/desktop-app/src/tests/services/reactive-node-service.test.ts:58-60 — the refusal path has no frontend test, and the test mock structurally cannot exercise it. The vi.mock('$lib/services/delete-confirmation.svelte', ...) factory declares only confirmNodeDeletion; showInaccessibleDescendantsRefusal is absent from the mock. Any test reaching line 1311 therefore throws showInaccessibleDescendantsRefusal is not a function rather than asserting behavior — I hit exactly this when writing the scratch verification, and had to add the missing mock export to proceed. Consequence: the delta's entire reason for existing (a refused delete leaves local state untouched and surfaces the modal) is verified only by my throwaway test, not by anything in the repo. The 6 tests added in delete-confirmation-modal.test.ts cover the modal component's own rendering, not deleteNode's control flow. This is the one thing I'd genuinely like to see before merge: add showInaccessibleDescendantsRefusal to that mock factory and two tests — (1) a leaf node whose backend delete rejects with INACCESSIBLE_DESCENDANTS stays in the store and does not fire nodeDeleted; (2) a successful leaf delete calls backendAdapter.deleteNode exactly once. Test (1) is precisely the regression guard for the bug just fixed, and without it a future refactor could reintroduce the descendantCount conditional with a fully green suite. Both are ~10 lines; I confirmed both pass against current HEAD, so this is writing down a verified behavior, not new work.

🟢 Nitpicks

  • Nit: packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts:1273-1274 — the updated doc comment reads "Shows a confirmation dialog when the node has (visibly) descendants." The parenthetical (visibly) lands slightly awkwardly mid-phrase; "when the node has visible descendants" reads cleaner and carries the same (important) caveat. Purely editorial — the substance of the rewritten comment block is excellent and correctly documents the RLS-filtering subtlety that motivated the fix.
  • Nit: descendantCount (line 1296) is no longer a control-flow input to the delete itself, but it is not dead — it still feeds confirmNodeDeletion(descendantCount) (1299) and the cancellation log (1301). No cleanup needed; flagging only because the re-review brief asked whether the fix left dead code behind. It didn't.
  • The deferred HTTP/dev-proxy handleResponse gap (backend-adapter.ts:280-298) remains, correctly scoped out. Worth noting the unconditional await slightly widens its blast radius: on that adapter, a refusal now fails all deletes silently (generic log.error + return at 1316-1317, no modal) rather than only cascades. Still not a regression — that path is browser/dev-proxy only, isVersionConflict has the identical pre-existing gap, and the backend still correctly refuses the write. A follow-up issue aligning the dev-proxy error contract with the Tauri CommandError shape remains the right disposition.

New Issues Introduced

None. Specifically checked for: local-state mutation reachable before the await (none), double-persistence on the leaf path (none — verified empirically), dead code from the removed conditional (none — descendantCount still used), changed behavior on user-cancel or node-not-found early returns (unchanged), and error-swallowing regressions from the crud.rs change (none — absent-target contract preserved).

Recommendation: APPROVE

The Critical is properly closed — not narrowed or worked around, but removed at the root by deleting the conditional entirely, which eliminates the whole "locally-visible count lies about the true subtree" bug class rather than patching one instance of it. I verified the fix empirically rather than by inspection: a refused leaf delete now leaves the UI untouched, and a successful leaf delete still writes exactly once. The two minor fixes are correct, the debug_assert is well-placed and unbypassable from any other production path, and the absent-target idempotency contract survives the crud.rs error-propagation change. Full suites are green on both sides (1075 Rust, 4116 frontend, clippy and svelte-check clean).

The one 🟡 — the missing showInaccessibleDescendantsRefusal mock export leaving the refusal path untested — is worth landing as a small follow-up commit before or right after merge, since it's the natural regression guard for the exact bug this delta fixes. I'm not blocking on it: the behavior is verified correct today, and the gap is in test scaffolding rather than shipped code.

@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.

Re-Review Recommendation: APPROVE

(GitHub does not allow approving your own pull request, so this is filed as a COMMENT review — the recommendation is APPROVE.)

The prior Critical is closed at the root: the descendantCount > 0 conditional is removed entirely, so the backend delete is always awaited before any local-state mutation. Verified empirically, not just by inspection — a refused delete on a leaf node now leaves the node in the store and does not fire nodeDeleted, and a successful leaf delete still issues exactly one backendAdapter.deleteNode call (no double-write via skipPersistence). Both minor fixes are correct, and the absent-target idempotency contract survives the crud.rs error-propagation change.

All checks green: 1075 Rust lib tests, 4116 frontend tests, clippy clean, eslint + svelte-check clean (1869 files, 0 errors).

One non-blocking 🟡: the test mock for delete-confirmation.svelte omits showInaccessibleDescendantsRefusal, so the refusal path has no repo test covering it. Worth a small follow-up commit as a regression guard. Full report in the comment above.

Follow-up to the prior commit: the re-review confirmed the fix is correct
but noted the test mock for delete-confirmation.svelte didn't export
showInaccessibleDescendantsRefusal, so the exact scenario the fix protects
against (a refused delete must leave local state untouched, not just
cascades) had no test coverage in the repo.

Adds the missing mock export plus two tests: a leaf-node delete calls
backendAdapter.deleteNode exactly once (no double-write), and a leaf-node
delete refused with INACCESSIBLE_DESCENDANTS leaves the node in the store
and never fires nodeDeleted — the regression guard for the bug just fixed.

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

malibio commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up: added the regression test coverage the re-review flagged

Re-review approved the critical fix and confirmed it's correctly closed, but noted (🟡) the test mock for delete-confirmation.svelte was missing showInaccessibleDescendantsRefusal, so the exact scenario the fix protects against had no repo test coverage.

Added the missing mock export plus two tests in reactive-node-service.test.ts:

  • a leaf-node delete calls backendAdapter.deleteNode exactly once (no double-write)
  • a leaf-node delete refused with INACCESSIBLE_DESCENDANTS leaves the node in the store and never fires nodeDeleted — this is the regression guard for the bug that was just fixed

All 116 tests in that file pass; full test:all is green (4118 tests); quality:fix clean.

This is additive test coverage only, no production code changed — no further re-review needed. PR is ready for merge at your discretion.

@malibio
malibio merged commit 3127b79 into main Aug 1, 2026
2 checks passed
@malibio
malibio deleted the issue-1736-access-gated-cascade-delete branch August 1, 2026 02:33
malibio added a commit that referenced this pull request Aug 1, 2026
PR #1868 landed the full vertical slice: SubtreeAccessGate trait +
AlwaysAllowGate default, plus a complete error-propagation chain
(NodeServiceError::InaccessibleDescendants, an OpsError variant, a
dedicated gRPC FailedPrecondition status, a Tauri CommandError code,
and a terminal frontend refusal modal) for a Denied state no caller
in this codebase can produce today.

Keeps the generic, already-wired seam: SubtreeAccessGate trait,
AlwaysAllowGate, the NodeService injection point, and the
collect_subtree_ids/delete_subtree_atomic refactor. Removes the
product-surface plumbing built only against a synthetic test gate:
the typed error, gRPC status mapping, Tauri command code, and
frontend refusal modal/state. The delete_node call site keeps
invoking the gate, but a Denied decision now maps to the existing
HierarchyViolation error as a placeholder until a real Pro gate
lands with its own typed error and UI treatment.

reactive-node-service.svelte.ts's deleteNode reverts to
optimistic-for-leaf-nodes behavior (no unconditional await), since
the non-optimistic path existed solely to protect the now-removed
refusal UX.

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.

CASCADE delete must abort when the subtree contains nodes the actor cannot read

1 participant