Skip to content

Fix x-play-rule-rejected non-ASCII metadata drop and validation-error fingerprint collision (post-#2644 follow-up) - #2649

Merged
mstomar125 merged 3 commits into
mainfrom
issue-2647-play-rule-rejected-followups
Sep 16, 2026
Merged

mstomar125 merged 3 commits into
mainfrom
issue-2647-play-rule-rejected-followups

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Fixes both adversarial-review findings from #2644 that landed on main unaddressed (closes #2647, supersedes #2646):

  • 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). Switched to gRPC's binary-metadata convention: x-play-rule-rejected-bin, carrying the payload via MetadataValue::<Binary>::from_bytes, which is infallible.
  • load_active_plays/handle_play_created/handle_play_updated each logged every validate_play error with a constant rule_name="validation" and error_location_index=0. error_fingerprint hashes (play_id, rule_name, error_location_index, error_type) and deliberately excludes the message text, so two structurally different validation errors on the same play collapsed onto one fingerprint — the second error's text was silently discarded. Added PlayValidationError::location()/kind() accessors and a shared log_validation_errors() helper that folds "{location}:{kind}" into the fingerprint identity, so distinct errors produce distinct log nodes.

Also renamed 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.

Testing

  • cargo test -p nodespace-core --lib playbook:: — 323 passed
  • cargo test -p nodespace-daemon --lib error_mapping_play_rule_rejected — 3 passed (incl. new non-ASCII regression test)
  • cargo test -p nodespace-core --test playbook_engine_integration_test distinct_validation_errors_on_the_same_play_produce_separate_log_nodes — 1 passed
  • cargo fmt --all -- --check — clean
  • cargo clippy -p nodespace-core -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async — clean
  • Both new regression tests mutation-tested locally (temporarily reverted each production fix and confirmed the corresponding test fails) to confirm they exercise the real fix rather than passing vacuously.

🤖 Generated with Claude Code

… 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]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Adversarial review (manual pass, not /pragmatic-code-review)

Verified against tonic 0.12.3 source (vendored locally) and by tracing every PlayValidationError push site in validation.rs.

Clean (verified, not just trusted)

  • No stale reader of the old ASCII x-play-rule-rejected key or the old rule_id field name anywhere in the repo. Repo-wide grep (core, daemon, desktop-app Tauri/TS, dev-tools, docs) found zero remaining references outside this PR's own new -bin key/rule_name field. The only surviving rule_id symbols are the unrelated rule_id_for/deterministic_action_output_id machinery in playbook/actions.rs, confirmed untouched and non-colliding.
  • insert_bin/MetadataValue::<Binary>::from_bytes usage is correct, checked against tonic 0.12.3's actual source: from_bytes(src: &[u8]) -> Self is genuinely infallible (no Result), and insert_bin::<K: IntoMetadataKey<Binary>> only panics if the key doesn't end in -bin (MetadataKey::from_static's is_valid_key check) — "x-play-rule-rejected-bin" satisfies that. get_bin/to_bytes() in the test are the matching accessors.
  • error_mapping_play_rule_rejected_preserves_non_ascii_message is a genuine, non-vacuous regression test — the message (em dash, curly quotes, café, emoji) would have failed to parse as MetadataValue<Ascii> under the old code, so the old if let Ok(...) would silently skip the metadata insert and this test's .expect("...header missing...") would panic. Confirmed real.
  • log_validation_errors is used at all three call sites — load_active_plays (engine.rs:220), handle_play_created (:574), handle_play_updated (:705). Confirmed by symbol search, not just the diff.
  • Dedup for genuinely-repeated identical errors still works: location()/kind() are purely structural/deterministic, so a play re-validated with the SAME error again produces the SAME (location, kind) identity → same fingerprint → correctly increments occurrences rather than forking a new node.

Real gap found: location() + kind() does NOT guarantee fingerprint uniqueness — three concrete, realistic scenarios still collide

The fix folds "{location}:{kind}" into the fingerprint, which fixes the original across-rule collision. But location is per-condition/per-action (not per-error), and several validators can legitimately push multiple errors of the identical kind at the identical location in one validate_play pass:

  1. InvariantOutOfScopeTarget (validation.rs ~896-911): target_id_params(&ActionType::AddRelationship) returns ["source_id", "target_id"] — two params checked in one loop iteration, both writing location: location.clone() (the same "rule[N].action[M]" string). An invariant add_relationship/remove_relationship action with BOTH source_id and target_id set to non-binding-template (out-of-scope) literal values pushes two errors, both (location, "invariant_out_of_scope_target") — identical identity. The second (e.g. target_id's value/param) silently collapses into the first via occurrences: 2, exactly the bug this PR is fixing, just narrower.
  2. BrokenPath (validation.rs ~368-401): a single condition can reference multiple dot-paths (e.g. node.foo.bar == node.baz.qux, a completely ordinary CEL condition) — validate_schema_path is called once per path but location is computed once per condition. If both paths are broken, two BrokenPath errors share the same (location, "broken_path") identity.
  3. InvariantNonDeterministic (validation.rs ~879-894): iterates every non-deterministic function name found in one condition (e.g. now() > 5 && random() > 0.5) — multiple matches in one condition again share the same (location, "invariant_non_deterministic") identity, differing only in the (unused-by-fingerprint) function field.

All three are ordinary authoring patterns, not contrived. Since create_or_update_log_node is awaited sequentially inside log_validation_errors's loop, the second error of a colliding pair genuinely queries back the just-created node from the first and increments its occurrences rather than creating a separate node — I traced this through create_or_update_log_node (logging.rs) to confirm it's not just a hash-math coincidence.

None of the existing tests cover a same-location multi-error case (the new integration test only covers two different locations/rules), so this gap is currently unguarded.

Recommendation: not necessarily a blocker for this PR's stated scope (it's strictly better than before), but flagging as a real, reachable residual instance of the exact bug class #2647 set out to fix. Consider either folding a per-error-instance disambiguator into the identity (e.g. an index within the location, or including the variant's most specific field like param/segment/function), or filing a fast follow-up if you'd rather ship this improvement now.

…alidate_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]>
…hapes

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]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Re-review (pragmatic-code-review) — full settled diff main...2c084564

