Skip to content

Give plays a user-owned enabled switch and persist engine suspensions (closes #3444) - #3489

Merged
malibio merged 1 commit into
mainfrom
issue-3444-play-enabled-switch
Oct 2, 2026
Merged

malibio merged 1 commit into
mainfrom
issue-3444-play-enabled-switch

Conversation

@malibio

@malibio malibio commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

Closes #3444

What changed

A play now has its own user-owned switch, enabled, and the engine's verdicts are suspensions recorded on the play node. Whether a play runs is one check (ADR-087 §5).

Type: play is a structured core type, category unchanged. No new type, relationship or structural rule.

Fields added to the play schema

Field Type Protection local_only Default
enabled boolean core no true
suspended_reason enum: validation_failed, action_failed, cycle_limit, schema_drift (closed) system yes none
suspended_message text system yes none
suspended_at datetime system yes none
  • Wire: PlayNode carries enabled, suspendedReason, suspendedMessage and suspendedAt. PlayNodeUpdate gains enabled; the suspension fields are read-only. PlaySuspensionReason is a new generated TypeScript type, and promoted fields gain a boolean shape.
  • Runnable check: PlayStatus::of_node (participates, then enabled, then not suspended) followed by rule validation, in one engine function (sync_play) used at startup, on create and on update. The engine no longer compares a play's lifecycle anywhere.
  • Suspension write: NodeService::record_play_suspension sets the three fields with no version bump and emits a node-updated event. enabled is never touched.
  • Clearing: a write that sets enabled: true (even when it already is) or changes rules clears the suspension; the engine re-validates and suspends again if the problem remains. A client write that names a suspension field is refused.
  • Rule validation runs only when rules change, so a switch-only write succeeds for a play whose rules a schema change has broken.
  • Engine defects fixed:
    • after an action failure, the play's later rules in the same work item are skipped;
    • a play created with invalid rules is suspended and known to the engine, instead of a no-op disable;
    • a parse failure on update suspends the play instead of dropping it;
    • a rule queued before its play was switched off, archived or suspended no longer runs.
  • Seeded-play warning (ADR-060 §8) fires when enabled goes true → false or the rules are edited. It no longer fires on other edits or on archive.
  • CLI: playbook enable|disable write enabled through the typed play update. playbook list reports each play as on, off or suspended (with reason, time and diagnostic), with its lifecycle beside it, and adds state to each node in --json. Archive is not folded into the state: the CLI doesn't interpret lifecycle_status. logs is gone from the playbook help.
  • Skill guidance: references/cli.md teaches enabled, the states and how to clear a suspension, and no longer teaches archiving as a play's switch. SKILL.md needed no change; the drift check passes.
  • Workspace context lists only plays that run, and reads a play's description from its bucket (it read the wrong key and was always empty).

Found along the way

Schema-drift detection never ran. handle_schema_updated read the changed type from properties.schema.forNodeType, which nothing writes, so it returned before checking any play. It now uses the schema node's id (which is its type) and schemaVersion. This makes drift suspension live: a schema update that genuinely breaks a play's rules now suspends it with schema_drift. Additive changes still stop nothing.

Not covered

A switch-only write still fails for a play whose stored rules don't decode at all (a row written around the service layer), because the play behaviour decodes every field on each write. Rules that decode but no longer validate, which is what a schema change produces, are covered. The engine suspends an undecodable play either way.

Docs

nodespace-docs c6e0c32 (direct to main): components/node-types.md play sheet (typed update, wire) and architecture/playbook-engine.md schema-drift section. The rest of the playbook docs already described this design.

Tests

  • Engine: disabled, archived, suspended and invalid plays don't run; a queued rule of a play disabled since doesn't run; action failure suspends and skips later rules, another play's rules still run; cycle limit and schema drift suspend; a suspension survives a restart, leaves enabled on, bumps no version and emits an event; enabling or saving fixed rules clears it; a still-broken play is suspended again; a parse failure on update suspends.
  • Service: switch-only write on a play with invalid rules; suspension fields refused in flat and bucketed patches.
  • Types: decode, defaults, wire keys, typed update; schema/promoted-field pin test covers the new fields.
  • CLI: state derivation, list line, help verbs, enable/disable/list round trips over gRPC.
  • Frontend: normalizer promotes the switch and suspension.

🤖 Generated with Claude Code

@malibio

malibio commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3489

Review Type: Initial Review (no prior reviews or comments on the PR)

Summary

This is a clear net improvement. The engine's run state is now derived from the play node in one function (sync_play), the engine's verdicts are persisted without touching the user's switch, and three real defects are fixed. The design matches ADR-087 §5 and playbook-engine.md closely.

There are no blockers. Two narrow correctness gaps are worth fixing in this PR (findings 1 and 2), and the test suite never runs the subscriber and the rule processor together (finding 3).

How I checked. I read the full diff and the surrounding code in engine.rs, lifecycle.rs, crud.rs, bulk.rs, the store's writer and transaction code, and the docs named in the issue. I ran check-lifecycle-reads, check-node-type-literals and check-pro-boundary; all three pass. I did not run the Rust tests, types:check or test:changed, so the findings below come from reading the code, not from a failing test.

Requirements Check

# Acceptance criterion Status Notes
1 play schema declares enabled and the three local_only suspension fields ✅ core_schemas.rs:1436-1531. enabled is boolean, Core, default true, synced. The suspension fields are System and local_only; the reason is a closed enum built from PlaySuspensionReason::ALL.
2 Engine never reads lifecycle_status; runnable is one check (tests: disabled, suspended, archived, invalid) ✅ PlayStatus::of_node plus sync_play. No lifecycle comparison is left in the engine, and the checker passes. All four states have tests in run_state_tests.
3 An engine failure writes a suspension that survives a restart and leaves enabled unchanged ✅ a_suspension_survives_a_restart_and_leaves_the_switch_on. The restart is a new engine plus load_plays on the same store, which is a fair stand-in.
4 enabled: true or fixed rules clears a suspension ✅ Three tests cover enable, still-broken re-suspension and fixed rules. See finding 2 for a subtype of play.
5 Switch-only write succeeds for a play with invalid rules ✅ a_switch_only_write_succeeds_for_a_play_with_invalid_rules; it would fail on main. The undecodable-rules case is disclosed in the PR body.
6 Later rules skipped after an action failure; created-disable and parse-failure defects fixed ✅ Each has a test that would fail on main.
7 CLI enable/disable/list use enabled and the suspension fields; logs gone from help ✅ Round-trip tests over gRPC, plus the help-verbs test.
8 Skill guidance teaches the new switch, not lifecycle; drift check passes ⚠️ cli.md is correct and the contradiction is gone. SKILL.md:271 still says only "managed with query/node update" and never names `playbook enable
9 Follows the node type sequence; node-types.md and playbook docs updated ✅ Registry, schema, wire type, generated TS, typed update and tests are all present. nodespace-docs c6e0c32 updates the play sheet; playbook-system.md and playbook-engine.md already describe this design. See finding 1 for the write path.
10 test:changed passes; quality:fix clean Not verified I ran only the three lint checkers.

Code Review Findings

🟡 Important

1. The suspension-field guard and the clear-on-enable rule cover only one write path
📁 packages/core/src/services/node_service/crud.rs:1773-1786, 2533-2564; create at crud.rs:597-626

apply_play_patch is called only from update_with_version_check_returning_node_in_tx. Nothing else refuses a suspension field, and the schema's System protection is not enforced on value writes (it only governs schema edits).

  • Create. create_node_in_tx accepts a play whose payload carries suspended_at, suspended_reason or suspended_message. nodespace node create --type play --property suspended_at=... produces a play that is born suspended. cli.md and node-types.md both say a write naming one of these fields is refused.
  • Play actions. An update_node action goes through update_node_in_tx (actions.rs:2368). A rule targeting a play node can write or null the suspension fields, and setting enabled: true there does not clear a suspension.
  • Unchecked and bulk paths. update_node_unchecked* and bulk_update skip it too. No client reaches these for plays today, so this is only a trap for later.

Recommendation: put the guard in one helper that create and every update pipeline call, and add a create test next to a_client_cannot_write_a_suspension_field. Principle: a single enforcement point for an invariant the docs state without qualification. Confidence: high for create and the action path.

2. A rules edit on a subtype of play skips the save-time gate and does not clear a suspension
📁 packages/core/src/services/node_service/crud.rs:1777-1786, 2545-2548

rules_changed compares PlayFields::stored_field(.., "rules") on existing and updated before rebucket_and_validate runs. For a node whose type extends play, a flat {"rules": [...]} patch is normalized into the node's own bucket (normalize_flat_properties_to_namespace), while stored_field reads the play bucket. At that point the two are equal, so rules_changed is false.

  • validate_play_rules is skipped. On main the gate ran on any properties patch for anything that type_is_a play, so this is a regression for subtypes.
  • The suspension is not cleared when fixed rules are saved.

The engine still catches bad rules afterwards and suspends the play, so nothing invalid runs. The save is accepted where it used to be refused. Core ships no play subtype today, but the engine deliberately treats one as a play (handle_event resolves the chain).

Recommendation: compute rules_changed after rebucket_and_validate, or decide it from the patch and compare after re-bucketing. Add a test with a schema that extends play. Principle: subtypes add rules and never relax them. Confidence: medium-high.

3. No test runs the subscriber task and the rule processor together
📁 packages/core/src/playbook/engine.rs:2710+ (run_state_tests), packages/core/tests/it/playbook_engine_integration_test.rs

Every new engine test calls handle_play_* directly and runs rule_processor_loop alone on a hand-built work item. The only test that goes through engine.start() is the suspended-at-load one. So the property the design depends on, that the engine's own NodeUpdated for a suspension comes back through the subscriber and changes nothing, is argued in comments but never exercised.

I traced it and believe it holds. A suspended node takes the park path in sync_play, which writes nothing, so the event cannot chain. The store's single writer with BEGIN IMMEDIATE means the un-versioned json_set cannot be lost to a version-checked update, because that update reads existing inside its transaction.

Recommendation: one spawn_engine test. A play with a failing action fires from a real node create. Assert that the node carries action_failed, the lifecycle status is Suspended, a second trigger does not fire the play, and the play's version is unchanged. Principle: test the interaction that carries the risk.

🟢 Suggestions

4. A lagged subscriber leaves the in-memory status stale
📁 packages/core/src/playbook/engine.rs:126-128, 352-412

sync_play holds a node snapshot across the validate_play await and then calls reenable_play. If the processor suspends the play in that window, the stale snapshot re-indexes it. This heals when the suspension's own event is handled next, because the subscriber is sequential. It does not heal if that event is dropped: RecvError::Lagged only logs. The handling of lag is not new, but the status is now documented as a cache of the node. Calling load_plays() again on Lagged would be a cheap resync.

5. A transient action failure is now a persistent outage with no in-app signal
📁 packages/core/src/playbook/engine.rs:1486-1499, actions.rs:1859, 2371

A version conflict in an update_node action is an action failure with no retry. On main a restart undid the disable. Now the play, including the seeded task-completion rollup, stays off until someone runs playbook enable, and there is no Plays UI yet. This is the documented design, so it does not block. Since park_play logs at info without the reason, a warn at load for each suspended play, with reason and time, would make it visible in the daemon log.

6. Rules of a deleted play still run from a queued work item
📁 packages/core/src/playbook/lifecycle.rs:309-313, engine.rs:1305-1320

is_parked is false for an unknown play. If such a rule's action fails, suspend_play returns false, nothing is parked, and the play's later rules in the same work item run too. Skipping unless the play is known and Runnable would close this.

7. park_play compiles rules under the write lock
📁 packages/core/src/playbook/lifecycle.rs:262-281

playbook-engine.md says lifecycle operations prepare data before taking the lock. park_play calls parse_play_rules (CEL compilation) while holding it, and the runnable path parses twice: once in sync_play and again inside reenable_play. Passing the parsed rules in would fix both.

8. SKILL.md does not name the new switch
📁 packages/skill/SKILL.md:271

The issue asks SKILL.md to teach playbook enable|disable and enabled. The line still reads "managed with query/node update". One clause in the generator source would satisfy the criterion.

9. Archiving a seeded invariant play no longer warns
📁 packages/core/src/playbook/seeded.rs:54-68

This follows ADR-087 §5 literally and a test pins it. ADR-087 §6 also says archiving is how a user turns a seed off, and the consequence is the same as switching it off: the invariant stops being enforced. Worth a product decision; no code change requested.

Nit: core_schemas.rs:1450 declares play.enabled as indexed: true, while tool.enabled at line 1695 is false. Nothing filters plays by it in SQL (context_ops filters in Rust).

What is done well

  • sync_play re-reads the node instead of trusting the event payload, so handling is idempotent and the engine's own write is a no-op by construction.
  • suspend_play returning was_running gives one suspension per failure without extra bookkeeping.
  • The schema-drift fix is a real find. The handler read a key nothing writes and never ran.
  • The per-rule cost on the hot path is one read-lock map lookup.

Recommendation

APPROVE

No blockers. Findings 1 and 2 are small and should be fixed in this PR; finding 3 is the test I would add with them. I have not confirmed 1 or 2 by running code.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed (commits b908df77, b24c78e5)

# Finding Outcome
1 🟡 Suspension guard and clear-on-enable covered one write path Fixed. One helper, settle_play_update, runs on all four update pipelines and on bulk update. Create refuses a play that carries a suspension.
2 🟡 A rules edit on a subtype of play skipped the gate and didn't clear a suspension Fixed. The helper runs after re-bucketing, so the rules are read from the bucket they live in. Test with a schema extending play.
3 🟡 No test ran the subscriber and the rule processor together Added an_action_failure_in_a_running_engine_suspends_the_play_until_it_is_enabled: real node create, failing action, suspension on the node, no version bump, play stops firing, enable brings it back.
4 🟢 A lagged subscriber left the run state stale Fixed. On Lagged the engine reloads plays; a reload forgets plays no longer in the store's load.
5 🟢 A persistent suspension had no visible signal Added a warning at load for each suspended play, with reason, time and diagnostic.
6 🟢 A deleted play's queued rule still ran Fixed. A rule runs only while its play is known and running (is_running replaces is_parked).
7 🟢 Rules compiled under the write lock, and twice Fixed. Compiled once in sync_play, before any lock; park_play and reindex_play take the compiled rules.
8 🟢 SKILL.md didn't name the switch Fixed, in one line: the file was 2 characters under its 5,000-token cap, so the detail stays in references/cli.md.
9 🟢 Archiving a seeded invariant play no longer warns Skipped. It follows ADR-087 §5 as written and a test pins it. Whether archive should warn too is a product decision.
nit play.enabled indexed Fixed: not indexed.

One refinement while fixing #1. A write is refused when it would change a suspension field, not when it merely names one. An update that carries a field's stored value back unchanged is accepted. Clearing a recorded suspension by writing null is still refused: enabling the play is how it is cleared. cli.md and the node-types.md play sheet (nodespace-docs b31e7dd) say this.

Tests: the full Rust workspace suite passes (4,394 tests); frontend, scripts and generated-type checks passed in the same test:changed run. quality:fix is clean.

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: Findings 1, 2, 4 and 6 changed logic on the write path and in the engine (a new helper on five pipelines, a reload on lag, a stricter run check in the rule processor).

@malibio

malibio commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3489 (re-review)

Review Type: Re-Review (commits b908df77 and b24c78e5, on top of db80e71b)

Previous Review Summary: 9 findings plus 1 nit. 8 findings and the nit are addressed, 1 was skipped with a reason that holds. No new Critical or Important issues; 3 new suggestions and 1 nit, none blocking.

How I checked. I read the diff db80e71b..HEAD and the surrounding code: the four update pipelines and the create path in crud.rs, bulk_update and bulk_create in bulk.rs, load_plays, sync_play, the subscriber loop and the rule processor in engine.rs, the lifecycle manager, type_ancestry.rs, and PlayFields in nodespace-types. I ran the 25 tests in run_state_tests, the two lifecycle tests and the new integration test with nextest; all pass. I did not run the full suite, types:check or the lint checkers again.

Per-finding status

# Finding Status
1 Suspension guard and clear-on-enable covered one write path Addressed. settle_play_update runs in all four update pipelines and in bulk_update, and insert_node_in_tx_no_invariant_dispatch refuses a play created with a suspension. bulk_create is not covered (new finding A).
2 A rules edit on a subtype of play skipped the gate and didn't clear a suspension Addressed. The helper runs after rebucket_and_validate, so the rules are compared in the play bucket. a_subtype_of_play_is_held_to_the_same_rules would fail on the old ordering.
3 No test ran the subscriber and the rule processor together Addressed. The new integration test goes through spawn_engine and a real node create.
4 A lagged subscriber left the run state stale Addressed. Lagged calls load_plays, which now forgets plays missing from the load. See new finding B for what is left.
5 A persistent suspension had no visible signal Addressed. load_plays warns for each suspended play with reason, time and message.
6 A deleted play's queued rule still ran Addressed. is_running replaces is_parked; the deleted-play test would fail on the old check.
7 Rules compiled under the write lock, and twice Addressed. sync_play compiles once before any lock; park_play and reindex_play take the compiled rules.
8 SKILL.md didn't name the switch Addressed, in one line.
9 Archiving a seeded invariant play no longer warns Skipped; the reason holds. ADR-087 §5 lists exactly two triggers for the warning (enabled going true → false, and a rules edit). Adding archive would go beyond the ADR, so it is a product decision, not a code defect.
nit play.enabled indexed Addressed.

What I checked in the new logic

  • Ordering against validation. In every pipeline the helper runs after rebucket_and_validate. The fields it nulls on a clear are therefore not re-validated, which is fine: null is the stored form of a cleared field, and stored_field reads null as absent. A forged value that is not in the enum is now refused by schema validation before the guard sees it; either way the write fails.
  • Cost on nodes that are not plays. type_is_a answers from the registry for a core type, with no read. For a user-defined type it is one indexed read of type_ancestry per update, where rebucket_and_validate already resolves the whole chain. The version-checked path used to ask only when a properties patch was present and now asks on every update; the extra read is negligible.
  • A reload while the rule processor is mid-work-item. reindex_play and park_play each swap a play's entry under one write lock, so a running play is never briefly absent and is_running cannot skip a rule by accident. retain_plays cannot drop a play created during the reload, because plays are only registered by the subscriber task, which is the task running the reload. The cron registry holds no per-entry state, so re-indexing loses nothing.
  • The "unchanged value is accepted" refinement. It compares stored values, so a client that sends a suspension field back as it read it is not refused, and writing null over a recorded suspension is. The tests cover both.
  • Would the tests fail without the fixes? Yes for the forged-field, create, subtype, deleted-play and reload tests. The integration test covers behaviour that already held; it was the missing coverage, not a fix.

New Findings

A. 🟢 Suggestion — bulk_create creates a play with neither the suspension guard nor the rule gate
📁 packages/core/src/services/node_service/bulk.rs:128-200

bulk_create validates and re-buckets each node but never asks whether it is a play, so a play created through it can carry suspended_* and unvalidated rules. The rule gate was already missing there on main. Only benches call it today, and bulk_create_hierarchy* is only reached with markdown-import node types, so no client can reach this. The play sheet in node-types.md now says creating a play with a suspension set is refused, without qualification. Calling ensure_play_created_unsuspended and validate_play_rules there would make that true on every create path. Principle: one enforcement point per invariant. Confidence: high that the gap exists, high that nothing reaches it.

Related, and unchanged from main: the three non-version-checked update pipelines and bulk_update discard the helper's rules_changed result, so a play's update_node action can save rules that don't validate. The engine suspends the play afterwards, so nothing invalid runs. Worth knowing; no change requested.

B. 🟢 Suggestion — the Lagged branch has no test, and a reload reads a snapshot
📁 packages/core/src/playbook/engine.rs:126-138, 314-363

  • a_reload_rebuilds_the_run_state_from_the_nodes calls load_plays directly. Nothing exercises the RecvError::Lagged arm, so deleting the call there would fail no test. A test that overflows the 4,096-event channel is heavy; this is acceptable as is.
  • load_plays queries the nodes once and then validates each play with awaits in between. If the rule processor suspends a play after the query, sync_play re-indexes it from the stale snapshot. It heals: the suspension's NodeUpdated is emitted after the reload began, so it is still in the channel and is handled next. This is the same window the first review described for sync_play, now also reachable from a reload.
  • Under sustained lag (a large import) each Lagged triggers a full reload that validates every play and logs every suspended one again. The number of plays is small, so this is a cost note only.

C. 🟢 Suggestion — the refusal message can contradict the write it refuses
📁 packages/core/src/services/node_service/crud.rs:2550-2556, 2577-2593

The guard runs before the clear. A patch on a suspended play that sets enabled: true and also carries the suspension fields as null (a client echoing a snapshot it read before the suspension, which bumps no version) is refused with "Set 'enabled' to true to clear a suspension", which is what the patch did. The typed play update never sends these fields, so only a raw properties write reaches it. The same message is used on create, where there is no suspension to clear. Skipping the comparison when the write clears the suspension anyway, or a create-specific message, would fix both. Confidence: high on the behaviour, low on anyone hitting it.

Nit: packages/core/src/playbook/lifecycle.rs:323-327 — reenable_play has no production caller now that the engine uses reindex_play; only two tests call it. The repo rule is to delete unused code, and it is the last place rules are compiled under the write lock.

Recommendation

APPROVE

The two Important findings are fixed at the right layer, with tests that fail without the fixes. The new suggestions are edge cases that no current caller reaches.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review (re-review): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed (commit 261f2a13)

Finding Outcome
A 🟢 bulk_create creates a play with neither the suspension guard nor the rule gate Guard added: a batch create refuses a play carrying a suspension, with a test. Rule gate skipped: it was absent before this change, nothing reaches that path for plays, and the engine suspends an invalid play anyway. Revisit if a client ever creates plays in batches.
B 🟢 The Lagged branch has no test; a reload reads a snapshot Skipped. A test needs to overflow the 4,096-event channel; the reload it calls is tested directly. The snapshot window heals on the next event, as the review notes.
C 🟢 The refusal message can contradict the write it refuses Fixed. A write that clears the suspension anyway (enabled: true, or changed rules) may also carry the suspension fields as null. Create has its own message.
nit reenable_play has no production caller Removed.

Tests: the full Rust workspace suite passes (4,394 tests) and quality:fix is clean.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The changes are a one-line guard on one more create path, a narrower refusal condition with a test for it, and the removal of an unused method. No design or control-flow change.

@malibio

malibio commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Merge queue: #3489 was taken out of the queue — it conflicts with main in: packages/core/src/services/node_service/schema.rs. Rebase onto origin/main, push, and re-run bun run merge 3489.

@malibio
malibio force-pushed the issue-3444-play-enabled-switch branch from 261f2a1 to d20f859 Compare October 2, 2026 12:00
@malibio
malibio force-pushed the issue-3444-play-enabled-switch branch from d20f859 to 350fde2 Compare October 2, 2026 12:08
@malibio
malibio merged commit 899c991 into main Oct 2, 2026
@malibio
malibio deleted the issue-3444-play-enabled-switch branch October 2, 2026 12:08
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.

Give plays a user-owned enabled switch and persist engine suspensions

1 participant