Repository navigation
Add reject action type for invariant playbook rules (ADR-060 §2) - #2644
Conversation
Adds ActionType::Reject: an invariant-only action whose entire effect is vetoing the triggering write rather than augmenting it. Save-time validation confines it to RuleClass::Invariant rules and requires a message param; existing eligibility checks (local-writes-only, same-graph-scope, non-chaining) apply to it unchanged or exempt it automatically, documented per check. Execution produces a new ActionError::Rejected, distinct from a generic action failure, and the two synchronous invariant-dispatch call sites translate it into NodeServiceError::PlayRuleRejected (modeled on VersionConflict) instead of InvariantRuleFailed. Refactors invariants.rs's single caller into a shared execute_matched_invariant_rules_in_tx so this reject-detection and the update_node wiring both run through one execution core. Adds OpsError::PlayRuleRejected and a daemon FAILED_PRECONDITION + x-play-rule-rejected metadata mapping. Co-Authored-By: Claude Sonnet 5 <[email protected]>
mstomar125
left a comment
There was a problem hiding this comment.
Second, independent adversarial review pass (separate from any other automated review on this PR).
Summary: I would block merge. One finding (#1 below) is a real, currently-unpatched gap in the exact "does save-time validation actually gate every real activation path" question this PR needs to answer correctly, given the transaction-integrity sensitivity of this code area and the precedent set by the #1739 double-execution bug caught only on adversarial re-review.
1. (Blocking) PlaybookEngine::load_active_plays does not call validate_play — the startup/reload path can reactivate a reject-on-Reactive rule unvalidated, disabling an entire play on first trigger
packages/core/src/playbook/engine.rs, load_active_plays (invoked from PlaybookEngine::start() on every daemon startup) calls lifecycle.activate_play(node) directly on every row from query_nodes_by_type("play", Some("active")), with no call to validate_play — unlike handle_play_created/handle_play_updated, which do validate.
Concretely: if a play with a reject action mistakenly declared on a Reactive rule ever lands in the store — e.g. via a replicated/synced write from another device that didn't route through this build's NodeService::create_node/update_node validation gate (ADR-060 is explicitly a multi-device-sync feature, and the store layer doesn't re-validate business rules on replicated writes), or via data written before this PR's RejectActionOnReactiveRule check existed — it reactivates unvalidated on every daemon restart. On its first reactive trigger, execute_reject always returns Err (there is no success path for it), so the existing "disable play on action failure" reactive-dispatch behavior fires and disables the entire play, not just the offending rule — silently taking out every other, unrelated rule in that play too.
This is exactly the class of bypass the task brief asked to hunt for: a real, non-test-harness path that constructs/activates a play without going through validate_play.
Note for the orchestrator: while investigating this I found that the shared worktree (.claude/worktrees/issue-2642-reject-action-type) currently has uncommitted, unpushed local changes to packages/core/src/playbook/engine.rs and packages/core/src/playbook/validation.rs that add exactly this validation call to load_active_plays, plus a related second fix (see #2 below). These are not part of PR #2644 as pushed to GitHub (confirmed via gh pr diff 2644 and git diff origin/main in the worktree) — so either another reviewer already found and is fixing this live, or it's stray WIP. Either way, PR #2644 as it currently stands on GitHub does not have this protection; whatever produced those local edits needs to actually get committed, pushed, and re-reviewed before merge.
2. (Related, same root cause) No validation rejects reject + for_each on the same action
A reject action can declare a for_each. Since execute_reject always errs, this only ever fails on the very first iterated item — but if the resolved collection is empty, the for_each loop body never runs and the action silently no-ops, vetoing nothing, with no save-time or runtime warning. Not a data-integrity bug (nothing gets corrupted), but a silent-no-op correctness hazard for exactly the type of rule whose entire job is to veto a write. (The same uncommitted worktree changes referenced in #1 also add a PlayValidationError::RejectActionHasForEach check for this — again, not yet on the pushed PR.)
3. (Medium) A pure single-binding message (e.g. "message": "{node.priority}" where priority is numeric) causes the wrong error type and loses the author's message
execute_reject (packages/core/src/playbook/actions.rs) does params.get("message").and_then(|v| v.as_str()). But resolve_bindings_in_string's documented fast path (same file) says: "If the entire string is a single {binding}, the resolved value is returned directly (preserving its JSON type: number, bool, object, etc.)." So "message": "{node.priority}" against a numeric priority field resolves to Value::Number, not Value::String — .as_str() returns None, and execute_reject returns ActionError::MissingParam { param: "message" } instead of ActionError::Rejected.
Consequences:
invariants.rs'sif let ActionError::Rejected { message, .. } = &errcheck doesn't match, so the caller gets the genericNodeServiceError::InvariantRuleFailedinstead ofPlayRuleRejected— silently breaking the ADR-060 §2 contract that a rejection is reported distinctly.- The author's actual violation text is lost entirely; the surfaced error is a confusing "missing param 'message'" instead.
- Save-time validation can't catch this:
validate_reject_actiononly checks that the params.message literal (pre-binding-resolution) is a non-empty JSON string, which"{node.priority}"trivially is. - The write is still blocked either way (fails closed), so this isn't a data-safety bug — but it's a real, reachable correctness bug in the PR's own stated contract ("message... may use
{binding}interpolation like every other action's params"), and no test in this diff exercises a binding-based message.
Fix would live in execute_reject: when the resolved value isn't a string, stringify it (mirroring what the multi-binding interpolation path already does) rather than treating it as a missing param.
4. (Low-medium, forward-looking) x-play-rule-rejected gRPC metadata silently drops for non-ASCII rejection messages
packages/daemon/src/services/node_service.rs's ops_error_to_status builds the x-play-rule-rejected metadata by JSON-serializing {node_id, play_id, rule_id, message} and parsing it as tonic::metadata::MetadataValue<Ascii>, silently dropping the whole payload on parse failure (if let Ok(val) = ...). This mirrors x-subtree-inaccessible-count's existing pattern, but that payload is just an integer — always ASCII. PlayRuleRejected's payload embeds the author-supplied, free-text message, which is exactly the kind of field likely to contain non-ASCII characters (accents, non-Latin scripts, emoji) for real-world, possibly-internationalized violation text. MetadataValue<Ascii> rejects any non-ASCII byte, so any such message causes the entire structured payload to vanish — the plain gRPC status message text still carries it, but the structured metadata the planned #2643 frontend work would key off to recognize this error type specifically silently disappears for exactly the messages most likely to need special UI treatment. Doesn't block this PR's own scope (nothing consumes the metadata yet), but worth fixing now since #2643 will build directly on this wire contract — likely fix is a -bin suffixed gRPC metadata key (base64, binary-safe) instead of a plain ASCII key.
5. (Style/process) Issue numbers embedded in code comments — violates this repo's own CLAUDE.md rule
CLAUDE.md: "Do not embed GitHub issue numbers in documentation content or code comments — describe the behavior/constraint directly, and reference decisions by ADR." This diff adds #2642/#2643 references directly in doc comments in packages/core/src/playbook/actions.rs, packages/core/src/playbook/validation.rs, packages/core/src/services/node_service/invariants.rs, and packages/core/tests/playbook_invariant_integration_test.rs. Mechanical fix, but it's an explicit, stated repo rule.
What I checked and found solid:
- The reject+augment same-rule rollback (both orderings) genuinely rolls back via the pre-existing
with_transaction/create_node_in_txmechanism from #1739 —rejectdoesn't introduce any new side-channel; it just returnsErrthrough the sameActionResult::Failed→?propagation every other action failure already uses, and the bufferedNodeCreatedevent is discarded on rollback per ADR-069 §2. The PR's own two adversarial integration tests correctly verify this via unchangedversionon the bystander node. is_local_write,target_id_params,check_invariant_self_chaining, andcheck_schema_change_impact's matches overActionTypeare all exhaustive (no wildcard) and correctly classifyReject— confirmed by reading each match arm directly, not just trusting the doc comments.- The daemon's
x-play-rule-rejectedvsx-subtree-inaccessible-countmetadata-key separation is explicitly tested for non-collision (error_mapping_play_rule_rejected_is_distinguishable_from_subtree_access_denied).
🤖 Generated with Claude Code
- Re-validate a play at startup load (load_active_plays), not just at save time: a reject-on-Reactive rule that reached the DB without going through today's save-time gate (an earlier build, a differently-validated device under multi-device sync) would otherwise reactivate unvalidated on every restart and disable its entire play the first time its trigger fired, since execute_reject always errors. Give the reactive-dispatch loop a distinct diagnostic for this case instead of the generic "action failed" message. - Reject a reject action declaring for_each at save time: its condition already gates whether it fires, and iterating it over a collection adds a silent-no-op hazard (an empty resolved collection never runs the loop body) with no offsetting benefit. - Fix execute_reject to accept a message binding that resolves to a non-string JSON scalar (e.g. a numeric property), rendering it as text instead of misreporting a successfully-resolved binding as a missing param and losing the author's message. - Add daemon-layer test coverage for the PlayRuleRejected -> FAILED_PRECONDITION + x-play-rule-rejected mapping, mirroring the existing VersionConflict/SubtreeAccessDenied coverage. - Remove issue-number references from code comments per repo convention; describe behavior directly and reference ADR-060. Co-Authored-By: Claude Sonnet 5 <[email protected]>
… fingerprint collision (post-#2644 follow-up) (#2649) * Fix x-play-rule-rejected non-ASCII metadata drop and validation-error fingerprint collision (#2647) ops_error_to_status's PlayRuleRejected arm parsed its JSON metadata payload as MetadataValue<Ascii>, silently dropping the whole payload (via `if let Ok(...)`) whenever the author-supplied rejection message contained a non-ASCII byte (em dash, curly quotes, accents, emoji). Switch to gRPC's binary-metadata convention: a `-bin`-suffixed key (x-play-rule-rejected-bin) carrying the payload via MetadataValue::<Binary>::from_bytes, which is infallible. Also rename the misnamed `rule_id` field (it has always held the rule's author-given name, not an id) to `rule_name` across OpsError, NodeServiceError, and their call sites. load_active_plays/handle_play_created/handle_play_updated each passed a constant rule_name="validation" and error_location_index=0 into create_or_update_log_node for every validate_play error on a play. error_fingerprint hashes (play_id, rule_name, error_location_index, error_type) and deliberately excludes the error message, so two structurally different errors on the same play collapsed onto the same fingerprint — the second error's text was silently discarded and the surviving log node's occurrences count misleadingly implied a repeat of one issue. Add PlayValidationError::location()/kind() accessors and fold "{location}:{kind}" into the fingerprint identity via a new shared log_validation_errors() helper used by all three call sites, so distinct errors produce distinct log nodes. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Disambiguate same-location validation-error fingerprints within one validate_play pass log_validation_errors folded each error's (location, kind) into its create_or_update_log_node fingerprint identity, but that pair isn't unique within a single validate_play call: a validator can legitimately push more than one same-kind error at the same location in one pass — e.g. InvariantOutOfScopeTarget checking both source_id and target_id on one add_relationship action, or a CEL condition referencing two broken dot-paths (BrokenPath is pushed once per path, with the location computed once per condition). Those still collided onto one fingerprint, silently discarding every error but the first at that spot — a narrower instance of the exact collision #2647 set out to fix. Suffix each error's identity with its ordinal among prior errors sharing its (location, kind) within the same errors slice (omitted for the first/only one, so the common case is unaffected). validate_play iterates rules/conditions/actions in a fixed order, so the ordinal is deterministic and stable across repeated validation passes over an unchanged play — re-validation still maps back to the same existing log nodes rather than spawning duplicates. Add a regression test covering the two-broken-paths-in-one-condition case end to end through the real engine; mutation-tested by reverting the fix and confirming the test fails against the unfixed code. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Add regression coverage for two more same-(location,kind) collision shapes Covers the InvariantOutOfScopeTarget case (add_relationship with both source_id and target_id set to literal, non-binding node ids) and the InvariantNonDeterministic case (a condition calling two different non-deterministic functions), both exercising the ordinal-suffix disambiguation added in the prior commit through the real engine end to end. Co-Authored-By: Claude Sonnet 5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
Summary
Adds
ActionType::Reject(ADR-060 §2) — a playbook action type whose entire effect is vetoing the triggering write, rather than augmenting it. Usable only onRuleClass::Invariantrules.ActionType::Reject(JSONaction_type: "reject"), requires aparams.message(author-supplied violation text; may use{binding}interpolation like every other action's params).PlayValidationError::RejectActionOnReactiveRulerejectsrejectdeclared on a non-Invariantrule, checked unconditionally for every rule (not just invariant-class ones, since the whole point is catching the wrong class).reject'smessageparam is required (MissingActionParamotherwise). Against the existing §2 eligibility checks,rejectis automatically exempt from "local writes only" (no I/O — trivially local) and "same-graph scope" (addresses no node — same exemptioncreate_nodealready has); it can never trip "non-chaining" since it creates/updates nothing.ActionError::Rejected { message, action_index }— reachingexecute_rejectat all IS the rejection (there's no success path). It propagates through the existing action-executor loop exactly like any other action error (short-circuits remaining actions in the rule), but the two synchronous invariant-dispatch call sites (today:create_node's;update_node's per Wire RuleClass::Invariant rules into the write path so they actually run synchronously, in-transaction #2643) detect it specifically and return a newNodeServiceError::PlayRuleRejected { node_id, play_id, rule_id, message }— modeled onVersionConflict— instead of the genericInvariantRuleFailedevery other action failure produces.invariants.rs's single caller into a sharedexecute_matched_invariant_rules_in_txso both Add a reject/validation action type so an invariant Play can veto a write, not just augment it #2642's reject-detection and Wire RuleClass::Invariant rules into the write path so they actually run synchronously, in-transaction #2643'supdate_nodewiring run through one execution core, not two independently-maintained copies.OpsError::PlayRuleRejected+ daemonops_error_to_statusmapping (FAILED_PRECONDITION+x-play-rule-rejectedmetadata, mirroringx-subtree-inaccessible-count's pattern) — required for theNodeServiceErrormatch to stay exhaustive, and already reachable today viacreate_node's existing invariant path.Per #2642's own scope: this does not wire
update_nodeinto synchronous invariant dispatch — that's #2643, which this PR is a prerequisite for. The end-to-end test here usescreate_node's already-existing synchronous invariant path (from #1739) as the harness.Adversarial cases covered
rejectas action[0] with an augmenting action after it in the same rule → the augmenting action never runs (asserted via the target node's unchangedversion).rejectas action[1] → the whole transaction rolls back, undoing the already-applied augmenting write too (not just "the triggering node doesn't exist").rejectdeclared on aReactiverule → rejected at save time (RejectActionOnReactiveRule), both as a unit test and end-to-end throughvalidate_play.rejectwithoutmessage→ rejected at save time (MissingActionParam).PlayRuleRejected(carryingnode_id/play_id/rule_id/message), not the genericInvariantRuleFailed.Test plan
cargo test -p nodespace-core --lib— 1392 passed, 0 failed (includes newtypes.rs/validation.rs/actions.rsunit tests).cargo test -p nodespace-core --test playbook_invariant_integration_test— 15 passed, 0 failed (6 new reject-specific tests + all 9 pre-existing invariant tests from Introduce invariant vs reactive playbook rule classes with synchronous pre-commit execution on the origin device #1739 still green).cargo clippy -p nodespace-core -p nodespace-daemon --all-targets— clean.bun run test:all— green (coverage/scripts/skill/rust:test all pass; the one environmental gap —nodespace-app's gitignored sidecar binaries missing on a fresh worktree — resolved viabun run build:sidecars --debug, unrelated to this change).🤖 Generated with Claude Code