Skip to content

Playbook execution under multi-device sync: derived identity, stable ordering, causal cycle depth, and catch-up suppression #1738

Closed

Description

@malibio

Overview

The playbook engine's execution semantics were specified for a single machine — rule evaluation atomicity is documented as "a safe assumption for single-user local-first desktop." Under Pro sync that assumption is false, and the resulting failures are silent (duplicate nodes, undetected loops) rather than loud.

Every device runs its own playbook engine. The sync apply leg writes pulled remote changes through NodeService, which emits ordinary domain events, and the engine's event handler dispatches on event shape and node type only — it never inspects the event's originating client. So a node created on device A fires the same rule on device A, B, and C.

Problem Statement

Verified against the current code:

  1. Remote-origin events are indistinguishable. PlaybookEngine::handle_event in packages/core/src/playbook/engine.rs matches on DomainEvent variant and node_type, then does trigger-key lookup. metadata.source_client_id is never read, even though sync already tags its own writes with a reserved client id ("sync-service") for echo suppression. The signal exists and is ignored.

  2. Duplicate create_node. N devices each create a node with its own identity. Sync merges all of them. There is no natural dedupe key, so one intended effect yields N nodes. This is the worst case.

  3. Duplicate add_relationship already converges. Benign — the push path derives edge ids as a deterministic UUIDv5 over (in_node, out_node, relationship_type), so every device derives the same id and the writes collapse to one row. This is the pattern the fix generalizes.

  4. Ordering diverges. packages/core/src/playbook/lifecycle.rs sorts rules by (playbook_created_at, rule_index). Playbooks are synced nodes created at wall-clock times on different machines, so clock skew or a different install order gives devices different evaluation orders — and chained rules reach different end states.

  5. Cycle detection is defeated across devices. Chain depth is carried in PlaybookExecutionContext { originating_event_id, depth, source_playbook_id }, built locally in the engine and attached to emitted events. It is not part of the synced node, so a chain that hops devices arrives with depth reset. N devices can sustain a loop in which none observes MAX_CHAIN_DEPTH, and the disable-the-playbook valve never trips.

  6. Conditions evaluate against divergent graphs. A device mid-catch-up holds a partial graph, so the same rule's conditions can pass on one device and fail on another. Effects become timing-dependent rather than a function of the data.

  7. Catch-up replays history. A reconnecting device applies a backlog through NodeService, firing playbooks across the entire history it just received.

Proposed Solution

Per ADR-060 §3 and §5:

  • Derived identity for reactive action outputs. An output node's id is a pure function of (rule_id, trigger_node_id, action_index), so N devices produce the same id and the writes collapse instead of forming N siblings. This works offline with no coordinating authority. Node ids are TEXT in both keyspaces and symbolic ids are already permitted, so no new machinery is required.
  • Non-idempotent actions are single-writer only. Where an action's output depends on model inference, a network response, or wall-clock time, derived identity cannot collapse it — the N nodes differ in content even where they share an id, and collapsing would silently discard N−1 real results. Such actions are declared non-idempotent; where sync is active, Pro elects a single writer and the rule does not run on non-elected devices.
  • Stable ordering. Sort cross-playbook rules by the playbook node's id, not created_at.
  • Causal cycle depth. Carry chain depth on the written node so it survives sync and is reconstructed by the receiving device rather than reset to zero.
  • Join-point suppression. Fire rules only for events at or after the device's join point — the cursor position at which it began observing live. Backlog applied during catch-up, and any historical replay, is applied as data without triggering evaluation. The effects already happened on the originating device and arrive as synced data.
  • Read the originating client so a sync apply is not mistaken for a local write.

Architecture Impact

  • ADR-060 (../nodespace-docs/decisions/060-playbook-execution-under-multi-device-sync.md) is the governing decision. This issue implements §3 (derived identity), §4 (single-writer election), and §5 (ordering, causality, catch-up).
  • architecture/playbook-system.md previously stated the single-user atomicity assumption as safe. It has been amended — the assumption is retired and the multi-device semantics are now specified there.
  • architecture/playbook-engine.md previously specified ordering by (playbook_created_at, rule_index). Amended to (playbook_id, rule_index), with the rationale recorded.
  • The companion nodespace-docs changes are already committed; no further docs work is required.

