Skip to content

Evaluate a write without making it, filter a saved query by what the rules permit, and sort any enum by its declared order - #3644

Merged
malibio merged 1 commit into
mainfrom
issue-3559-dry-run-permitted-enum-order
Oct 5, 2026
Merged

malibio merged 1 commit into
mainfrom
issue-3559-dry-run-permitted-enum-order

Conversation

@malibio

@malibio malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Closes #3559. Implements ADR-094 §9 (Build order steps 6 and 7).

What changed

Dry run of a write

  • nodespace node update --dry-run and nodespace node set-status --dry-run report whether a rule would reject the change, with the rule's message, play and rule name. Nothing is written and no version changes. The agent's update_node takes dry_run too.
  • New RPC DryRunUpdateNode(UpdateNodeRequest) returns (DryRunUpdateResponse), the way CountQuery reuses ExecuteQueryRequest.
  • There is one implementation of rule matching and evaluation. The invariant loop (execute_matched_invariant_rules) takes an InvariantRun mode; ConditionsOnly evaluates conditions exactly as a write does and, of the actions, carries out reject alone. The action loop skips every other action before resolving its bindings.
  • The proposed node comes from prepare_update, split out of the version-checked update so the write and the dry run build the node through the same steps (merge, bucketing, validation, title).
  • What a rule sees matches the write: the proposed node as the trigger node, a property-changed event with the stored value as old and the proposed value as new, and the committed graph for everything else (a write's rule reads go through the pool, not the open transaction).
  • A rule that cannot be evaluated is reported as unresolved and counts as not allowed, as the write fails closed on it.
  • A dry-run update_node call is not counted as a write by the agent loop (is_write_call).

permitted query filter

  • {"type":"permitted","operator":"equals","property":"status","value":"in_progress"} keeps the nodes for which that change would not be rejected: a dry run per candidate.
  • It is evaluated in query_ops::run_definition, after the statement's other filters and sorting, in sort order until the limit is filled, so sort and limit apply to what it keeps.
  • QueryService refuses a definition that still holds one, so no caller can run the statement without it.
  • A candidate whose rules cannot be evaluated is left out and counted (permitted_unresolved on RunSavedQuery, the CLI and the agent's run_query); the query does not fail.
  • Negation, run-time narrowing, CountQuery and saved-query membership (applicable skills) all go through the same evaluation.
  • A Play's selector refuses it, inline or through a saved query, as it refuses relative dates.
  • The app declines to answer it client-side when deciding whether a changed node joins an open result.

Enum order

  • Sorting by any enum on any type follows the schema's declared values, core then user, ascending and descending, in SQL and in the re-sort alike. A value the schema does not list sorts last; a node with no value sorts first ascending.
  • priority goes through the same generic path. Priority::rank, USER_RANK and ABSENT_RANK are removed; SortConfig::rank_scope is replaced by SortConfig::rank (EnumRank).

Behaviour changes to note

  • User-added priorities used to sort alphabetically after the core values; they now sort in the order they were added to the schema.
  • Every enum sort changes from alphabetical to declared order (two existing tests pinned the alphabetical order and now pin the declared one).

Not done here

Tests

  • core: dry_run_tests (dry run vs. the write it predicts), permitted_filter_test (seeded gate Plays, running engine), query ops / query service (enum order, filter validation, the service's refusal), selector validation.
  • daemon: DryRunUpdateNode, and the filter over RunSavedQuery / ExecuteQuery / CountQuery.
  • cli: flag parsing, output, and that a dry run writes nothing.
  • agent: update_node with dry_run.
  • frontend: matchesFilter declines a permitted filter.

Docs (nodespace-docs, pushed to main alongside the merge): architecture/playbook-engine.md, architecture/playbook-system.md, components/query-node.md, architecture/data-layer.md, ADR-092 §7, ADR-094.

🤖 Generated with Claude Code

@malibio

malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3644 (issue #3559)

Review Type: Initial Review (no prior reviews or comments on the PR; reviewed at 37168595d)

How this was checked: read the full diff against origin/main and the surrounding code on the write path. Ran scripts/check-node-type-literals.ts and scripts/check-lifecycle-reads.ts (both pass). I did not run the Rust or frontend test tiers; the findings below come from reading the code.

Summary

A net improvement, and a careful one. The design holds its central promise: there is one rule loop (execute_matched_invariant_rules) with an InvariantRun mode, one way to build the proposed node (prepare_update, used by both the write and the dry run), and the query service refuses a permitted filter instead of silently dropping it, so no caller can run the statement without it. Every production caller of QueryService goes through query_ops or the selector (which refuses the filter). The real write path is unchanged in behaviour: prepare_update is the old body moved, and the lifecycle assignment added at its end only affects the returned updated, which the write uses solely to build the NodeUpdate it already built. Tests pair each dry run with the write it predicts, which is the right shape.

No blockers. Two things are worth fixing in this PR (the is_write_call scope and what an Err from a per-candidate dry run is treated as); the rest are optional.


Requirements Check

Dry run

  • ✅ node update / node set-status accept --dry-run; result says allowed or rejected with message, play and rule name; nothing written, no version change — packages/cli/src/commands/node.rs, output.rs; covered by a_dry_run_update_or_set_status_writes_nothing, the daemon test and dry_run_tests.
  • ✅ Same rules, same condition inputs: compute_property_changes(existing, proposed) is the same diff the write computes, the trigger node is the prepared node, graph reads go through the pool in both cases. One small gap noted below (modified_at).
  • ✅ One invariant execution path in a conditions-only mode; no second matcher.
  • ✅ Unresolved condition reported and treated as a rejection (DryRunVerdict::Unresolved, allowed = false).
  • ✅ No action other than reject is executed (skipped before binding resolution); docs and CLI help say it predicts rejections only.
  • ✅ The agent's update_node accepts dry_run; golden tool surface re-recorded.

permitted filter

Enum order

  • ✅ Any enum on any type sorts by declared core-then-user order, ascending and descending, in SQL and in the Rust re-sort (EnumRank::of and the CASE both use the position in EnumRank::values; values are bound, not interpolated).
  • ✅ priority goes through the generic path; Priority::rank, USER_RANK, ABSENT_RANK and rank_scope are deleted, not deprecated. Note the stated behaviour change: user-added priorities now sort in the order added, not alphabetically.
  • ✅ A value not in the schema's list sorts last (tested with rows written past validation).

General

  • ✅ references/cli.md documents the flag and the filter. skill:check not run by me.
  • ✅ Docs: updates exist uncommitted in nodespace-docs for playbook-engine.md, playbook-system.md, query-node.md, data-layer.md, ADR-092 §7, ADR-094. They must be pushed alongside the merge.
  • ➖ quality:fix / test:changed: not run by me.

Code Review Findings

🟡 Important

1. is_write_call honours dry_run on every write tool, but only update_node implements it
📁 packages/agent/src/local_agent/tools.rs:3625-3629 (callers: agent_types.rs:626, agent_loop.rs:1273,1440, deletion_confirmation.rs:75)

is_write_call(tool, args) returns false for any write tool whose args carry dry_run: true. create_node is deliberately not deny_unknown_fields and promotes unknown top-level keys into field_values, so a model that copies the new parameter onto create_node makes a call that is attempted as a real write while the loop classifies it as a non-write. If that write lands, the turn is not reported as Acted, landed_write is false, and the cut-off backstop and type-listing suppression read the turn as write-free. I did not run this; whether the create lands depends on whether the type accepts the stray key. The predicate should not depend on that.

Fix: tie the exemption to the tool that implements the flag, e.g. Tool::from_name(tool) == Some(Tool::UpdateNode) && dry_run == true, or a Tool::supports_dry_run() beside write_semantics() so a later tool must opt in. Add an assertion that is_write_call("create_node", {"dry_run": true, ...}) is true.
Principle: a safety classification should be derived from what the tool does, not from an argument any caller can attach (fail closed).

2. A permitted filter turns every per-candidate error into "unresolved", including errors that are the query's, not the node's
📁 packages/core/src/ops/query_ops.rs:775-817 (permission), :657-669 (resolve_filter)

permission maps any Err from dry_run_update to Permission::Unresolved with a warn! per node. Two different things land there:

  • A change that cannot be made to any node — the filter's value is not one the schema accepts (a typo such as "in_progres"). resolve_filter checks that the field is declared but not the value, so the query returns zero rows, permitted_unresolved = N, and N warning lines, where every other malformed filter is refused at check time with a message naming the problem.
  • A store or schema-read failure. The query then answers "nothing is permitted" instead of failing, which is the opposite of how the rest of the query path treats an unreadable database.

Fix: validate the value once when the filter is checked (for a named target_type, run the field's validation against the value, or probe one prepared update) and return InvalidParams; in permission, keep "unresolved" for DryRunVerdict::Unresolved and validation-class errors, and propagate the rest. If per-node logging stays, log once per run with the count.
Principle: fail fast on caller errors; do not convert infrastructure failures into data.

3. The unresolved count is dropped on the ad hoc query paths
📁 packages/core/src/ops/query_ops.rs:739-741 (execute_query_nodes_excluding), :1217-1228 (count_query)

ExecuteQuery (CLI nodespace query, the agent's ad hoc query tool) takes .nodes and discards unresolved; CountQuery returns a count with no indication that candidates were left out. A caller of those sees a short result with no signal. The acceptance criterion is worded for saved queries, so this does not fail it, but the same filter behaves observably differently by entry point. Either carry unresolved on ExecuteQueryOutput and the count response, or say in cli.md that only query run reports it (it currently says "query run reports how many were", which is accurate but easy to miss).
Principle: least surprise; one filter, one contract.

🟢 Suggestions

4. Candidates are loaded unbounded before the limit is filled
📁 packages/core/src/ops/query_ops.rs:856-876

run_definition removes the limit and materialises every candidate (plus the Rust re-sort) before the loop that stops at limit. The dry runs stop early, the load does not. count_query and definition_matches are a dry run per candidate by design, and each dry run is several reads (prepare_update re-buckets, validates, resolves the type chain three times and computes a title). Fine at today's sizes and documented in the doc comment and cli.md ("put the cheap filters beside it"). If it shows up, page the statement in chunks of a few times the limit. Not for this PR.

5. The proposed node keeps the stored modified_at
📁 packages/core/src/services/node_service/crud.rs:55-63 (into_proposed_node)

On the write, the trigger node is the row read back, with a new modified_at; the dry run's node carries the stored one. A rule condition on node.modified_at would read differently. Unlikely in an invariant rule; either set it to now or add it to the table of differences in playbook-engine.md, which currently claims the inputs are identical.

6. permitted on a value the node already holds is always "allowed"
📁 packages/core/src/ops/query_ops.rs:788-791

Setting a field to its current value changes nothing, matches no rule, and is kept (pinned by a_dry_run_matches_rules_by_what_the_change_touches). That is consistent with the write, but it means permitted status=in_progress alone lists every task already in progress. cli.md hints at pairing it with status = open; one explicit sentence there would save a confused reader.

7. Nit: execute_actions_in_tx now runs without a transaction
📁 packages/core/src/playbook/actions.rs:2157-2190

The name and TxCtx wording no longer describe the conditions-only mode, and the match &txc { Some(..) => execute_single_action_in_tx(..), None => execute_reject(..) } block is repeated for the for_each and plain branches. A small local closure/helper would state "only reject gets this far" once.

8. Nit: DryRunUpdateResponse encodes three outcomes in two booleans
📁 packages/proto/proto/node_service.proto:556-573

allowed + unresolved + a message whose meaning depends on unresolved allows states the server never produces (allowed && unresolved). A oneof or a three-value enum would make the verdict the wire type's own. Pre-release, so cheap to change now; also permitted_unresolved = 7 is declared before field 6 in RunSavedQueryResponse.

9. Nit: fixed sleeps in permitted_filter_test.rs
📁 packages/core/tests/it/permitted_filter_test.rs:139,151,361

sleep(150ms) waits for the engine to pick up a Play change. It follows the existing pattern in core_model_plays_test.rs, so not a regression, but it is a wall-clock assumption under merge-gate load. Polling the lifecycle until the rule set changes would remove it.

Things checked and found sound

  • Write path unchanged: prepare_update is read-only (settle_play_update, stamp_task_started, rebucket_and_validate, title) and the write destructures it into the same NodeUpdate as before.
  • Archiving: applying lifecycle_status last in prepare_update makes the dry run of an archiving write skip the rules, as the write does once the store has applied it; it is an assignment, and goes through governance::participates, so the lifecycle-read rule is respected.
  • SQL: enum values in the ORDER BY CASE are bound (?N, numbered, so clause order is safe); the searched-CASE/NULL handling is preserved; wildcard targets are never ranked in either layer.
  • Security: no new unvalidated input reaches SQL; CLI output passes rule name, play id and message through sanitize_for_terminal; the dry-run RPC routes and applies the typed-client check like UpdateNode.
  • CLAUDE.md: no literal node-type comparisons, no lifecycle reads, no lint suppressions, no compatibility code (rank_scope and the priority rank are removed outright), generated filter-type.ts regenerated rather than hand-edited, no issue numbers in comments, no docs added to the repo. FilterType::Permitted is a wire-type change in nodespace-types with regenerated TypeScript; it adds no node type or schema field, so node-types.md needs no change.

Recommendation: APPROVE — with findings 1 and 2 recommended before merge (both small), and 3 as a follow-on decision. The unmet "Ready tasks" criterion is an acceptable deferral to #3543.

@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 5, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary

Addressed

  • 1 is_write_call exempts a dry run only on update_node; a dry_run argument on any other write tool still counts as the write it is. Test added for create_node.
  • 2 A permitted filter whose value an enum does not list is refused when the query is checked or saved, naming the valid values. Per candidate, only a validation-class error is 'unresolved'; a store failure now fails the query.
  • 3 / 6 cli.md says that only query run reports the unresolved count, and that a change to the value a node already holds is always permitted (hence pairing with status = open).
  • 5 The proposed node carries a fresh modified_at, as the written row does.
  • 7 One helper dispatches an invariant rule's action for a write and a dry run.

Skipped

  • 4 Paging candidates: premature; revisit if a profile shows it.
  • 8 oneof for the dry-run response: the two booleans are never produced in an invalid combination and are what the CLI reads; not worth the churn.
  • 9 Fixed sleeps: the existing seeded-play harness pattern; changing it belongs with that harness.

Rust workspace: 5473 passed.

Re-Review Decision

Decision: RE-REVIEW NEEDED — finding 2 changed error handling on the query path (new logic), so the new commit gets a second look.

@malibio

malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3644 (issue #3559)

Review Type: Re-Review (of f9f2a699b, against the first review at 37168595d)

How this was checked: read git diff 37168595d..f9f2a699b and the code around it (dry_run_update, prepare_update, check_field_value, resolve_field_owners, flatten_chain_fields, extend_inherited_field, SkillQueries::load / matching, the NodeServiceError to OpsError mapping). I did not run any test tier; the findings below come from reading.

Previous Review Summary

  • Previous recommendations: 9
  • Addressed: 6 (findings 1, 2, 3, 5, 6, 7)
  • Not addressed: 3 (findings 4, 8, 9), each skipped with a reason I accept
  • New issues found: 1 Important, 2 Suggestions

Previous findings

# Finding Status
1 is_write_call honoured dry_run on every write tool Addressed. The exemption is tied to Tool::UpdateNode; a create_node call carrying dry_run: true is asserted to be a write.
2 Every per-candidate error became "unresolved" Addressed, with one gap in the up-front check (finding A below). permission returns Result; only ValidationFailed, InvalidUpdate and UnknownNodeType are "unresolved", everything else fails the query. Both callers (run_definition, definition_matches) propagate.
3 Unresolved count dropped on the ad hoc paths Addressed by documentation: cli.md now says only query run reports it. That was one of the two options offered.
4 Candidates loaded unbounded Skipped (premature). Accepted: it was marked "not for this PR".
5 Proposed node kept the stored modified_at Addressed in into_proposed_node.
6 permitted on a value the node already holds Addressed in cli.md.
7 Repeated match &txc dispatch Addressed by run_invariant_action. Behaviour is unchanged: same arguments, same two arms.
8 Two booleans for three outcomes on the wire Skipped. Accepted: a nit, and the server never produces the invalid combination.
9 Fixed sleeps in permitted_filter_test.rs Skipped. Accepted: it is the existing harness pattern and not a regression.

Code Review Findings

🟡 Important

A. The up-front enum check reads the target type's values only, so it refuses a value a subtype added
📁 packages/core/src/ops/query_ops.rs:670-696

declared.fields is the effective field set of target_type. A subtype can add values to an inherited extensible enum (ADR-078; extend_inherited_field in packages/core/src/schema/mod.rs materializes the field on the subtype with the added user_values, and leaves the parent's list alone). A query on the base type also returns the subtype's nodes, and the write of the added value to one of those nodes is valid.

So for a base-type query whose permitted filter names a subtype-added value (a task query, a value an issue-like subtype added to status), this check returns InvalidParams ("is not a value of 'task.status'") although some candidates accept the change. Before this commit the same query ran: the base type's own nodes were counted unresolved and the subtype's nodes were evaluated. The comment added to permission in this commit describes that case ("the change is refused for this node by its own type"), but the up-front check now prevents it from being reached.

The same refusal applies when the query is saved (validate_query_paths), and in SkillQueries::load, where the query is logged and matches nothing.

I did not run this; it follows from resolve_field_owners returning only the chain upward from target_type. No seeded core subtype extends an enum today, so it needs a user-defined subtype to reach.

Fix: refuse only when no type the query can return lists the value. DeclaredFields::subtypes already gives the subtype closure; collect the enum's values over target_type and each subtype, then test membership. Add a case to a_permitted_filter_names_one_change_to_a_declared_field (or the integration test) with a subtype-added value.
Principle: a fail-fast check must be no stricter than the operation it guards; otherwise it rejects valid input.

🟢 Suggestions

B. The enum value list is assembled a third time; the write path's own check is available
📁 packages/core/src/ops/query_ops.rs:672-687 (also :521-535 in enum_rank, and NodeService::enum_values / check_field_value in packages/core/src/services/node_service/crud.rs:3612-3790)

core_values chained with user_values is now written out in enum_rank, in resolve_filter and in NodeService::enum_values. NodeService::check_field_value(field, value) is pub(crate) and is what the write runs. Calling it here (per type, once finding A is settled) would keep the check and the write in step, and would also cover what the hand-written version skips: a non-string value for an enum, and a wrong-typed value for a number, boolean or date field. Those still produce "every candidate unresolved", the outcome the original finding 2 described for an enum typo.
Principle: DRY; one definition of "a value this field accepts".

C. The validation-class list in permission is an allow-list by variant, with no test on the propagating arm
📁 packages/core/src/ops/query_ops.rs:851-863

The three variants cover what prepare_update raises for a refused property change (nearly all invalid_update). PlayValidationFailed is also a per-node refusal and now fails the query; it needs a permitted filter that names a play's rules, so I would leave it. The direction is the right one: an unlisted error fails loudly instead of being read as data. A one-line comment saying a new per-node refusal variant has to be added here would help the next person, since the catch-all arm will not prompt them. Nothing tests the Err(e) => Err(OpsError::from(e)) arm; a store failure is awkward to inject, so this is optional.

Checked and found sound

  • is_write_call (packages/agent/src/local_agent/tools.rs:3631-3635): Tool::from_name is the same lookup is_write_tool uses, so an unknown tool name is still a non-write, and dry_run: false or a non-boolean value on update_node is still a write.
  • run_invariant_action (packages/core/src/playbook/actions.rs:2290-2317): a pure extraction. Seven parameters, the same count as execute_single_action_in_tx, so it stays inside clippy's argument limit.
  • into_proposed_node (packages/core/src/services/node_service/crud.rs:47-55): only the dry run calls it, so the write's NodeUpdate is unaffected.
  • Error propagation into node context: SkillQueries::matching already turned an error from definition_matches into Internal; a store failure in a dry run now reaches it instead of reading as "not a member", which is consistent with the membership query beside it.
  • Up-front check, other cases: skipped under *, for a non-enum field and for an enum that lists no values; a null value is not refused. The new error is InvalidParams, which validate_query_paths maps to invalid_update on save and SkillQueries::load tolerates.
  • CLAUDE.md: no literal node-type comparison, no lifecycle read, no lint suppression, no compatibility code, no issue numbers in comments. The cli.md edit is in the reference file, not SKILL.md.

Recommendation: APPROVE — the commit resolves the two findings that were asked for before merge. Finding A is a narrow over-refusal introduced by the fix for finding 2; it is cheap to fix and worth doing in this PR, but it fails loudly, needs a user-defined subtype with an extended enum to reach, and does not block.

@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 5, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary (re-review)

  • A (addressed) The up-front enum check now accepts a value listed by the queried type or any of its subtypes, since a subtype's nodes are among the query's rows. New test: a_permitted_filter_takes_a_value_a_subtype_added (the subtype's node is kept, the base type's node is counted unresolved).
  • B (partly) One enum_values helper now serves the check and the sort order. Not switched to check_field_value: a wrong-typed value for a non-enum field still shows up as every candidate unresolved with the count reported, which is acceptable for now.
  • C (addressed) Comment on the validation-class list says a new per-node refusal variant belongs there.

Core suite: 2842 passed.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED — the change widens one fail-fast check exactly as the reviewer specified, is covered by a new test, and touches no other logic.

…rules permit, and sort any enum by its declared order
@malibio
malibio force-pushed the issue-3559-dry-run-permitted-enum-order branch from 361e425 to eace0d7 Compare October 5, 2026 16:42
@malibio
malibio merged commit 9bf187a into main Oct 5, 2026
@malibio
malibio deleted the issue-3559-dry-run-permitted-enum-order branch October 5, 2026 16:42
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.

Evaluate a write without making it, filter a saved query by what the rules would permit, and sort any enum by its declared order

1 participant