Skip to content

Introduce invariant vs reactive playbook rule classes with synchronous pre-commit execution on the origin device #1739

Closed

Description

@malibio

Overview

Every playbook rule today runs post-commit and fail-open: actions abort on failure with no rollback, leaving a log node and a node that never received the rule's effect. That is the right model for enrichment and notification. It is the wrong model for any rule that establishes a property the node must never be observable without — most obviously a rule that assigns access or membership, where a post-commit rule leaves a window in which the node exists unprotected, and a failed action leaves it permanently wrong.

This issue introduces a second rule class that runs synchronously inside the creating transaction, fail-closed, on the originating device only.

Problem Statement

Current execution semantics: actions run sequentially, abort on first failure, and are never rolled back. A rule that adds a required classification to a newly created node therefore has two failure modes that cannot be fixed within the model — a window between commit and effect, and a permanent divergence when an action fails.

The reason a second class is possible at all is an asymmetry worth stating plainly: synchronous pre-commit execution is only ever available on the originating device. A remote device receives an already-committed node; there is no open transaction to join. That asymmetry is the design, not an obstacle:

  • Because an invariant rule's effect commits atomically with the node, remote devices must not re-run it — the effect arrives with the node as ordinary synced data.
  • So the multi-device duplicate-execution problem does not apply to this class at all, and the class that does have that problem (reactive) is the one where duplicates are tolerable and convergent.

Proposed Solution

Two rule classes, declared in the playbook and validated at save time.

Invariant rule Reactive rule
Executes Synchronously, inside the creating transaction Asynchronously, post-commit
Runs on The originating device only Every device that observes the event
On failure The triggering write fails (fail-closed) Actions abort, a log node records it; no rollback
Multi-device duplication Does not apply Applies; handled by derived identity

Eligibility, validated at save time

A rule may be declared invariant only if it provably terminates inside a transaction. Saving a playbook whose invariant rule violates any condition is rejected, naming the offending action:

  • Local writes only — no LLM inference, no network call, no PTY. A transaction cannot await an external service, and holding a write transaction across an unbounded wait is a correctness and liveness hazard.
  • Non-chaining, depth 1 — the rule's actions must not themselves trigger rule evaluation. Unbounded recursion inside a transaction is unacceptable.
  • Deterministic — no random values, no wall-clock reads. Two devices reasoning about the same node must agree on what the invariant requires.
  • Same-graph scope — actions address the triggering node and what it already references; no queries whose results depend on sync state.

Invariant violations arriving from a remote device

A device can receive an already-committed node that violates an invariant it holds — the originating device ran an older playbook version, had the rule disabled, or predates the rule. The node cannot be un-committed. The resolution is repair and log: apply the effect to the received node and record a log node describing what was repaired and why.

Repair is preferred over quarantine (which hides real user data and creates a state no other device shares) and over silent acceptance (which lets a violation persist). It is only safe because invariant rules are deterministic and local-write-only by the eligibility rules — the repairing device computes the same effect the originating device should have.

Seeded playbooks carry protection semantics

Playbooks shipped as part of the product are seeded as ordinary playbook nodes, user-inspectable and user-modifiable. Seeded playbooks carrying an invariant additionally are resettable to their shipped default and warn explicitly on edit or disable, naming the consequence concretely — disabling a privacy invariant silently changes the default for everything created afterwards while leaving existing nodes correct, a divergence the user will not notice.

The engine is not an authorization boundary

Invariant rules give correctness for well-behaved clients only. A client that does not run the engine, holds a stale playbook, or has the rule disabled produces no effect. Any invariant with a privacy or access consequence must also be enforced server-side as a Pro tenant-schema constraint or trigger — mirroring how the last-admin invariant is enforced by a BEFORE DELETE OR UPDATE trigger on membership edges regardless of which client path attempts the write. That server-side enforcement is scoped to the consuming issue, not this one; this issue must not be understood as delivering a guarantee it cannot.