Re-reviewed the entire diff fresh (not just the delta since the last pass), read the prior review's exact findings, re-traced the code myself, and ran the real test suite. Covers all 3 commits: e7879691 (already reviewed), f5bb9ffd, 2c084564.

Context: what changed since the prior review

The prior review pass (on e7879691) came back clean on the ASCII→binary metadata fix and the rule_id→rule_name rename, but found a real residual gap in the fingerprint-collision fix: (location, kind) alone is not unique within a single validate_play pass — a single condition/action can legitimately push >1 same-kind error at the same location (two broken dot-paths in one condition, both source_id/target_id out-of-scope on one add_relationship, two non-deterministic functions in one condition). f5bb9ffd and 2c084564 are the fix for exactly that gap.

What I verified

1. Ordinal-suffix disambiguation is deterministic and restart-stable — traced directly, not trusted from the commit message.

log_validation_errors (packages/core/src/playbook/engine.rs) computes, for each error at index i:

let prior_same_kind_at_location = errors[..i]
    .iter()
    .filter(|e| e.location() == err.location() && e.kind() == err.kind())
    .count();

suffixed into the identity only when nonzero, so the common single-error-per-location case is byte-identical to before (existing fingerprints for non-colliding plays are unaffected).

This is deterministic iff validate_play returns the same error content in the same order on every pass over an unchanged play. I traced every producer:

  • validate_play walks rules/conditions/actions via .iter().enumerate() over plain Vecs — fixed order.
  • target_id_params(&ActionType) (source of the InvariantOutOfScopeTarget collision) is a match returning a &'static [&'static str] literal (&["source_id", "target_id"]) — fixed order, not hash-based.
  • path_extractor::extract_function_names/extract_paths (source of InvariantNonDeterministic/BrokenPath) build their output via a recursive, deterministic pre-order AST walk pushing into a Vec — no HashMap/HashSet involved in ordering.
  • The one HashMap in validation.rs (schema_cache) is a pure memoization cache keyed by node type; it's only .get()/.insert()'d, never iterated to produce error order, so it can't perturb ordering.

So for an unchanged play, validate_play is fully deterministic across calls, which makes the ordinal — and therefore the fingerprint — stable across restarts (load_active_plays), correctly mapping back to the same existing playbook_log node instead of spawning a duplicate each restart. Confirms the commit message's claim rather than just trusting it.

Also worth noting positively: the : delimiter joining location/kind/ordinal can't collide with real content — location strings are always built via format!("rule[{}]...") (no colons ever appear), and kind() returns fixed underscore-separated static strings — so there's no risk of two logically different identities stringifying to the same value.

2. Binary metadata round-trip — confirmed by code and by running the real tests:

test services::node_service::tests::error_mapping_play_rule_rejected_preserves_non_ascii_message ... ok
test services::node_service::tests::error_mapping_play_rule_rejected_returns_failed_precondition_with_metadata ... ok
test services::node_service::tests::error_mapping_play_rule_rejected_is_distinguishable_from_subtree_access_denied ... ok

