Skip to content

Add computed-date arithmetic to the playbook engine (add_days + function-call action bindings) - #2715

Merged
mstomar125 merged 3 commits into
mainfrom
issue-2640-add-days-action-values
Sep 17, 2026
Merged

mstomar125 merged 3 commits into
mainfrom
issue-2640-add-days-action-values

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Closes #2640. Two coupled gaps, addressed together:

  1. add_days(date_string, n) -> date_string registered in packages/core/src/playbook/cel.rs alongside the existing days_since/days_until/today. It follows parse_date_and_compute_days's parsing precedent (full RFC 3339 datetime or bare YYYY-MM-DD), returns the same format style as the input, and never reads wall-clock time — so it's deliberately excluded from NON_DETERMINISTIC_FUNCTIONS and stays usable in ADR-060 §2 invariant-rule conditions. All arithmetic is checked (try_days/checked_add_signed), not wrapping or panicking, since n ultimately comes from user-authored play content — an out-of-range offset is a clean function error.

  2. A function-call form for action-value bindings in packages/core/src/playbook/actions.rs: {add_days(item.start_date, 14)} alongside the existing bare {path} interpolation, both resolved through the same BindingContext.

Design decision (per the issue's explicit ask)

Built option A — extend {path} interpolation to accept a function-call form, resolved through the same binding-resolution machinery, rather than option B (a full CEL program for any action param value). Option B would change the performance/complexity profile of every action-value resolution across the whole playbook engine — a broad change to already security-sensitive infrastructure that had a major ADR-060 build-out with multiple adversarial review rounds just before this issue. Option A is scoped and additive: the only new surface is the exact identifier(...) shape inside a {...} binding, dispatched through a fixed, hardcoded match — not a general function-registration framework. I did not hit a case where the minimal path-plus-one-function version was insufficient, so no such framework was added.

Implementation notes

  • parse_function_call in actions.rs recognizes ONLY the whole-path shape <identifier>(...). ( is not a legal character in any trigger/actions/item path segment a play author can write today (actions[N] uses square brackets), so this can never misfire on, or change the resolution of, an existing bare {path} binding — every string it newly recognizes previously hit "unknown binding root" anyway.
  • BindingContext::resolve_function_call matches on a fixed function name (add_days today); an unsupported name is a hard, immediate error — there is no lookup table an action param's string could index into.
  • add_days's two arguments are each resolved as a dot-path (through this same BindingContext, recursively via Box::pin since the recursion is indirect) or, for the day-offset, a bare integer literal. A nested function-call argument is explicitly detected and rejected with a clear error rather than evaluated — this stays a fixed one-level substitution, not a general expression evaluator reachable through argument position.
  • All error paths are ordinary Errs, never panics, including malformed/malicious input: unresolvable paths, non-numeric offsets, non-string dates, wrong argument counts, and offsets large enough to overflow chrono's internal representation.

Testing

  • packages/core/src/playbook/cel.rs: unit tests for add_days/compute_add_days (bare date, full datetime, negative offset, month/year boundary crossing, invalid date, extreme-offset overflow safety, CEL-condition usage, and confirmation it's excluded from NON_DETERMINISTIC_FUNCTIONS).
  • packages/core/src/playbook/actions.rs: unit tests for parse_function_call/split_top_level_args (including nested-parens handling), the add_days(...) binding end-to-end (path arg, path-resolved day-offset arg, integer literal, negative offset, {...} fast path, mixed literal text), every malformed/malicious-input error case named in the issue ({add_days(bad.path, "not a number")}, non-string date, invalid date string, nested function call, unsupported function name), and two explicit regression tests asserting existing bare-path/{path} resolution is unchanged.
  • packages/core/tests/playbook_engine_integration_test.rs: scheduled_play_computes_end_date_via_add_days_and_writes_it_to_a_new_node — a real running PlaybookEngine, a scheduled play scanning pb_cycle_source nodes, computing end_date = start_date + 14 days via {add_days(...)} in a create_node action's properties, and writing it to a new pb_cycle_result node — the motivating end-to-end case from the issue.

bun run test:all and the full pre-push gate (including cargo build --bin nodespaced, test:e2e, and the Tauri-seam integration suite) pass locally. bun run quality:fix clean (0 errors, 0 warnings, clippy clean with -D warnings -D clippy::unused-async).

Non-goals (unchanged from the issue)

No Cycle schema or Cycle-creation Play (engine capability only), and no date arithmetic beyond day-offset (month/year-aware or business-day-aware arithmetic).

Reviewer note

Per the issue's own request, I dispatched an independent adversarial review focused on: injection/malformed-input risk in the new function-call parsing, whether it correctly rejects anything attempting to call something other than the explicitly-supported function set, and whether existing {path}-only behavior is byte-identical. See PR comments/review for that pass.

🤖 Generated with Claude Code

…oses #2640)

Registers add_days(date_string, n) -> date_string in cel.rs alongside
days_since/days_until/today, using checked date arithmetic so a huge or
out-of-range offset from user-authored play content is a clean function
error, never a panic. It reads no wall-clock time, so it is deliberately
excluded from NON_DETERMINISTIC_FUNCTIONS and stays usable in invariant
rule conditions.

Extends actions.rs's {path} binding-interpolation syntax to also accept a
function-call form, e.g. {add_days(item.start_date, 14)}, resolved through
the same BindingContext rather than a separate CEL program (option A from
the issue: scoped, additive, keeps the blast radius to the new syntax
rather than changing the resolution path for every action-value across the
engine). The function set is fixed and hardcoded to add_days; an
unsupported name and a nested function-call argument are both rejected
with a clear error rather than dispatched or evaluated. parse_function_call
only recognizes the exact `identifier(...)` shape, which cannot occur in
any existing bare dot-path, so ordinary {path} bindings are unaffected.

Covers the motivating end-to-end case with an integration test: a
scheduled play computing a new node's end_date as start_date + N days via
the new binding syntax.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Code Review Summary

Review Type: Initial Review (no prior reviews/comments found via gh pr view --json reviews,comments)

This PR closes #2640 cleanly on the "does it do what it claims" axis: add_days is a genuinely deterministic, checked-arithmetic date function, and the new {fn(...)} action-value binding syntax is scoped exactly as documented — a fixed one-arm-today match, gated so it can never intercept an existing bare {path} binding. I verified the panic-safety and injection-resistance claims empirically, not just by reading: I ran the PR's own test suites (cargo test -p nodespace-core --lib playbook::cel::tests::add_days — 10/10 pass; --lib playbook::actions::tests — 86/86 pass; the new end-to-end scheduled-play integration test — pass), then added and ran my own throwaway adversarial tests directly against this build (both-args-nested calls, 3-level nesting, 100,000 unmatched (/), i64::MAX/i64::MIN as literal argument text, a >i64 digit string) — every case returned a clean Err, zero panics. cargo clippy --lib -D warnings and cargo fmt --check are both clean. I reverted my scratch tests before finishing (repo is back to the PR's own diff).

There is one real, non-obvious gap this surfaced: the ADR-060 invariant-rule determinism validator was never updated to account for the new action-value function-call surface, and its doc comment now asserts something the PR makes false. Details below. Not exploitable today (the one function is deterministic), but it's exactly the class of "silently invalidated invariant" this subsystem has been adversarially reviewed for before, and it's cheap to close now.

Requirements Check (issue #2640)

  • ✅ Design decision made and documented (Option A vs B) with rationale — PR body and module-doc comments are explicit and match the actual code.
  • ✅ add_days(date_string, n) available from an action's computed field value — confirmed via a real running-engine integration test (scheduled_play_computes_end_date_via_add_days_and_writes_it_to_a_new_node), which I ran myself and it passes.
  • ✅ Scheduled Play computes end_date = start_date + N days end-to-end, exercised by an integration test, not just unit-level mocking — confirmed, ran it myself.
  • ✅ Existing {path} interpolation / CEL condition behavior unaffected — confirmed by reading parse_function_call (gated on a literal ( character, which cannot appear in any existing path shape) and by the PR's own regression tests, which I also ran.
  • ⚠️ "Tests pass" / "quality:fix" — I did not run the full bun run test:all pyramid (frontend is untouched by this PR; only Rust files changed), but ran the Rust-relevant subset directly plus clippy/fmt, all clean.

Findings

Critical Issues

  • 📁 packages/core/src/playbook/validation.rs:878-881 (unchanged by this PR) — ADR-060 §2 determinism check has a real, unenforced coverage gap this PR opens, and the doc comment describing it is now factually false.

    The comment for validate_invariant_eligibility's "Deterministic" guarantee reads:

    "Action params are pure {binding} data references (see actions.rs) with no function-call surface, and no random-value function is registered anywhere, so conditions are the complete non-deterministic surface."

    That's no longer true after this PR: action params now have exactly one function-call surface, {add_days(...)}. The actual check (validation.rs:984-998) only calls path_extractor::extract_function_names(&condition.source) — i.e. it scans CEL conditions for non-deterministic function names. I grepped validation.rs for any reference to extract_function_names, resolve_function_call, or parse_function_call/add_days and found exactly one call site (line 988), scoped to rule.conditions only. Nothing statically checks whether a function reachable from an action-value {fn(...)} binding is deterministic.

    Today this is safe purely by luck of the current match arm: BindingContext::resolve_function_call (actions.rs) currently supports only add_days, and add_days genuinely never reads wall-clock time (correctly excluded from NON_DETERMINISTIC_FUNCTIONS, confirmed and test-covered). But that safety now rests entirely on a human remembering, every time a second function gets added to that match, to also hand-verify it's deterministic — there is no test, debug_assert!, or validator wiring that would catch a future non-deterministic addition (e.g. a hypothetical now_plus_days or random_id) before it silently broke the ADR-060 §2 termination/determinism proof for invariant rules. That's precisely the shape of bug this subsystem's last review round was built to catch (a trust boundary whose enforcing code quietly stopped covering an expanded surface).

    Recommendation (small, mechanical, doesn't require a design change):

    1. Update the validate_invariant_eligibility doc comment to reflect that action params now do have a fixed function-call surface, and state explicitly why it's currently safe (single hardcoded deterministic function) rather than asserting the (now false) absence of one.
    2. Either (a) extend the "Deterministic" check in validate_invariant_eligibility to also scan each invariant-eligible rule's action params for the {name(...)} shape and reject any name in NON_DETERMINISTIC_FUNCTIONS, mirroring the existing condition check — the parsing primitive (parse_function_call) already exists in actions.rs and could be exposed/reused — or (b) at minimum add a unit test (e.g. in cel.rs or actions.rs) that asserts every function name BindingContext::resolve_function_call can dispatch to is absent from NON_DETERMINISTIC_FUNCTIONS, so a future addition trips a test rather than silently shipping.

    I'd treat this as blocking only in the sense that it's cheap to fix now and expensive to rediscover later — the current PR's own new code is otherwise sound (see below).

Suggested Improvements

  • 📁 packages/core/src/playbook/cel.rs:669-679 (compute_add_days) vs. packages/core/src/playbook/cel.rs:392-397 (parse_date_and_compute_days) — both independently implement the same "try RFC 3339, then try bare %Y-%m-%d" two-step date parse. Minor DRY violation; a shared fn parse_flexible_date(&str) -> Option<ParsedDate> (enum over DateTime<FixedOffset> vs NaiveDate) would remove the duplication. Not blocking — the two call sites use the result differently enough (day-diff vs. shift-and-reformat) that the duplication is small and low-risk, but worth a follow-up if a third date function shows up.

Nitpicks

  • Nit: resolve_add_days_call (actions.rs:69-121) only accepts the date argument as a dot-path, never a literal date string (e.g. add_days(trigger.node.id, "2026-01-01") isn't supported — only paths resolve there). That matches the motivating use case and isn't a defect, but could trip up a play author who expects symmetry with the n argument's dual path-or-literal support. Worth a one-line doc-comment callout if it isn't obvious from usage; not blocking.
  • Nit: the error text "add_days: first argument ('{}') did not resolve to a string date, got: {}" (actions.rs:99-104) interpolates date_value via Display on serde_json::Value — confirmed this compiles and doesn't panic (serde_json::Value implements Display), just flagging it for the next reader since it's a slightly unusual choice vs. {:?}.

Verdict

REQUEST CHANGES — solely for the validation.rs determinism-coverage gap above. Everything else in this PR (the parser, the fixed dispatch, the date arithmetic, and the test coverage including a real end-to-end integration test) held up under adversarial testing I ran directly against this build, not just static reading, and clippy/fmt are clean. The requested fix is small (doc update + either a validator extension or a guarding test) and doesn't require touching the design this PR already made.

🤖 Automated pragmatic-code-review

@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: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above. Summary: the new add_days function-call binding surface and date arithmetic are solid (verified via the PR's own tests plus my own adversarial probes — nested calls, malformed parens, i64::MAX/MIN, empty arg lists — all clean errors, no panics; clippy/fmt clean). One real gap requested to be fixed before merge: packages/core/src/playbook/validation.rs's ADR-060 determinism check (validate_invariant_eligibility) was not updated to cover the new action-value function-call surface, and its doc comment asserting action params have 'no function-call surface' is now false.

mstomar125 and others added 2 commits September 17, 2026 11:57
Address review feedback on PR #2715: the invariant-rule determinism check
(ADR-060 §2) only scanned rule.conditions for non-deterministic CEL
functions; action-value bindings could not express a function call before
this PR, but now can via {add_days(...)}, and the check's own doc comment
still claimed action params had "no function-call surface" -- a stale
claim invalidated by this PR's own change, and an unenforced gap for any
future non-deterministic function added to resolve_function_call's match
arm.

Adds a second determinism pass over each invariant rule's actions,
scanning action params for the {name(...)} function-call shape (via new
pub(crate) actions.rs helpers extract_binding_templates and
collect_binding_templates_in_value, reusing parse_function_call) and
checking matched names against the same NON_DETERMINISTIC_FUNCTIONS list
conditions already use. add_days is genuinely deterministic and stays
absent from that list, so this check is a no-op today -- it exists to
catch a future violation by name, not to flag add_days itself.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
for_each is a raw, unbraced binding path resolved through the same
BindingContext::resolve_binding as any {path} action-value, so a
function-call form is reachable there too without {...} wrapping -- the
previous commit's scan only looked inside {...}-wrapped param text and
would have missed it. Check action.for_each directly with
parse_function_call alongside the params scan.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Addressed the Critical finding from the automated review.

Fix (commits a533ef2, 5b3d2c0): extended the ADR-060 §2 determinism check in validate_invariant_eligibility (packages/core/src/playbook/validation.rs) to also scan action-value function-call bindings, not just conditions:

  • Added a second pass that walks each invariant rule action's params for {name(...)} binding templates (new pub(crate) helpers extract_binding_templates/collect_binding_templates_in_value in actions.rs, reusing parse_function_call) and checks the matched function name against the same NON_DETERMINISTIC_FUNCTIONS list conditions already use.
  • While implementing that, found and closed a second instance of the same gap: for_each is a raw, unbraced binding path resolved through the identical BindingContext::resolve_binding — so a function-call form is reachable there too, without {...} wrapping, and the params-only scan would have missed it. Added a direct parse_function_call check on action.for_each as well.
  • Updated the stale doc comment that claimed action params had "no function-call surface."
  • 4 new tests: rejects a function-call-shaped action-value binding using a known non-deterministic name (today, proving the check works by name even though today isn't itself implemented as an action-value function — it's a forward-looking guard), accepts add_days (genuinely deterministic), and two regression guards confirming ordinary {path} params and ordinary bare for_each paths are never flagged.

add_days itself stays correctly absent from NON_DETERMINISTIC_FUNCTIONS, so this check is a no-op today — it exists to catch a future non-deterministic function added to resolve_function_call's match arm before it can silently break the invariant-rule determinism guarantee.

Full pre-push gate (bun run test:all, cargo build --bin nodespaced, test:e2e, Tauri-seam integration suite) green on both follow-up pushes. bun run quality:fix clean.

The Nits/Improvements from the review (DRY overlap between compute_add_days and parse_date_and_compute_days's date parsing; add_days's date argument only accepting a path, not a literal) are left as-is — non-blocking per the review's own triage, and the DRY overlap mirrors an existing precedent in the same file rather than introducing a new pattern.

@mstomar125
mstomar125 merged commit dd4f050 into main Sep 17, 2026
@mstomar125
mstomar125 deleted the issue-2640-add-days-action-values branch September 17, 2026 10:07
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.

Add computed-date arithmetic to the playbook engine (action values, not just CEL conditions)

1 participant