Acceptance Criteria

  • Rule dispatch reads the event's originating client and can distinguish a local write from a sync apply
  • Reactive action output node ids are a deterministic function of (rule_id, trigger_node_id, action_index)
  • Two engines processing the same trigger event produce writes that converge to one node, not two
  • Cross-playbook rule ordering keys on playbook id; two engines given the same playbook set in different creation order evaluate rules in the same order
  • Chain depth survives a device hop: a chain whose events cross the sync boundary accumulates depth and trips the cycle limit
  • A device applying a catch-up backlog fires no rules for events before its join point
  • An action declared non-idempotent does not execute on a device that is not the elected writer
  • Existing single-device playbook behavior is unchanged (no regression in the current playbook test suite)
  • Tests pass (bun run test:all)
  • Code passes bun run quality:fix

Technical Specifications

Reference Files

  • Engine: packages/core/src/playbook/engine.rs — handle_event, the RuleProcessor loop, PlaybookExecutionContext construction (cycle-depth propagation)
  • Ordering: packages/core/src/playbook/lifecycle.rs — OrderedRuleRef, playbook_created_at, lookup_rules
  • Actions: packages/core/src/playbook/actions.rs — execute_actions
  • Cycle limit: packages/core/src/playbook/logging.rs — MAX_CHAIN_DEPTH, PlaybookErrorType::CycleLimit
  • Event metadata: packages/core/src/db/events.rs — EventEnvelope, EventMetadata { source_client_id, playbook_context }
  • Sync client id: the reserved "sync-service" identity used by the echo gate in nodespace-sync
  • Edge identity precedent: the deterministic UUIDv5 edge_id(in_node, out_node, relationship_type) in the sync push path

Implementation Details

  • EventMetadata.source_client_id is already threaded through every event; the engine only needs to consult it. Do not add a parallel signal.
  • Derived ids must be stable across a playbook edit that does not touch the rule, and must change when action order changes (the action index is part of the key). Document this so a rule edit that reorders actions is understood to re-key its outputs.
  • Carrying depth on the node means a persisted field whose only purpose is loop detection. Keep it namespaced per the project's schema rules rather than adding a bare top-level property.
  • Join point is a sync-cursor concept (sync_seq), so the engine needs to know the device's live-observation cursor. Prefer suppressing at dispatch (the engine asks "is this event at or after my join point?") over having sync strip metadata, so that a non-sync install needs no special case.
  • The cron runner already sets an explicit source_client_id ("cron-runner") and checks it — follow that existing pattern rather than inventing a second convention.

Related Issues

