Repository navigation
Add synchronous invariant-rule execution, repair-and-log, and seeded-playbook protection (ADR-060 §1/§7/§8) - #2632
Merged
Conversation
…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]>
This was referenced Sep 15, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/TxandNodeService::with_transaction/NodeServiceTxunit-of-work seam this issue's invariant path joins.Slice B — synchronous, pre-commit, fail-closed execution (ADR-060 §1)
NodeService::create_node_in_txnow dispatches matchingRuleClass::Invariantrules (services/node_service/invariants.rs) after the node insert lands on the open transaction but before commit. An action failure returnsErr, whichwith_transactionturns into a full rollback — the triggering node is never durably created.SqliteStore::get_node_in_tx,NodeService::update_node_in_tx, and tx-scopedcreate_relationship_in_tx/remove_relationship_in_tx.playbook::actions::execute_actions_in_txis the transaction-scoped twin of the reactive executor.NodeService::create_node(the no-parent path) now also runs throughwith_transaction, so every local node create — not justcreate_node_with_parent's composed path — gets the same seam. Collection-name-collision detection/marking (previously insideSqliteStore::create_node) is preserved by doing the pre-check/post-mark explicitly around the transaction.create_node_in_tx's dispatch call is unreachable frominsert_node_in_tx_no_invariant_dispatch, which is what the invariant action executor calls for its owncreate_nodeaction. Verified by a dedicated adversarial test (see Testing).node_created(synchronous dispatch is wired only into that write path — aproperty_changed/relationship_added/relationship_removed/scheduled trigger would otherwise silently never fire), and an invariantadd_relationshipaction tomember_of/has_childmust supply an explicitedge_data.order(those two types normally get an atomically-computed order viaadd_to_collection/append_child_edge, which has no transaction-scoped twin here).NodeService::client_id/SYNC_SERVICE_CLIENT_IDis a pre-existing (ADR-027) convention already known synchronously insidecreate_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'sapply_node_upsert) calls the exact sameNodeService::create_nodethrough awith_client(SYNC_SERVICE_CLIENT_ID)-tagged instance, so gating dispatch onself.client_idwas 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 forNodeCreatedevents before returning — architecturally separate from the reactivempscqueue, same as the pre-commit path.playbook_lognode.play_id/rule_name/trigger_node_id, mirroring the derived-identity technique ADR-060 §3 /deterministic_action_output_idalready 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)
playbook::seeded: a play markedproperties._seed.default_rulescan be reset to that shipped default (reset_seeded_play_to_default), and editing or disabling a seeded play that carries an invariant rule surfaces aplaybook_logwarning naming the play and the invariant rule(s) — not a silentlifecycle_statusflip.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_createdtriggers (notproperty_changed/relationship/scheduled — save-time validation rejects those); themember_of/has_childatomic-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 throughcreate_node_in_txdon't gain invariant dispatch.Testing
New:
packages/core/tests/playbook_invariant_integration_test.rs(9 tests) plus unit/integration tests invalidation.rs(+14, trigger/order eligibility),seeded.rs(+7), andlogging.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— viawith_client(SYNC_SERVICE_CLIENT_ID), the same tagging convention the real sync-apply path uses.sync_applied_node_violating_invariant_is_repaired_and_loggedandrepeated_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_txrefactor left its original validation/normalization/title pipeline in place and called the newinsert_node_in_tx_no_invariant_dispatchhelper, 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 passedcargo test -p nodespace-core --tests— all 27 integration binaries green, 0 failuresbun 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)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 greenCloses #1739
🤖 Generated with Claude Code