Architecture Impact

  • ADR-060 (../nodespace-docs/decisions/060-playbook-execution-under-multi-device-sync.md) is the governing decision. This issue implements §1 (rule classes), §2 (eligibility), §7 (repair-and-log), and §8 (seeded-playbook protection).
  • architecture/playbook-system.md previously specified one rule class with post-commit, abort-on-failure, no-rollback semantics as the only model. It has been amended with the two-class table and the eligibility rules.
  • ADR-030 (../nodespace-docs/decisions/030-prompt-skill-node-architecture.md) is the precedent for DB-seeded, user-modifiable product content that the seeded-playbook mechanism follows.
  • The companion nodespace-docs changes are already committed; no further docs work is required.

Acceptance Criteria

  • A rule can be declared invariant or reactive; absent a declaration, a rule is reactive (current behavior preserved)
  • An invariant rule's actions execute inside the same transaction as the triggering write
  • An invariant rule action failure fails the triggering write — the node is not created
  • An invariant rule does not re-execute on a device that received the node via sync
  • Save-time validation rejects an invariant rule containing an LLM, network, or PTY action, naming the offending action
  • Save-time validation rejects an invariant rule whose actions would trigger further rule evaluation
  • Save-time validation rejects an invariant rule using random values or wall-clock reads
  • A device receiving a node that violates an invariant it holds repairs the node and creates a log node recording the repair
  • A seeded playbook can be reset to its shipped default
  • Editing or disabling a seeded playbook carrying an invariant surfaces a warning naming the concrete consequence
  • Reactive rules behave exactly as before (no regression in the existing playbook test suite)
  • Tests pass (bun run test:all)
  • Code passes bun run quality:fix

Technical Specifications

Reference Files

  • Rule types: packages/core/src/playbook/types.rs — the rule struct the class declaration is added to
  • Save-time validation: packages/core/src/playbook/validation.rs — where eligibility checks belong (schema/version validation already happens here)
  • Engine: packages/core/src/playbook/engine.rs — handle_event, the RuleProcessor queue (reactive path); the invariant path does not go through this queue
  • Actions: packages/core/src/playbook/actions.rs — execute_actions; needs a transaction-scoped variant
  • Lifecycle: packages/core/src/playbook/lifecycle.rs — activate_playbook, disable_playbook
  • Node creation: packages/core/src/services/node_service/ — the transaction the invariant path must join
  • Last-admin trigger precedent: db/tenant-schema.sql in nodespace-cloud — enforce_last_admin, the pattern for DB-level invariant enforcement

Implementation Details

  • The invariant path is architecturally distinct from the reactive path: reactive rules are dispatched to a bounded mpsc queue with a single consumer, which is exactly what an invariant rule must not do (the queue is post-commit and asynchronous by design). Invariant rules must be evaluated inline in the write path, before commit.
  • This means the write path gains a dependency on rule lookup. Keep the lookup read-only and lock-free relative to the transaction — lifecycle already holds rules behind a std::sync::RwLock for in-memory HashMap reads with no .await across the lock, which is the property needed here.
  • Save-time eligibility validation needs an action-classification table (which action kinds are local-write-only, which are non-deterministic). Define it once and share it with the non-idempotent-action classification the reactive path needs.
  • Repair-and-log runs on the receiving device against an already-committed node, so it is an ordinary write, not a transaction join. It must be idempotent — several devices may repair the same node concurrently, and the repair must converge rather than produce N log nodes for one violation. The existing log-node fingerprinting and deduplication mechanism is the tool for this.
  • "Reset to shipped default" implies the seeded playbook's default content is available at runtime, not only at seed time.

Dependencies

Related Issues

