Skip to content

Add synchronous invariant-rule execution, repair-and-log, and seeded-playbook protection (ADR-060 §1/§7/§8) - #2632

Merged
mstomar125 merged 2 commits into
mainfrom
issue-1739-invariant-playbook-rules
Sep 15, 2026
Merged

mstomar125 merged 2 commits into
mainfrom
issue-1739-invariant-playbook-rules

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Implements Slices B, C, and D of #1739 — the remaining pieces of the invariant/reactive playbook rule class ADR-060 introduces. Slice A (RuleClass + save-time eligibility gate) shipped earlier in #1773 and is unchanged here.

This was unblocked by ADR-069 (PR#2513), which added the SqliteStore::with_transaction/Tx and NodeService::with_transaction/NodeServiceTx unit-of-work seam this issue's invariant path joins.

Slice B — synchronous, pre-commit, fail-closed execution (ADR-060 §1)

  • NodeService::create_node_in_tx now dispatches matching RuleClass::Invariant rules (services/node_service/invariants.rs) after the node insert lands on the open transaction but before commit. An action failure returns Err, which with_transaction turns into a full rollback — the triggering node is never durably created.
  • Extends the ADR-069 seam with the primitives invariant actions need: SqliteStore::get_node_in_tx, NodeService::update_node_in_tx, and tx-scoped create_relationship_in_tx/remove_relationship_in_tx. playbook::actions::execute_actions_in_tx is the transaction-scoped twin of the reactive executor.
  • Bare NodeService::create_node (the no-parent path) now also runs through with_transaction, so every local node create — not just create_node_with_parent's composed path — gets the same seam. Collection-name-collision detection/marking (previously inside SqliteStore::create_node) is preserved by doing the pre-check/post-mark explicitly around the transaction.
  • Cross-rule chaining is prevented structurally, not just validated. Save-time validation only catches the statically-decidable self-chaining case (a rule's own action re-satisfying its own trigger). The general case — rule A's action creating a node that matches a different active invariant rule's trigger — is closed by construction: create_node_in_tx's dispatch call is unreachable from insert_node_in_tx_no_invariant_dispatch, which is what the invariant action executor calls for its own create_node action. Verified by a dedicated adversarial test (see Testing).
  • Save-time validation gained two new checks: an invariant rule's trigger must be node_created (synchronous dispatch is wired only into that write path — a property_changed/relationship_added/relationship_removed/scheduled trigger would otherwise silently never fire), and an invariant add_relationship action to member_of/has_child must supply an explicit edge_data.order (those two types normally get an atomically-computed order via add_to_collection/append_child_edge, which has no transaction-scoped twin here).
  • The originating-client-vs-sync-apply signal this needed was not blocked on Playbook execution under multi-device sync: derived identity, stable ordering, causal cycle depth, and catch-up suppression #1738: NodeService::client_id/SYNC_SERVICE_CLIENT_ID is a pre-existing (ADR-027) convention already known synchronously inside create_node_in_tx, independent of Playbook execution under multi-device sync: derived identity, stable ordering, causal cycle depth, and catch-up suppression #1738's reactive-engine work. Confirmed via direct code read: sync-apply (nodespace-sync's apply_node_upsert) calls the exact same NodeService::create_node through a with_client(SYNC_SERVICE_CLIENT_ID)-tagged instance, so gating dispatch on self.client_id was sufficient.

Slice C — repair-and-log (ADR-060 §7)

  • playbook::engine's existing ADR-073 sync-origin gate (handle_event) now also runs repair dispatch for NodeCreated events before returning — architecturally separate from the reactive mpsc queue, same as the pre-commit path.
  • For each active invariant rule matching the synced node's creation whose condition still passes (i.e. the effect is missing), it runs the rule's actions as an ordinary write and records a repair in a playbook_log node.
  • The repair log node's id is deterministic (UUIDv5 over play_id/rule_name/trigger_node_id, mirroring the derived-identity technique ADR-060 §3 / deterministic_action_output_id already uses for reactive outputs), so two devices independently repairing the same violation converge to one row via ordinary sync upsert rather than each minting a random-id log node.

Slice D — seeded-playbook protection (ADR-060 §8)

Explicitly out of scope (per the issue)

The engine is not an authorization boundary. This PR gives correctness for well-behaved clients only — a client that doesn't run the engine, holds a stale playbook, or has the rule disabled produces no effect. Server-side enforcement of any privacy/access invariant (the Pro tenant-schema constraint mirroring the last-admin trigger) is explicitly a separate, consuming issue, not this one.

Also out of scope, called out in code comments where relevant: invariant dispatch is wired only for node_created triggers (not property_changed/relationship/scheduled — save-time validation rejects those); the member_of/has_child atomic-auto-order paths have no transaction-scoped twin (an invariant rule needs an explicit order instead); bulk-import/hierarchy paths that don't already compose through create_node_in_tx don't gain invariant dispatch.

Testing

New: packages/core/tests/playbook_invariant_integration_test.rs (9 tests) plus unit/integration tests in validation.rs (+14, trigger/order eligibility), seeded.rs (+7), and logging.rs (+3, repair-log determinism/idempotency).

Adversarial focus, per the task:

  • invariant_action_failure_rolls_back_the_whole_node_creation — the triggering node is verified absent afterward (get_node → None), not just missing the action's effect.
  • one_failing_invariant_rule_rolls_back_another_rule_s_successful_effect_too — a second rule's failure undoes a first rule's already-applied write in the same transaction.
  • an_invariant_action_creating_a_node_does_not_trigger_another_invariant_rule — the cross-rule chaining-prevention fix described above, caught by writing this test after noticing the structural gap on self-review.
  • invariant_rule_does_not_re_execute_on_sync_applied_node / sync_applied_node_already_satisfying_invariant_is_not_touched — via with_client(SYNC_SERVICE_CLIENT_ID), the same tagging convention the real sync-apply path uses.
  • sync_applied_node_violating_invariant_is_repaired_and_logged and repeated_repair_of_the_same_violation_converges_to_one_log_node — repair-and-log correctness and idempotency (true cross-device concurrency can't be constructed in one process; the idempotency test calls the log-node function twice with an identical key, which is what two devices independently computing the same deterministic id amounts to from either device's own perspective).
  • reactive_rule_still_fires_normally_alongside_an_invariant_rule — no regression to reactive semantics when both rule classes are active in the same engine.

Also caught and fixed on self-review (not a test, a direct code read): an early version of the create_node_in_tx refactor left its original validation/normalization/title pipeline in place and called the new insert_node_in_tx_no_invariant_dispatch helper, which duplicates that same pipeline — harmless functionally (idempotent) but wasteful and confusing. Fixed to a single delegation.

Test plan

  • cargo test -p nodespace-core --lib — 1376/1376 passed
  • cargo test -p nodespace-core --tests — all 27 integration binaries green, 0 failures
  • bun run rust:quality:fix (cargo fmt --all + cargo clippy --all-targets -D warnings -D clippy::unused-async) — clean across the whole workspace (core, daemon, agent, cli, desktop-app)
  • Full pre-push gate (scripts/test-gate.ts): bun run build:skill, bun run test:all (frontend + skill + Rust), cargo build --bin nodespaced, bun run test:e2e, cargo test -p nodespace-app --test "*" (Tauri-seam integration) — all green

Closes #1739

🤖 Generated with Claude Code

mstomar125 and others added 2 commits September 15, 2026 13:29
…playbook protection (ADR-060 §1/§7/§8)

Slice B: RuleClass::Invariant rules now dispatch synchronously inside the
node-creating transaction (NodeService::create_node_in_tx), fail-closed on
action failure. Extends the ADR-069 transaction seam with the primitives
invariant actions need: SqliteStore::get_node_in_tx,
NodeService::update_node_in_tx, and tx-scoped
create_relationship_in_tx/remove_relationship_in_tx (generic path only —
member_of/has_child auto-order has no transaction-scoped twin, so save-time
validation now requires an explicit edge_data.order for those two types on
an invariant add_relationship action). Save-time validation also now rejects
any invariant rule whose trigger isn't node_created, since synchronous
dispatch is wired only into that write path. Cross-rule chaining (rule A's
action creating a node that matches a DIFFERENT active invariant rule) is
prevented structurally: create_node_in_tx's dispatch call is unreachable from
insert_node_in_tx_no_invariant_dispatch, which is what the invariant action
executor calls for its own create_node action.

Slice C: repair-and-log for a node received via sync that violates an
invariant this device holds — engine.rs's existing ADR-073 sync-origin gate
now also runs repair dispatch for NodeCreated events before returning. The
repair log node's id is deterministic (UUIDv5 over play_id/rule_name/
trigger_node_id, mirroring ADR-060 §3's derived-identity technique), so two
devices independently repairing the same violation converge to one row via
ordinary sync upsert rather than each minting a random-id log node.

Slice D: a seeded play (properties._seed.default_rules) carrying an
invariant rule can be reset to its shipped default
(playbook::seeded::reset_seeded_play_to_default), and editing or disabling
one surfaces a playbook_log warning naming the play and the invariant
rule(s), not a silent lifecycle_status flip.

Adversarially tested: an invariant action failure genuinely rolls back the
whole node creation (node absent afterward, not just missing the action's
effect), including when a second rule's failure must undo a first rule's
already-applied write in the same transaction; sync-applied writes never
re-run invariant dispatch; repeated repair of the same violation converges
to one log node; and a dedicated regression test confirms an invariant
action's own create_node does not trigger a second active invariant rule.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… adversarial review

Two independent adversarial review passes on PR#2632 found:

1. (Blocking) PlaybookEngine::handle_event's local-event branch looked up
   matching rules with no RuleClass filter and enqueued RuleClass::Invariant
   rules onto the reactive ExecutionQueue exactly like reactive ones. Every
   invariant rule therefore ran TWICE on the originating device: once
   correctly (synchronous, pre-commit, fail-closed) and once more
   asynchronously, post-commit, fail-open, with no rollback protection --
   confirmed by a reviewer's throwaway probe test showing a node's version
   advancing a second time ~100-500ms after create_node() had already
   returned. A failure of that spurious second run would silently disable
   the whole play (and its invariant) via the existing fail-open
   disable-on-failure path, for a rule that had already succeeded correctly
   moments earlier -- exactly the failure mode ADR-060 exists to prevent.
   Fixed by filtering RuleClass::Invariant out of matched_rules before
   enqueueing, mirroring the filter dispatch_invariant_repair already
   applies for the sync-apply path. Added a regression test
   (invariant_rule_does_not_also_run_via_the_reactive_queue) that spawns a
   live engine and asserts a node's version does not advance after the
   synchronous in-tx stamp.

2. create_relationship_in_tx's member_of cycle check called the plain
   non-tx SqliteStore::validate_no_member_of_cycle even though every other
   read in that function was already converted to a tx-consistent read --
   a two-edge member_of cycle formed entirely within one transaction
   (e.g. by two invariant rules matching the same trigger) would go
   undetected. Added validate_no_member_of_cycle_in_tx and wired it in.

Also: softened create_or_update_repair_log_node's doc claim from
"idempotent by construction" to accurately describe the narrow check-then-act
race a second reviewer identified (non-blocking: the repair effect itself
still converges correctly; only occurrence-count bookkeeping can undercount
in that window); corrected an inaccurate assembly.rs comment about why
invariant dispatch is inert during startup seeding (the real reason is the
empty TriggerIndex before PlaybookEngine::start(), not "nothing writes
through node_service yet" -- seed_agent_nodes already does); and documented
the create_node_with_parent scope note that invariant dispatch runs before
the parent/collection edge is added, so a condition cannot see it.

Co-Authored-By: Claude Sonnet 5 <[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.

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

1 participant