Grepped the whole repo (core, daemon, desktop-app, dev-tools) for x-play-rule-rejected and bare rule_id — zero stale references to the old ASCII key or the old field name; the only surviving rule_id symbols are the unrelated rule_id_for/deterministic_action_output_id machinery in playbook/actions.rs. desktop-app has no reader of either the old or new key — no client consumer wired up yet, which is out of scope for this PR, not a regression.

3. Generality of the fix — confirmed. It lives entirely in log_validation_errors's generic location()/kind()/ordinal logic, applied once at the single call site now shared by load_active_plays/handle_play_created/handle_play_updated. PlayValidationError::location()/kind() exhaustively match all 14 enum variants (compiler-enforced), so the mechanism isn't scoped to the three collision shapes the new tests happen to cover — any future validator that pushes >1 error at one (location, kind) is covered automatically.

4. Off-by-one / panics — the ordinal counts strictly-prior same-(location,kind) errors (errors[..i]): first occurrence → ordinal 0 → suffix omitted, second → 1 → disambiguated, etc. No off-by-one. location()/kind() are infallible pure matches; nothing in log_validation_errors can panic.

5. Test coverage/quality — the three regression tests are meaningfully distinct, not redundant: each goes through a different validator/loop (validate_schema_path's per-path walk vs. target_id_params's per-param loop vs. the non-deterministic-function-name loop), each end-to-end through the real engine, each asserting 2 distinct node IDs with occurrences: 1 apiece (ruling out both "collapsed to one node" and "two nodes but one wrongly incremented"). Worth keeping all three — no redundancy to flag.

One real (non-blocking) gap: no test in this suite restarts the engine (calls load_active_plays twice against the same unchanged play) to assert the SAME log node is reused across restarts rather than duplicated. I confirmed this property holds by code-reading (point 1 above), not by an automated test. This gap predates this PR — the base distinct_validation_errors_on_the_same_play_produce_separate_log_nodes test from e7879691 doesn't cover it either — so it's not a regression, just still unguarded.

Test run (fresh, not trusted from CI)

cargo test -p nodespace-core --lib playbook                          → 324 passed, 0 failed
cargo test -p nodespace-core --test playbook_engine_integration_test → 8 passed, 0 failed (incl. all 3 new regression tests)
cargo test -p nodespace-daemon --lib play_rule_rejected              → 3 passed, 0 failed
cargo clippy -p nodespace-core -p nodespace-daemon --lib --tests     → clean, zero warnings

Findings

Critical Issues

None.

Suggested Improvements

  1. (Non-blocking) Add a regression test that restarts the engine against an unchanged play with a same-location multi-error collision, asserting the SAME playbook_log node id is reused with occurrences incremented rather than a new node created. This is the one property in this PR's risk area currently verified only by code inspection (see point 1 above), not by an automated test — and it's specifically the restart-stability guarantee the commit message promises.

Nitpicks

  1. create_or_update_log_node's doc comment (packages/core/src/playbook/logging.rs) still describes its rule_name parameter as "The rule within the play" — pre-existing looseness (other call sites already pass literals like "parse"/"seeded-play-protection"), but log_validation_errors now routes a location:kind[:ordinal] composite through the same parameter, drifting further from that description. Purely cosmetic — the new call site's own doc comment in engine.rs explains the actual semantics well. Optional.

Recommendation: APPROVE

The residual gap the prior review flagged on e7879691 is genuinely closed by f5bb9ffd/2c084564: the ordinal-suffix mechanism is general (not per-collision-shape), deterministic/stable across restarts (verified by tracing every producer of validate_play's error order, not just trusting the commit message), and exercised by three well-targeted, non-redundant regression tests — all passing, alongside the full existing suite and a clean clippy run.

@mstomar125 mstomar125 left a comment

Copy link
Copy Markdown
Contributor 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.

@mstomar125
mstomar125 merged commit bc33d37 into main Sep 16, 2026
@mstomar125
mstomar125 deleted the issue-2647-play-rule-rejected-followups branch September 16, 2026 09:17
mstomar125 added a commit that referenced this pull request Sep 16, 2026
…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]>
mstomar125 added a commit that referenced this pull request Sep 16, 2026
mstomar125 added a commit that referenced this pull request Sep 16, 2026
…0 §2) (#2650)

* Wire RuleClass::Invariant rules into update_node's write path (ADR-060 §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]>

* Update Tauri PLAY_RULE_REJECTED reader to match the daemon's binary metadata

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]>

* Update dev-proxy's PLAY_RULE_REJECTED mirror to the binary metadata key 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]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
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.

Fix x-play-rule-rejected non-ASCII metadata drop and validation-error fingerprint collision (post-#2644 follow-up)

1 participant