Activity

  1. mstomar125 commented on Sep 12, 2026

    @mstomar125
    Contributor

    Status check against current main (0435c4d), since the epic hasn't moved in comments but has had real code land against it.

    Done, with evidence

    • Rule dispatch reads the event's originating client — done. packages/core/src/playbook/engine.rs's local-origin gate (ADR-073, landed in Wire playbook engine into daemon startup, hard-gated to local-only events #2575 / commit ba605ac2) checks EventEnvelope.source_client_id against SYNC_SERVICE_CLIENT_ID before any TriggerKey lookup.
    • Reactive action output ids are a deterministic function of (rule_id, trigger_node_id, action_index) — done, and generalized further than originally asked. Implement derived identity for playbook action outputs #2565 / PR merged as commit 3a6c53d5 added deterministic_action_output_id(rule_id, action_index, iteration_path) in packages/core/src/playbook/actions.rs, where iteration_path starts as [trigger_node_id] and gains one entry per nested for_each level — covering the scheduled/cron-scan case this issue's own criterion didn't anticipate (see ADR-074, referenced from Implement derived identity for playbook action outputs #2565).
    • "No firing on catch-up backlog" — satisfied, but by a blunter mechanism than ADR-060 §5 specifies. The ADR-073 gate landed by Wire playbook engine into daemon startup, hard-gated to local-only events #2575 excludes all sync-originated events from rule evaluation, not just backlog-before-join-point. There is no join-point/sync_seq cursor concept anywhere in the code. Worth flagging: ADR-060 §5 (and its own "Alternatives Considered" section) explicitly rejects "suppress rule firing for all sync-applied events" as a blanket policy for reactive rules ("a rule that only ever fires for your own edits is a different and much weaker feature"). ADR-073 does exactly that, as a deliberate interim stopgap per its own issue (Wire playbook engine into daemon startup, hard-gated to local-only events #2562) text: "Full ADR-060 support... is explicitly out of scope here and tracked separately." So this criterion's symptom (catch-up replay) is currently impossible, but not via the mechanism this issue asked for, and at the cost of reactive rules not yet firing on remote devices at all — which is itself a still-open piece of ADR-060's actual design.

    Not done

    Recommendation

    Leaving this issue open as the ADR-060 tracking issue rather than closing — #2577/#2578/#2579 now carry the three remaining concrete pieces, but #1738 is also the place documenting that the shipped interim solution (ADR-073's blanket sync gate) diverges from what ADR-060 §5 actually specified for reactive rules, which none of the three follow-ups individually own fixing. Relaxing that gate to the real join-point design is arguably a fourth piece of remaining scope; happy to file it separately if that's wanted, but wanted to surface the doc-gap/design-divergence finding here first rather than losing it in a follow-up issue.

  2. mstomar125 commented on Sep 12, 2026

    @mstomar125
    Contributor

    Correction to the docs-gap note in the comment above: ADR-073 and ADR-074 do exist — both are real, accepted decisions on nodespace-docs's origin/main (confirmed just now via git fetch origin main + git show origin/main:decisions/073-...md and 074-...md, both return real content, both Status: Accepted). The highest ADR present on origin/main is actually 075, not 066.

    The prior comment's claim came from a stale local checkout of nodespace-docs that was never fetched to origin/main before checking — the exact same trap a reviewer hit on 2026-09-11 during #2575's review (also resolved the same way: fetch first, then check). Everything else in the comment above (the ADR-073/ADR-060 §5 divergence itself, the three follow-up issues, the done/not-done breakdown) is unaffected by this correction — only the "the ADRs don't exist" line was wrong.

  3. mstomar125 commented on Sep 14, 2026

    @mstomar125
    Contributor

    The 'stable ordering' acceptance criterion of this epic (ADR-060 §5: cross-playbook rule ordering keyed on a stable identifier rather than created_at) is now closed via #2577 / PR #2605 — OrderedRuleRef::Ord now sorts on play_id instead of play_created_at. This epic stays open for its remaining acceptance criteria.

  4. mstomar125 commented on Sep 14, 2026

    @mstomar125
    Contributor

    The "causal cycle depth" acceptance criterion of this epic is now closed via #2578 / PR #2606 (not yet merged): playbook actions now persist chain depth onto the nodes they create/update (_playbookChainDepth, a _-prefixed internal-bookkeeping property), and rule_processor_loop's cycle check now falls back to that persisted depth when no in-process PlaybookExecutionContext is available — the shape a node takes after arriving via sync.

    This does not change the ADR-073 local-origin gate this epic still tracks (reactive rules currently don't fire on sync-applied events at all), so the fix isn't yet observable end-to-end over live sync until that gating relaxes — it just makes sure the depth is correct and consulted once it does, per #2578's own scoping. Leaving this issue open for the remaining acceptance criteria (derived identity / stable ordering / catch-up suppression, per the issue's other in-flight sub-work).

  5. malibio commented on Sep 27, 2026

    @malibio
    CollaboratorAuthor

    Closing as superseded — verified against current main (2026-09-27).

    This issue's full scope has already shipped, decomposed across later, more precisely-scoped work:

    The one piece of ADR-060 genuinely not implemented — single-writer election for non-idempotent actions (§4) — is already tracked with its own scoped issue: #2579. That's the actual remaining work; this issue's acceptance criteria are stale copies of ground already covered elsewhere.

    No code changes made against this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions