Skip to content

Wire RuleClass::Invariant rules into the write path so they actually run synchronously, in-transaction #2643

Closed

Description

@malibio

Overview

../nodespace-docs/decisions/060-playbook-execution-under-multi-device-sync.md (ADR-060) specifies RuleClass::Invariant as a rule that runs "synchronously, inside the creating transaction," so that on failure "the triggering write fails (fail-closed)" — a real, structural guarantee, not a description of what happens to an async action that later errors. Confirmed by direct inspection: NodeService::update_node (packages/core/src/services/node_service/crud.rs, ~line 1184 onward) never calls into the playbook engine directly. It only calls self.emit_event(DomainEvent::NodeUpdated {...}) (confirmed at ~lines 981, 1723) — a post-commit event, consumed later by PlaybookEngine's event subscriber (packages/core/src/playbook/engine.rs). There is no call path today where any Play — Invariant or Reactive — runs before a write returns to its caller. engine.rs (~line 218) contains an explicit comment disclaiming that its own sync-gating logic "does not make RuleClass::Invariant rules sync-safe."

This means the RuleClass distinction is currently inert at runtime: every Play, regardless of its declared class, executes exactly the same way — asynchronously, post-commit, with failures silently logged ("actions abort, a log node records the failure; no rollback," per ADR-060's own description of the Reactive failure mode). Invariant-class rules pass their save-time eligibility checks (validate_invariant_eligibility) but have no distinct runtime behavior to actually earn that classification.

Problem Statement

This blocks two concrete, motivating needs surfaced while scoping a Linear-style work-tracking recipe:

  1. A validation Play that must reject a write (e.g. "can't close an issue with open sub-issues" — tracked as Add a reject/validation action type so an invariant Play can veto a write, not just augment it #2642's action-type mechanism) has no synchronous execution point to run at. Add a reject/validation action type so an invariant Play can veto a write, not just augment it #2642 defines what a reject action does; this issue is the prerequisite that makes any invariant rule — reject or otherwise — actually run before the triggering write commits, rather than after.
  2. No user-facing feedback loop exists for a rejected write. Even once (1) is wired, the calling client needs to learn the write did not take effect, reconcile its optimistic local state, and show the rule's own violation message — not have the failure disappear into a log node the way today's async action failures already do, invisibly, by design, for the Reactive case.

No existing ADR or architecture doc claims this wiring already exists or is out of scope — ADR-060 presumes it as the mechanism throughout, it has simply never been built. This is consistent with ../nodespace-docs/decisions/073-playbook-engine-local-only-until-sync-stable.md (ADR-073), which already establishes that the playbook engine's daemon-startup wiring itself is separately-tracked, unfinished work — this issue is a further, distinct gap even once that lands, specific to Invariant-class synchronous execution.

Proposed Solution

NodeService::update_node (and the equivalent path for create_node) must, for any locally-originated write, run rule evaluation in this order, synchronously, inside the same transaction, before the write is finalized:

  1. Schema validation (existing, unchanged) — a schema-invalid write is rejected exactly as it already is today.
  2. Invariant-class Play-rule validation (new) — resolve which RuleClass::Invariant rules are triggered by this write (reusing the same trigger-index/matching machinery PlaybookLifecycleManager already maintains for post-commit dispatch, scoped to RuleClass::Invariant only), evaluate their conditions, and execute their actions inside the current transaction.
  3. If a Play rule rejects (via Add a reject/validation action type so an invariant Play can veto a write, not just augment it #2642's reject action): the write does not persist, and the call returns an error directly to its own caller (see Rejection delivery below) — no new node state exists to broadcast.
  4. If both pass: persist and broadcast exactly as today. Reactive-class rules are unaffected either way — they continue to run via the post-commit emit_event path exactly as now.

Rejection delivery: a direct Err return, modeled exactly on the existing VersionConflict pattern — no broadcast, no event system involved

A Play-rule rejection is, structurally, the same category of outcome as an OCC (optimistic concurrency control) version conflict: the calling client's update_node/create_node call did not take effect, and that same call is the correct, sufficient channel to report why. Confirmed by direct inspection of the existing precedent: NodeServiceError::VersionConflict { node_id, expected_version, actual_version } (packages/core/src/services/error.rs, ~line 72) is returned as a plain Err directly from the failing update_node call (packages/core/src/services/node_service/crud.rs, ~lines 1327, 1720) — no DomainEvent is ever involved, no WatchNodes broadcast, no suppression/echo handling of any kind. The calling client already has everything it needs from the RPC's own error response.

An earlier version of this issue proposed reusing the domain-event broadcast channel, with a bypass of WatchNodes' same-origin suppression (packages/daemon/src/services/node_service.rs's is_own_echo), to deliver a rejection back to the originating client. That design is rejected as unnecessary complexity, superseded by this direct-return approach: it would have built a second, parallel "your write failed" reporting path alongside one (VersionConflict) that already exists, already works, and already has a working frontend consumer — two mechanisms solving the same shape of problem (a client's own write did not take effect) is worse than one, not better, with no capability gained in exchange. The only real difference between OCC and a Play-rule rejection is when inside update_node the failure is discovered (immediately, before any transaction work, for OCC; during synchronous invariant evaluation, per this issue's step 2, for a Play rejection) — not how the failure should be reported, which should be identical for both.

Concretely:

  • Add NodeServiceError::PlayRuleRejected { node_id: String, play_id: String, rule_id: String, message: String } (naming TBD to match existing conventions), mirroring VersionConflict's shape exactly, where message is the rejecting rule's author-supplied violation text (see Add a reject/validation action type so an invariant Play can veto a write, not just augment it #2642).
  • update_node/create_node return this directly as an Err when step 2's invariant evaluation rejects — same call, same synchronous return, no event emitted at all for a rejected write.
  • The frontend catches this the same way it already catches isVersionConflict (packages/desktop-app/src/lib/services/shared-node-store.svelte.ts, ~lines 1990-2020): a new isPlayRuleRejected-style type guard alongside the existing one, reusing the same rollbackUpdate() call and the same surrounding catch/error-handling structure, differing only in which toast message is shown (the rule's own message, vs. OCC's generic conflict text).
  • No changes needed anywhere in the domain-event/WatchNodes/same-origin-suppression system. That mechanism is untouched by this issue — confirmed unnecessary once modeled on VersionConflict instead.

Architecture Impact

This implements ADR-060 §1's RuleClass::Invariant execution model as originally specified — it is not a reversal, but it is substantial, previously-undone implementation work that the ADR's acceptance did not itself complete. This rejection-delivery behavior should be recorded in ADR-060 (or a companion note) alongside the reject-action documentation update tracked in #2642. Depends on ../nodespace-docs/decisions/073-playbook-engine-local-only-until-sync-stable.md (ADR-073)'s daemon-wiring work existing in some form, since there must be a playbook engine instance reachable from the write path at all.

Acceptance Criteria

  • update_node/create_node synchronously evaluate matched RuleClass::Invariant rules inside the write's own transaction, before commit, after schema validation
  • A failing invariant rule's action prevents the transaction from committing — no partial write, verified by test
  • On rejection, update_node/create_node returns NodeServiceError::PlayRuleRejected (or equivalent), carrying the rejecting rule's author-supplied message, directly to the calling client — same pattern as VersionConflict
  • No DomainEvent is emitted for a rejected write — verified by test that no broadcast occurs
  • RuleClass::Reactive rules are unaffected — same post-commit, async, log-on-failure behavior as today
  • Test coverage: an invariant rule using a normal augmenting action (e.g. AddRelationship) still commits atomically with the triggering write, per ADR-060's original access/membership motivating example, and broadcasts normally since that write did succeed
  • Tests pass (bun run test:all)
  • Code passes bun run quality:fix

Technical Specifications

Reference Files

  • packages/core/src/services/node_service/crud.rs — update_node (~line 1184), create_node — where synchronous invariant evaluation must be added, after schema validation and before the existing emit_event calls (~lines 981, 1723); rejection returns Err before reaching those calls, mirroring version_conflict usage at ~lines 1327, 1720
  • packages/core/src/services/error.rs — NodeServiceError::VersionConflict (~line 72) — the exact shape and precedent PlayRuleRejected mirrors
  • packages/core/src/playbook/engine.rs (~line 218) — existing comment disclaiming sync-safety; confirms this gap is already known, not newly discovered
  • packages/core/src/playbook/lifecycle.rs — PlaybookLifecycleManager's trigger-index — the matching machinery to reuse, scoped to RuleClass::Invariant
  • packages/core/src/playbook/validation.rs — validate_invariant_eligibility (~line 632) — the save-time guarantees that make synchronous execution safe
  • packages/desktop-app/src/lib/services/shared-node-store.svelte.ts (isVersionConflict, rollbackUpdate, ~lines 1990-2020) — the existing frontend catch/rollback/toast pattern to extend with a new isPlayRuleRejected branch, reusing rollbackUpdate() as-is
  • ../nodespace-docs/decisions/060-playbook-execution-under-multi-device-sync.md (ADR-060) — the specification this issue implements
  • ../nodespace-docs/decisions/073-playbook-engine-local-only-until-sync-stable.md (ADR-073) — related daemon-wiring prerequisite

Dependencies

None strictly required to begin, but meaningfully incomplete without the playbook engine being reachable from daemon/service startup at all (ADR-073's scope) — verify current state of that wiring during implementation.

Related Issues

Non-Goals

  • Multi-device semantics for invariant rules under sync (ADR-060 §3-§7) — explicitly out of scope per ADR-073, unaffected by this issue
  • Any specific Play content — this issue is the write-path wiring only
  • Frontend isPlayRuleRejected branch and toast presentation themselves — that's a desktop-app-side follow-up consuming the typed error this issue produces; this issue's scope is the backend synchronous evaluation and error return only
  • Any domain-event/WatchNodes/broadcast changes — explicitly not needed, per Rejection delivery above; an earlier draft of this issue proposed such a mechanism and it has been superseded

Activity

  1. mstomar125 commented on Sep 16, 2026

    @mstomar125
    Contributor

    Checked directly against current `main` before picking this up — one correction to this issue's premise, the rest of the scoping holds.

    `create_node`/`create_node_in_tx` already has synchronous invariant-rule execution — this landed via #1739 (PR#2632, merged 2026-09-15): `packages/core/src/services/node_service/crud.rs`'s `create_node_in_tx` calls into `invariants.rs`'s execution path inside the same transaction, with rollback-on-failure via `with_transaction`/`?`. This issue's opening paragraph correctly diagnoses `update_node` as having no such call path (confirmed independently — `update_with_version_check_returning_node` does core-behavior validation, schema validation, and a play-content validation gate, but never evaluates invariant rules triggered by the update), but the "and the equivalent path for `create_node`" framing in the Proposed Solution section is now stale.

    So the real remaining scope here is `update_node` only — wiring it to reuse the same invariant-execution machinery `create_node_in_tx` already established (trigger-index matching scoped to `RuleClass::Invariant`, transaction-scoped action execution, rollback on reject), not building the mechanism from scratch. The `PlayRuleRejected`/rejection-delivery design (modeled on `VersionConflict`) and all the acceptance criteria still apply as written — just narrower in code-touch surface than "two call sites" implies.

    Picking this up now, scoped to `update_node`.

  2. self-assigned this
    on Sep 16, 2026
  3. mstomar125 commented on Sep 16, 2026

    @mstomar125
    Contributor

    Resolved by #2650 (merged 6ee495e7 → squash-merged to main). update_node now runs RuleClass::Invariant rules synchronously in-transaction, matching create_node's existing wiring from #1739/#2632. Two real bugs caught by the test suite during implementation and fixed before merge (stale self-referential-augment read, dropped collection-name-collision detection on the update path) — details in the PR description. Went through three independent adversarial review rounds; the deciding round found no remaining gaps.

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