Activity

  1. self-assigned this
    on Jul 28, 2026
  2. mstomar125 commented on Jul 28, 2026

    @mstomar125
    Contributor

    Picking this up (mstomar125), implementing ADR-060 in reviewable slices. Slice A (this first PR): rule class + save-time eligibility validation — add the invariant/reactive rule class (default reactive, no execution change yet) and reject at save time any invariant rule that violates ADR-060 §2 (local-writes-only, non-chaining depth-1, deterministic, same-graph scope). Slice B adds the synchronous pre-commit invariant execution; C = repair-and-log for remote violations (§7); D = seeded-playbook protection (§8). §6 (DB-side enforcement) is a separate cloud task and will be flagged.

  3. mstomar125 commented on Jul 28, 2026

    @mstomar125
    Contributor

    Slice A merged in #1773 (issue stays open — 3 slices remain). Added the invariant/reactive rule class (default reactive, behavior-neutral — no execution change) and the save-time eligibility gate for invariant rules per ADR-060 §2: local-writes-only (exhaustive action classification), deterministic (rejects wall-clock CEL functions, the only non-deterministic surface), same-graph scope (rejects literal target ids), and the statically-decidable self-chaining case of non-chaining depth-1. The general cross-rule/multi-device chaining case is deferred to the runtime causal-depth guard (Slice B, ADR-060 §5). Next: Slice B — synchronous pre-commit invariant execution in the create transaction (I'll surface its design before it lands, as it modifies the write path); then C (repair-and-log, §7) and D (seeded-playbook protection, §8). §6 (DB-side enforcement) is a separate cloud task.

  4. mstomar125 commented on Jul 28, 2026

    @mstomar125
    Contributor

    ⏸️ PARKED for later pickup (Slice A landed; remaining slices blocked on a design decision).

    Done: Slice A merged in #1773 — the invariant/reactive rule class + save-time eligibility gate (ADR-060 §2). Behavior-neutral (default reactive, no execution change, no invariant rules seeded yet).

    Why parked — Slice B needs a transaction-model decision before any code: ADR-060 requires an invariant rule to run inside the creating transaction, fail-closed. But NodeService::create_node today does its pre-processing, a single store.create_node write, and emits NodeCreated afterwards — there is no open, joinable transaction the engine can inject invariant-action writes into. So Slice B needs one of:

    • Option 1 (recommended): restructure create_node to open an explicit libsql Transaction spanning the node insert + the invariant-rule action writes, commit atomically; any invariant-action failure rolls the whole thing back (the node never commits). This is what ADR-060's atomicity actually requires — but it's a significant core write-path change and needs the store/NodeService to expose transaction-scoped writes.
    • Option 2: a logical pre-commit (run invariant actions, abort the create on failure, no single SQL tx). Smaller, but weaker atomicity — likely insufficient for the privacy-invariant use case ADR-060 targets.

    Also for Slice B: dispatch must run invariant rules ONLY pre-commit on the originating device; the existing post-commit event handler AND the sync-apply path must NOT re-run them (reuse sync's reserved client-identity tag — the #1738 §5 signal; coordinate to avoid an engine.rs collision).

    Still queued: Slice C = repair-and-log for remote invariant violations (§7). Slice D = seeded-playbook protection: resettable + warn on edit/disable (§8). §6 (DB-side enforcement of privacy invariants in the Pro tenant schema) is a separate cloud task (the engine is not an authorization boundary).

    Resolve Option 1 vs 2 (likely a malibio/architecture call) to unpark.

  5. mstomar125 commented on Jul 29, 2026

    @mstomar125
    Contributor

    @malibio — flagging this for your sign-off before Slice B lands, because the transaction-model decision here changes the core write path (NodeService::create_node) and therefore affects the whole app's create flow. I want your confirmation on the approach before writing any of it.

    Where we are

    Slice A is merged (rule model + save-time eligibility): RuleClass { Invariant, Reactive }, defaulting to Reactive, plus a validator that rejects an invariant rule doing network/LLM/random/wall-clock work (per ADR-060 §2). Nothing behavioral changed yet — no rule executes pre-commit.

    Slice B is the core of the ADR and it's blocked on one design question, which is why I'm parking it here rather than proceeding autonomously.

    The blocker

    ADR-060 §1 requires invariant rules to run "synchronously, inside the creating transaction," fail-closed. But today create_node does its pre-processing, calls store.create_node, and emits NodeCreated after the write returns — there is no open, joinable transaction the playbook engine can inject its action-writes into. The store has create_child_node_atomic (a single atomic child insert) but no general "run these N writes + the node insert as one transaction" primitive. So Slice B needs one of:

    Option A — Restructure to an explicit transaction (my recommendation).
    Open a real libsql Transaction in create_node: insert the node, match + run the invariant rule's actions through that same tx, commit atomically. Any invariant-action failure rolls the whole thing back — the node never commits.

    • Delivers true atomicity — the fail-closed guarantee ADR-060's privacy/access invariants actually need.
    • Biggest change: the store / NodeService must expose transaction-scoped writes, and the action executors must accept a tx handle. Needs a deadlock/re-entrancy review against the existing reorder_lock discipline.

    Option B — Logical pre-commit.
    Run the invariant actions before finalizing the create and abort the create on failure, but without a single SQL transaction wrapping node-insert + actions.

    • Much smaller change.
    • Weaker atomicity: a crash in the gap can leave a node without its invariant effect — which is precisely the window an invariant rule exists to eliminate. Likely insufficient for the privacy-invariant use case.

    Why I recommend Option A

    The entire justification for having an invariant class (vs. just reactive rules) is the fail-closed, no-window guarantee for access/membership/classification properties. Option B reintroduces exactly the window we're trying to close, so it doesn't really deliver the class's reason for existing — it's a smaller change that buys a weaker version of the thing we need. Option A is more work but it's the correct shape, and I think it's worth doing once rather than shipping B and re-doing it.

    I believe Option A is correct — but given this reshapes the create path app-wide, I'd like your explicit sign-off before I write it.

    One coupling to note

    Slice B also needs to distinguish a local write from a sync-apply so invariant rules run only pre-commit on the origin and are not re-run on the receiving device (the effect arrives as synced data). That signal is the same reserved client-identity tag #1738 §5 formalizes — so Slices B and the #1738 dispatch work should coordinate on engine.rs to avoid colliding.

    What I'd like from you

    1. Confirm Option A (explicit transaction) vs Option B.
    2. Confirm you're OK with NodeService / the store growing a transaction-scoped write API.
    3. A steer on the Playbook execution under multi-device sync: derived identity, stable ordering, causal cycle depth, and catch-up suppression #1738 coordination (who owns the shared local-vs-sync-origin signal).

    Parked until you weigh in. Slices C (repair-and-log, §7) and D (seeded-playbook protection, §8) follow B and are lower-risk.

  6. mstomar125 commented on Sep 12, 2026

    @mstomar125
    Contributor

    Re-checked against current main (0435c4d) — this issue's title ("...with synchronous pre-commit execution on the origin device") is still not satisfied. Summarizing so the board reflects the actual state rather than just staleness:

    What's actually merged: only Slice A, commit 4e368e78 (PR #1773, "Add the invariant/reactive playbook rule class and its save-time eligibility gate"). This is explicitly behavior-neutral: RuleClass { Invariant, Reactive } on the rule model (packages/core/src/playbook/types.rs, defaults to Reactive), plus save-time eligibility validation in packages/core/src/playbook/validation.rs rejecting non-local-write/non-deterministic/out-of-scope/self-chaining invariant rules. No rule executes pre-commit anywhere in the codebase — confirmed by packages/core/src/playbook/engine.rs's own comment: "This does not make RuleClass::Invariant rules sync-safe: their fail-closed guarantee depends on ADR-060 §2/§7 mechanisms that are out of scope here."

    Still unimplemented (the actual headline of this issue): Slice B (synchronous pre-commit execution inside the creating transaction — the core mechanism the title names), Slice C (repair-and-log for remote invariant violations, §7), Slice D (seeded-playbook reset/warn protection, §8). grep-ing the repo for invariant execution wiring, repair, or seeded/reset_to_default playbook logic outside validation.rs's eligibility checks and tests.rs turns up nothing.

    Why it's stuck: Slice B was explicitly parked on 2026-07-29 pending an architecture sign-off that never came. The blocker, per the parked comment: NodeService::create_node has no open, joinable transaction to inject invariant-rule action writes into, and the fix is a real core write-path change (Option A: restructure create_node around an explicit libsql transaction spanning node-insert + invariant actions, vs. Option B: a weaker non-transactional pre-commit check). The playbook author (issue author, GitHub handle malibio) was asked to confirm Option A vs B on 2026-07-29; no response as of today (2026-09-12, 45 days later). No related commits since (git log --all --grep for "1739"/"invariant"/"slice b/c/d" turns up nothing past #1773).

    Leaving open — genuinely not done, and still blocked on the same unresolved decision as when it was parked. Not re-pinging for sign-off here since that request already stands on the thread above.

  7. mstomar125 commented on Sep 15, 2026

    @mstomar125
    Contributor

    Unblocked — the transaction-model decision Slice B was parked on has been resolved by ADR-069 (merged as PR#2513, commit a555f9aa, "Add unit-of-work transaction seam; make multi-write operations atomic and emit events after commit").

    This is exactly Option 1 from the parking comment: NodeService now has its own with_transaction/NodeServiceTx seam (packages/core/src/services/node_service/mod.rs), giving composed operations a real, joinable transaction to inject writes into — create_node's public entry point wraps a create_node_in_tx that runs inside this seam, exactly what Slice B needs to inject invariant-rule action writes into the same transaction as the node insert, fail-closed on rollback.

    Moving to Todo — ready to pick up Slice B (synchronous pre-commit invariant execution, ADR-060 §5) against this now-real seam.

  8. self-assigned this
    on Sep 15, 2026
  9. mstomar125 commented on Sep 15, 2026

    @mstomar125
    Contributor

    Baseline (frontend, bun run test): 242/243 files passed, 4966/4967 tests passed. 1 pre-existing failure unrelated to this issue: architecture-benchmarks.test.ts's combineNodes <40ms perf threshold (flaky timing assertion, no playbook/core-write-path code touched). Starting Slice B/C/D implementation (ADR-069 transaction seam is in place per prior comments; #1738's originating-client signal — SYNC_SERVICE_CLIENT_ID/self.client_id — and the action-classification table from Slice A are independently sufficient, confirmed by direct code read, so proceeding without further blocking on #1738).

  10. mstomar125 commented on Sep 15, 2026

    @mstomar125
    Contributor

    Merged via PR #2632 (commit 8252a4d). Slices B (synchronous pre-commit invariant execution), C (repair-and-log), and D (seeded-playbook protection) all shipped, on top of Slice A (#1773). Not blocked on #1738 in the end — the originating-client signal (SYNC_SERVICE_CLIENT_ID/self.client_id) it depends on turned out to be a pre-existing ADR-027 convention, not something #1738's still-open reactive-engine work needed to supply first; confirmed by direct code read before starting.

    Two independent adversarial review passes caught and fixed a real, serious bug before merge: PlaybookEngine::handle_event's local-event branch enqueued RuleClass::Invariant rules onto the reactive ExecutionQueue with no class filter, so every invariant rule ran TWICE — once correctly (synchronous, pre-commit, fail-closed) and once more asynchronously post-commit with no rollback protection. A failure of that spurious second run would have silently disabled the whole play via the existing fail-open path, for a rule that had already succeeded moments earlier. Fixed by filtering RuleClass::Invariant out of what gets enqueued (mirroring the filter repair-and-log already applied on the sync-apply side), with a regression test asserting a node's version doesn't advance after the synchronous stamp. Also fixed a transaction-consistency gap in the member_of cycle check for invariant add_relationship actions, caught by the same review.

    Board still lists follow-ups from #1738's own thread (single-writer election NodeSpaceAI/nodespace-sync#521, relaxing the ADR-073 blanket sync gate) — unrelated to this issue, left untouched.

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