Repository navigation
Wire RuleClass::Invariant rules into update_node's write path (ADR-060 §2) - #2650
Conversation
…0 §2) Relaxes InvariantUnsupportedTrigger to accept property_changed triggers alongside node_created. Adds dispatch_invariant_rules_for_update_in_tx (the update_node twin of the existing create-path dispatch), reusing trigger_keys_for_event for exact/wildcard matching and the shared execute_matched_invariant_rules_in_tx execution core so the reject-action distinction holds identically for both call sites. Refactors update_with_version_check_returning_node to wrap a new tx-scoped twin in with_transaction, mirroring create_node's own wrapping of create_node_in_tx: read existing, validate, write version-checked (tx-scoped), compute the real changed_properties diff (_in_tx store methods bypass the notifier that normally computes this), buffer the NodeUpdated event, run synchronous invariant dispatch, then re-read the node's final tx-consistent state before returning (an invariant action can be a self-referential update on the same node, writing a second time inside the same transaction — returning the pre-dispatch snapshot silently omitted that write from the RPC response). A rejecting rule's Err rolls back everything, including the buffered event, never flushed on rollback. Also restores collection-name-collision pre-check/post-mark handling that the tx-scoped store primitive deliberately omits (same posture as create_node_in_tx) but the old non-tx path did internally — switching primitives had silently dropped it, caught by the existing collection_name_convergence_test suite. Adds isPlayRuleRejected (frontend type guard + shared-node-store wiring, Tauri command layer PLAY_RULE_REJECTED branding, and the dev-proxy gRPC-js mirror of the same daemon metadata mapping). Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
Updated the PR description: found and disclosed a second known-limitation write path ( |
…pdate-node-invariant-wiring # Conflicts: # packages/desktop-app/src-tauri/src/commands/nodes.rs
Adversarial review (manual pass, not
|
…etadata status_to_command_error's PLAY_RULE_REJECTED branch (this branch's own addition) read the daemon's x-play-rule-rejected ASCII metadata key and the payload's rule_id field. Both are now stale against main: the non-ASCII-metadata fix switched the daemon to a binary x-play-rule-rejected-bin key (immune to non-ASCII rejection messages being silently dropped) and renamed the payload's rule_id field to rule_name. Update the Tauri reader and the frontend's PlayRuleRejectedData type to match, plus the one stale test still asserting the old field name. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ey too grpc-error-mapping.ts (the gRPC-js/dev-proxy mirror of the Tauri layer's status_to_command_error) still read the old ASCII x-play-rule-rejected key and documented the payload's old rule_id field name. Unlike nodes.rs, this file shares no lines with anything #2649 touched, so it would have merged with no conflict marker and then silently never matched the daemon's real (binary, rule_name) metadata again — every PLAY_RULE_REJECTED refusal reached through `bun run dev:browser` would fall through to the generic GRPC_ERROR path. gRPC-js requires binary keys to end in '-bin' and hands back Buffer values for them, which firstMetadataString already decodes via toString('utf8'), so switching the key string is sufficient. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Code Review SummaryRe-review of the FULL settled diff ( The core transactional/invariant-wiring logic (item 2) re-verifies clean. Read Item 1 (the three stale-ASCII-key fixes) is where this re-review found a critical, blocking problem that is NOT what it appears to be from the diff or commit messages alone. FindingsCritical Issues1. This branch never actually merged PR #2649 ( Verified with Concrete, verified consequence — the currently-committed state of this branch (not main) still has:
Meanwhile, this session's three follow-up commits ( Net effect: the daemon emits ASCII The commit messages for This is straightforward to fix, not a design problem: Test-coverage caveat worth flagging for whoever picks this up: the tests that currently pass do not catch this gap. Suggested ImprovementsNone beyond what the prior review already disclosed as acceptable (the narrow collection-name-collision edge case where an invariant action's own write, not the primary update, introduces the collision — same posture as NitpicksNit: Once the branch is re-merged with current Verification performed
Recommendation: REQUEST CHANGESThe core |
mstomar125
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above. Summary: core invariant-wiring logic (crud.rs/invariants.rs) re-verifies clean and is well-tested. Blocking issue: this branch never actually merged PR #2649 (bc33d37 is not an ancestor of HEAD — the branch's merge commit 8296bce only picked up main through 0eb68bf, which predates #2649). As a result the daemon (packages/daemon/src/services/node_service.rs) still emits the old ASCII x-play-rule-rejected/rule_id metadata shape, while this session's own follow-up commits (7bfe4e5, dfb2eef) updated every frontend/dev-proxy consumer to expect the new binary x-play-rule-rejected-bin/rule_name shape. The keys never match as currently committed, so the PLAY_RULE_REJECTED frontend feature this PR adds ships completely dead. Fix: re-merge (or rebase onto) current origin/main — confirmed conflict-free via a read-only git merge-tree simulation — before this can land.
…e-issue-2643-update-node-invariant-wiring
Code Review SummaryThird-round re-review of PR #2650, focused specifically on verifying that the merge performed in response to round 2's REQUEST CHANGES actually landed correctly and completely — the exact failure category that round 2 caught. All checks below were run independently, from scratch, not trusted from the reported summary. FindingsCritical IssuesNone. Suggested ImprovementsNone beyond what round 1/round 2 already disclosed as acceptable (the narrow collection-name-collision edge case sharing NitpicksNone new. Verification performed1. Merge correctness (the core thing this round exists to check)
2. Repo-wide grep for the dead ASCII scheme
3. Read the three previously-suspect files directly (not inferred from grep)
4. Confirmed the merge didn't touch the PR's own invariant-wiring logic
5. Tests re-run for real, from a cold shell, not trusted from the reported numbers
6. Read the full prior-round comment/review history ( ConclusionThe merge genuinely landed this time: Recommendation: APPROVE |
mstomar125
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
…ected writes (#2654) * Add PlayRuleRejected handling to updateTaskNode() and audit remaining write-failure call sites updateNode()'s catch block, errors.ts's isPlayRuleRejected, and the 'play-rule-rejected' conflictType were already wired by core#2643/#2650. updateTaskNode() was missing the equivalent branch even though it is the primary path for a task status-change rejection — add it, following this method's existing non-rollbackUpdate() recovery pattern. Audit the other conflictNotifications.add({..., conflictType: 'write-failure'}) call sites in shared-node-store.svelte.ts and document each one's reachability inline: deleteNode() is structurally unreachable (delete_node never dispatches invariant rules); setNode() and persistBatchedChanges()/commitAllBatches() are reachable but deliberately keep their existing generic-failure handling, matching how each already treats OCC conflicts. Extend dev-proxy-grpc-error-mapping.test.ts, backend-adapter.test.ts, and add play-rule-rejected-notification.test.ts covering both updateNode() and updateTaskNode() call sites end to end (backend-adapter mock through to the surfaced toast). Co-Authored-By: Claude Sonnet 5 <[email protected]> * Correct occConflictAlreadyNotified comments to cover PlayRuleRejected Both outer-catch comments (updateNode(), updateTaskNode()) described the shared flag as OCC-only, left stale once the PlayRuleRejected branches started setting it too. Update the wording to name both cases. Co-Authored-By: Claude Sonnet 5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
Summary
Wires
RuleClass::Invariantrules intoupdate_node's write path so they actually run synchronously, in-transaction — the prerequisiteupdate_nodehalf of ADR-060 §1/§2 thatcreate_nodealready had (from #1739/#2632). Depends on core#2642 (therejectaction type), already merged.packages/core/src/playbook/validation.rs: relaxedInvariantUnsupportedTriggerto acceptproperty_changedtriggers, not justnode_created— the whole point of this issue is giving that trigger a real synchronous join point.relationship_added/relationship_removed/scheduled remain unsupported (no equivalent transaction to join). Updated the one existing test that assertedproperty_changedwas rejected (it's now accepted, same asnode_created).packages/core/src/services/node_service/invariants.rs: newdispatch_invariant_rules_for_update_in_tx, theupdate_nodetwin of the existingdispatch_invariant_rules_in_tx. Reusesplaybook::lifecycle::trigger_keys_for_event— the exact same exact-key/wildcard-key dual lookup the reactive engine's event subscriber already uses — so save- and dispatch-time trigger matching can never silently diverge, and reuses the sharedexecute_matched_invariant_rules_in_txexecution core Add a reject/validation action type so an invariant Play can veto a write, not just augment it #2642 built, so the reject-action distinction (PlayRuleRejectedvs genericInvariantRuleFailed) holds identically for both call sites by construction.packages/core/src/services/node_service/crud.rs: the substantial change.update_with_version_check_returning_nodenow wraps a new tx-scoped twin (update_with_version_check_returning_node_in_tx) inwith_transaction, mirroring howcreate_nodealready wrapscreate_node_in_tx. Inside the transaction: read existing (tx-consistent) → validate (behavior/schema/play-rules) → version-checked write (tx-scoped) → compute the realchanged_propertiesdiff (compute_property_changes, since_in_txstore methods bypass the store's own notifier that normally computes this) → buffer theNodeUpdatedevent → synchronous invariant dispatch → re-read the node's final tx-consistent state (see "self-referential augment" note below) before returning. A rejecting rule'sErrpropagates through the whole chain and rolls back everything, including the buffered event (never flushed on rollback). Post-commit side effects (embedding queue, mentions sync, collection-name-collision marking) stay outside the transaction, unchanged in behavior from before.Two real bugs caught by the test suite during implementation (not by review — worth flagging)
verified: true." My first pass returned the pre-dispatch node snapshot asupdate_node's result, silently omitting the invariant action's own write from the RPC response (even though it was genuinely, durably committed). Fixed by re-reading the node's tx-consistent final state after dispatch succeeds, rather than returning the captured pre-dispatch value.SqliteStore::update_node_with_version_checkdid collision pre-check + post-commit marking internally; switching to the tx-scoped primitive (which deliberately omits this, same posture ascreate_node_in_tx) silently dropped that behavior. Caught bycollection_name_convergence_test.rs's existingupdate_path_introducing_a_name_collision_is_now_markedtest. Fixed by replicatingcreate_node's own pre-check/post-mark pattern for the update path (pre-tx read-only detection, post-commit best-effort marking).Both are exactly the kind of thing this repo's full-suite-before-push discipline exists to catch — glad the existing tests were doing their job.
Adversarial focus (per the task)
invariant_update_rule_reject_prevents_partial_writeconfirms both the property value AND the version stay at their pre-update values after a rejection.DomainEventbroadcast on rejection, verified by test:invariant_update_rule_reject_emits_no_domain_eventsubscribes before the write and assertstry_recv()isEmptyafter a rejected update.RuleClass::Reactivecompletely unaffected:reactive_update_rule_still_fires_asynchronously_post_commitproves a reactive rule on the same trigger shape stays async/post-commit, requiring the real engine loop andwait_until— unlike every invariant test, which asserts synchronously onupdate_node's own return value.invariant_update_rule_augmenting_action_commits_and_broadcasts_normallyproves an augmenting action commits atomically AND a realNodeUpdatedbroadcast for the triggering write goes out.invariant_update_rule_scoped_to_one_property_ignores_a_different_property_changeproves aproperty_key-scoped rule doesn't fire on an unrelated property change (exercises the realtrigger_keys_for_eventexact/wildcard matching, not a blanket per-node-type match).Frontend
Per the task's explicit instruction (this specific piece is listed as a desktop-app follow-up in the issue's own Non-Goals, but was requested directly): added
isPlayRuleRejectedtype guard (packages/desktop-app/src/lib/types/errors.ts) and wired it intoshared-node-store.svelte.ts'supdateNodecatch block (~line 2003), alongside the existingisVersionConflictbranch, reusing the samerollbackUpdate()call and differing only in which toast message shows (the rule's own author-supplied message, not a generic one). Also updated:packages/desktop-app/src-tauri/src/commands/nodes.rs'sstatus_to_command_error— newPLAY_RULE_REJECTEDbranding gated onFAILED_PRECONDITION+x-play-rule-rejectedmetadata (mirrors the existingSUBTREE_ACCESS_DENIEDpattern), with tests.packages/dev-tools/src/grpc-error-mapping.ts— the dev-proxy/gRPC-js-side mirror of the same mapping, sobun run dev:browsersees the samecode/conflictDatashape as the Tauri path. No existing test infrastructure for this file (verified viatsc --noEmit, no pre-existing test suite to extend).Known limitations (explicitly out of scope, flagging for visibility)
Two other write paths bypass
update_with_version_check_returning_nodeentirely and therefore do not get synchronous invariant dispatch from this PR — only the genericupdate_nodeRPC path does. The issue's own reference files and Proposed Solution only nameupdate_node/create_node, so both are treated as correctly out of scope rather than silently expanded; flagging so they're conscious, visible gaps rather than a surprise:NodeService::update_task_node(packages/core/src/services/node_service/schema.rs) — a genuinely separate write path, callingSqliteStore::update_task_nodedirectly with its own bespoke OCC handling via error-string matching. Reached via the dedicatedupdateTaskNodefrontend method andUpdateTaskNodeRPC.NodeService::bulk_update(packages/core/src/services/node_service/bulk.rs) — callsSqliteStore::bulk_update, a single-SQL-statement batch primitive with noNodeServiceTx-composable hook point (not thewith_transaction/NodeServiceTxmachinery this PR's wiring depends on), so a property change delivered via a bulk update won't trigger a matching invariant rule either.Both are pre-existing, independent write paths, not something this PR introduces or regresses — they simply don't (yet) share the transaction-wrapped pipeline this issue extends.
Test plan
cargo test -p nodespace-core --lib— 1396 passed.cargo test -p nodespace-core --test playbook_invariant_integration_test— 22 passed (16 pre-existing + 6 new update-triggered invariant tests).cargo test -p nodespace-core --test playbook_engine_integration_test— 4 passed.cargo test -p nodespace-core --test collection_name_convergence_test— 11 passed (confirms the collision-detection fix).cargo test -p nodespace-daemon --lib— 208 passed.--test grpc_round_trip— 25 passed (includingupdate_increments_version,watch_nodes_receives_create_update_delete_events,watch_nodes_over_real_transport_suppresses_own_echo_and_delivers_foreign_writes).cargo test -p nodespace-app --lib— 169 passed (including newstatus_to_command_errortests).bun run test(frontend) — 4959 passed across 240 files, including newisPlayRuleRejectedunit tests.cargo clippy --all-targets -- -D warnings -D clippy::unused-async— clean across the whole workspace.bun run test:all— green.🤖 Generated with Claude Code