From 1a4a3f41c9cbd5aec31a80c623a4c3c29eb9afcd Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sun, 15 Nov 2026 16:54:59 -0500 Subject: [PATCH 1/3] feat(trogonstack-eda): add eda-bound-process-lifetime skill so process managers prove a maximum lifetime instead of relying on reapers Signed-off-by: Yordis Prieto --- .../eda-bound-process-lifetime/SKILL.md | 133 ++++++++++++++++++ .../principles/deadline-and-exit.md | 32 +++++ .../references/principles/longest-path.md | 48 +++++++ .../principles/loops-are-counted.md | 29 ++++ .../references/principles/shared-windows.md | 34 +++++ .../principles/terminal-states-absorb.md | 34 +++++ .../principles/time-is-a-message.md | 28 ++++ .../waits-are-where-lifetime-goes.md | 33 +++++ .../references/review/declare-and-check.md | 133 ++++++++++++++++++ .../references/review/finding-template.md | 46 ++++++ .../references/review/lifecycle-table.md | 38 +++++ 11 files changed, 588 insertions(+) create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/deadline-and-exit.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/longest-path.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/loops-are-counted.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/shared-windows.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/terminal-states-absorb.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/time-is-a-message.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/waits-are-where-lifetime-goes.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/declare-and-check.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/finding-template.md create mode 100644 plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/lifecycle-table.md diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md new file mode 100644 index 0000000..d6c9c97 --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md @@ -0,0 +1,133 @@ +--- +name: eda-bound-process-lifetime +description: "Design or review event-driven process managers, sagas, and multi-step workflows so every instance provably ends within a known maximum lifetime (T_max). Lists the waiting states, gives each one a deadline and a named exit, keeps loops counted, makes late timers and duplicates harmless, and computes T_max from the longest path. Produces a lifecycle table, findings for every unbounded wait or loop, and the T_max derivation. Use when designing a saga, process manager, approval flow, OAuth or payment flow, or any aggregate with pending or awaiting states; when reviewing a state table in an ADR or design doc; when instances get stuck, need a reaper, or block a version cutover; and when asking 'how long can this run', 'when can we delete the old version', or 'how long must we keep these streams'. Do not use for long-lived entities that never finish (accounts, sessions, connections), periodic reconcilers, event naming or payload design (use event-definition), full event modeling workflows, or race conditions (use concurrency-find-toctou)." +allowed-tools: + - AskUserQuestion + - Read + - Write + - Bash +--- + +# Bound Process Lifetime + +A process that can wait forever will eventually be waiting forever. Give every wait a deadline and an exit, count every loop, and the longest an instance can live becomes a number you compute instead of a hope. + +## Core Principle + +A process manager (saga, workflow, multi-step aggregate) coordinates other actors: it sends a command, then waits for something to come back. Each wait is a bet that the other side answers. When the bet has no deadline, the instance can sit in that state indefinitely, and nobody can say when it ends. + +Once every waiting state has a deadline and every loop has a count, the maximum lifetime `T_max` follows from the definition: add the deadlines along the longest path. That number turns operational problems into waiting: + +- **Version cutover**: new instances start on the new version; old instances are guaranteed finished by `deploy_time + T_max`, then the old code is deleted. No in-flight state migration. +- **Retention**: a finished instance's stream is kept for `T_max` plus an audit margin, not forever by default. +- **Stuck instances**: impossible by construction. Every instance ends in a typed terminal state. + +The restriction is the feature. You give up "wait as long as it takes", and in exchange the lifetime question becomes decidable. There is no framework or DSL behind this skill: it is a discipline applied to whatever state table, code, or design document exists, and the output is a lifecycle table a team can later encode and check mechanically. + +## When It Does Not Apply + +Some things are entities, not processes: an account, a session log, a connection, a subscription. They have no terminal outcome by design. Do not force deadlines onto them. The bounded processes are the flows that coordinate them (opening an account, refreshing a credential, settling a payment). A periodic reconciler is a loop, not a process; bound each run, not the reconciler. A process that truly must run indefinitely (a perpetual monitor) is decomposed into chained bounded instances, each handing off to the next. + +## Principles + +Apply them in order. A state or loop that fails an earlier principle is a finding; the later principles shape the fix. Each one names its reference; read it when the situation matches, not up front. + +### 1. Waits Are Where Lifetime Goes + +Instant transitions (decide, emit, move on) cost no lifetime. Only waiting states do: a command was sent and the process needs an event it does not control (a reply, a callback, a human, a provider, a timer). The first job is to separate waiting states from instant ones, because only waiting states need deadlines and only they count toward `T_max`. + +Read [references/principles/waits-are-where-lifetime-goes.md](references/principles/waits-are-where-lifetime-goes.md) when building the state list or when it is unclear whether a state waits. + +### 2. Every Waiting State Has A Deadline And A Named Exit + +A deadline without an exit is a log line; an exit without a deadline is a hope. Each waiting state needs both: how long, and which event ends the state when time runs out (`Expired`, `OutcomeUnknown`, `Failed` with a typed reason). Choosing what the timeout *means* is a business decision, and the skill asks for it rather than inventing it. A background reaper that sweeps "stuck" instances is evidence of a missing deadline, not a substitute for one. + +Read [references/principles/deadline-and-exit.md](references/principles/deadline-and-exit.md) when a state lacks either, when choosing a deadline value, or when a reaper exists. + +### 3. Time Is A Message + +The deadline fires as a message the process schedules for itself on entering the waiting state, delivered into the same stream or correlation as every other input. The process never reads a wall clock to decide. If the real reply arrives first, the late timer must be refused or absorbed like any other stale command. The scheduler's delivery delay is part of the bound and has to be stated. + +Read [references/principles/time-is-a-message.md](references/principles/time-is-a-message.md) when designing how deadlines fire, or when the code polls, sleeps, or compares timestamps to decide. + +### 4. Loops Are Counted, Never Conditional + +`retry up to 3 times` is bounded; `retry until it works` is not. `repeat at most 10 iterations` is bounded; `while not shipped` is not. A loop whose exit depends only on the outside world adds unbounded lifetime even if every single wait inside it has a deadline. Count it, or move the repetition out of the process (a fresh instance per attempt, chained). + +Read [references/principles/loops-are-counted.md](references/principles/loops-are-counted.md) when the design has retries, polling, repeat-until, or a state that can be re-entered. + +### 5. Concurrent Waits Share One Window + +Waiting for A and B together is one wait, not two: one deadline covers the join, and the partial states (got A, got B) inherit it rather than restarting it. Waiting for A or B is one wait that the first arrival ends. A phase that spans several states (consent requested, then callback received) is often one window set when the phase begins. Restarting a timer per partial state silently multiplies the bound. + +Read [references/principles/shared-windows.md](references/principles/shared-windows.md) when the process waits on several inputs at once, or when a deadline is set once and spans several states. + +### 6. Terminal States Absorb + +Every path ends in a typed terminal state (`Completed`, `Failed`, `Expired`, `Cancelled`, `Killed`). Once there, duplicates, late replies, and late timers change nothing: they are refused or recorded as no-ops. Deterministic message identity (derived from the instance and step, not random) makes redelivery harmless. Without absorption, a late timer can reopen a finished instance and the bound is fiction. + +Read [references/principles/terminal-states-absorb.md](references/principles/terminal-states-absorb.md) when checking what happens after the end, or when a late or duplicate input could move a finished instance. + +### 7. Lifetime Is The Longest Path + +`T_max` is the longest path from the initial state to any terminal state, where each waiting window contributes its deadline once and instant transitions contribute zero, plus the scheduler's delivery delay for each timer on the path. Compare it to a declared budget. A budget exceeded is a design conversation, not a rounding error. + +Read [references/principles/longest-path.md](references/principles/longest-path.md) when computing `T_max`, when there is no budget yet, or when the result surprises anyone. + +## Procedure + +Works the same for a new design and for a review of an existing one (code, ADR state table, sequence diagram, prose). + +1. **Classify.** Decide whether the subject is a process (it has terminal outcomes) or an entity. For an entity, stop and say so, naming the processes inside it that could be bounded instead. +2. **List states.** Build the lifecycle table (template below): every state, what enters it, what leaves it, which states are terminal, and which events record progress without changing state (self-loops). +3. **Mark waits.** Classify each non-terminal state as instant or waiting (principle 1). +4. **Give each wait a deadline and an exit** (principles 2, 3, 5). Group states that share a window. Where a value or meaning is missing, ask with AskUserQuestion; never invent a business timeout. In a review, each missing one is a finding. +5. **Check loops** (principle 4). Every re-entry is counted or moved out. +6. **Check absorption** (principle 6): late timer, duplicate command, late reply, each against every terminal state and every state the timer no longer covers. +7. **Compute `T_max`** (principle 7). Show the derivation. Ask for the budget if none is declared. +8. **Report.** Lifecycle table, findings (one per gap), `T_max` derivation, and residuals. + +## Lifecycle Table + +```markdown +| State | Kind | Entered by | Left by | Window | Deadline | On deadline | +|---|---|---|---|---|---|---| +| | initial / waiting / instant / terminal | | | | | | +``` + +Self-loops go in "Left by" as ` (stays)`. Read [references/review/lifecycle-table.md](references/review/lifecycle-table.md) for a filled example and how to encode the table so a program can check it. + +## Finding Format + +``` +### + +- Location: +- State: +- Waiting on: +- Missing: +- Consequence: +- Principle: +- Fix: +- Residual: +``` + +Read [references/review/finding-template.md](references/review/finding-template.md) for a fully worked example. + +## Making It Mechanical Later + +Without a framework, the lifecycle table is the artifact. When a team wants the bound enforced rather than reviewed, the table becomes a declaration next to the schema (a protobuf custom option, a YAML file) and a small program checks it in CI: every name resolves, every waiting state is covered by a timer, every state reaches a terminal one, no cycles except self-loops, and `T_max` fits the budget. A conformance test then proves the hand-written state machine agrees with the declaration. + +Read [references/review/declare-and-check.md](references/review/declare-and-check.md) when the user wants enforcement, a schema annotation, or a CI check. + +## Quality Checklist + +- [ ] The subject was classified as a process or an entity, and entities were not given deadlines. +- [ ] Every non-terminal state is marked instant or waiting. +- [ ] Every waiting state has a deadline value and a named exit event, or a finding saying it does not. +- [ ] No deadline value or timeout meaning was invented; missing ones were asked for or reported. +- [ ] States sharing one window are grouped and counted once. +- [ ] Every loop has a count, or a finding. +- [ ] Late timers, duplicates, and late replies are shown to be refused or absorbed in every terminal state. +- [ ] `T_max` is derived step by step, includes the timer delivery delay, and is compared with a budget. +- [ ] Any reaper or sweeper is explained as a missing deadline or justified as a backstop. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/deadline-and-exit.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/deadline-and-exit.md new file mode 100644 index 0000000..a5e019a --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/deadline-and-exit.md @@ -0,0 +1,32 @@ +# Every Waiting State Has A Deadline And A Named Exit + +A wait is bounded only when it states both how long it will wait and which event ends it when the time is up. + +## Why It Holds + +A deadline alone does nothing: when it passes, something has to happen, and that something must be a recorded transition to a known state, or the instance is still sitting where it was. An exit alone (a `Cancel` command, an `Expire` command) does nothing either if no one is obliged to send it by a known time. Bounding needs the pair: after `d`, the process receives the exit input and moves to a defined state. + +The exit also has to *mean* something. "The provider never answered" can mean the request failed, the request may have succeeded and needs reconciliation, the user abandoned the flow, or the step should be escalated to a person. Those are different business outcomes with different follow-ups. Choosing between them is a product or domain decision, so it is asked for, not invented. + +## Choosing The Deadline Value + +- **From the other party's contract.** A provider's documented response time, a token or code lifetime, a payment network's settlement window. The deadline is no shorter than what the other side may legitimately take. +- **From the person waiting.** For human steps: how long until the request is stale for the business (a consent link, an approval request, a quote). Then decide the exit: expire, remind and extend once (counted), or escalate. +- **From what the exit costs.** A short deadline whose exit is "outcome unknown, reconcile" is cheap. A short deadline whose exit is "fail and refund" is expensive when it fires spuriously. +- **Round and named.** `10m consent window`, `30s provider response`, not `437s`. Deadlines are read by people during incidents. + +## What Violating It Looks Like + +- A waiting state whose only exits are the happy reply and an explicit cancel. +- An expiry field stored on the record that nothing schedules or acts on. +- "A reaper sweeps instances stuck in X." The reaper is a deadline with no stated value and an exit decided at sweep time. It is evidence of a missing deadline. +- A timeout in the client library (HTTP timeout, RPC deadline) treated as the process deadline. The client timeout bounds one call; if the response is lost, the process is still waiting unless the timeout produces a recorded exit event. +- A human approval with no expiry because "they will get to it". + +## What The Reviewer Must Cite + +For each waiting state: the deadline value and where it is configured, the exit event, the state the exit leads to, and what that state means for the business. For a missing value or meaning: a finding, and the question to ask. + +## The Wrong Fix It Rules Out + +Keeping the reaper and tuning its interval. A reaper decides outcomes in bulk, outside the process, on a schedule nobody reasons about; a deadline decides one outcome inside the process at a stated time. A reaper may remain as a backstop for a broken scheduler, but then it only *delivers* the exit the process already expects, it never chooses one. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/longest-path.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/longest-path.md new file mode 100644 index 0000000..0de6dbc --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/longest-path.md @@ -0,0 +1,48 @@ +# Lifetime Is The Longest Path + +The maximum lifetime of an instance is the heaviest path through its state graph, where waiting windows weigh their deadline and everything else weighs zero. + +## Why It Holds + +With every wait bounded (principles 2 to 5), loops counted (unrolled up to their maximum), and terminal states final (principle 6), the state graph is a finite directed acyclic graph apart from self-loops that record progress without changing state. The worst an instance can do is take the path that accumulates the most waiting. That path's weight is `T_max`. + +## Computing It + +1. Unroll each counted loop to its maximum iterations. +2. Weigh each path: add each window's deadline **once** if the path passes through any state it covers. Instant transitions and self-loops add nothing. +3. Add the timer delivery delay `delta` once per window on the path. +4. `T_max` is the maximum over all paths from the initial state to a terminal state. + +Graphs for real process managers have a handful of states, so enumerating paths by hand or in a few lines of code is fine. + +Worked example: + +```text +consent_window 10m covers AwaitingConsent, CallbackClaimed +exchange 30s covers Exchanging +reconciliation 15m covers OutcomeUnknown +delta (scheduler delivery delay) 1m per timer + +Longest path: AwaitingConsent -> CallbackClaimed -> Exchanging -> OutcomeUnknown -> Failed +T_max = 10m + 30s + 15m + 3 * 1m = 28m30s +Budget: 30m -> fits +``` + +## The Budget + +Declare a budget per process type: the lifetime the business is willing to promise. It is the number operations will use for version drain (`deploy_time + T_max`) and retention (`T_max` plus audit margin). When `T_max` exceeds the budget, the options are a shorter deadline, a different exit (escalate instead of wait), or splitting the process into chained instances. Raising the budget is allowed, but it is a recorded decision, not a default. + +## What Violating It Looks Like + +- No one can state how long the process can run. +- Version cutover plans that say "wait until the old instances drain" with no date. +- Retention set to forever because nobody knows when an instance is safe to drop. +- A `T_max` computed without the scheduler delay, or with a shared window counted per state. + +## What The Reviewer Must Cite + +The path that yields `T_max`, the arithmetic, the `delta` used and where it comes from, and the budget it is compared with. + +## The Wrong Fix It Rules Out + +Measuring `T_max` from production (the p99 of instance lifetimes). Observed lifetimes say how long instances happened to run; the bound says how long they can run. Use the measurement to check the bound, never to replace it. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/loops-are-counted.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/loops-are-counted.md new file mode 100644 index 0000000..7c66993 --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/loops-are-counted.md @@ -0,0 +1,29 @@ +# Loops Are Counted, Never Conditional + +A loop adds bounded lifetime only when its number of iterations is fixed before it starts. + +## Why It Holds + +Each iteration of a loop may contain a bounded wait, but the number of iterations multiplies it. `retry until success` with a 30 second deadline per attempt is unbounded, because nothing caps the attempts. `retry at most 3 times` with the same deadline costs at most 90 seconds plus backoff. The difference is whether the exit depends only on the outside world (unbounded) or also on a counter the process owns (bounded). + +A state that can be re-entered (`Pending -> Retrying -> Pending`) is a loop even if nobody calls it one. Every cycle in the state graph needs a counter carried in state, and the counter is part of the definition, not a runtime setting someone can raise to infinity. + +## Decomposing What Must Run Forever + +Some behavior really does repeat without end: a monitor that checks an entity every day, a subscription that renews monthly. Model each period as its own bounded instance that, at its end, starts the next one (or is started by a schedule). Each instance has a `T_max`; the chain does not need one. Versioning then works per instance: a new period starts on the new version. + +## What Violating It Looks Like + +- `while not done: send; wait` with no counter. +- Retry policies configured as "infinite" or "until success" for a step inside a process. +- Backoff with no cap on attempts (exponential backoff bounds the rate, not the count). +- A cycle in the state table with no counter field in state. +- A long-running "watcher" process that never terminates by design. + +## What The Reviewer Must Cite + +For each cycle in the state graph: the counter, its maximum, where the maximum is defined, and the exit taken when it is exhausted (typically `Failed` with a reason, or escalation). + +## The Wrong Fix It Rules Out + +Adding a global timeout on top of an uncounted loop. It bounds the instance but hides that the loop itself never gives up, and the timeout's exit rarely means what the loop's exhaustion should mean. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/shared-windows.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/shared-windows.md new file mode 100644 index 0000000..12029ca --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/shared-windows.md @@ -0,0 +1,34 @@ +# Concurrent Waits Share One Window + +When a process waits for several inputs as one step, a single deadline covers the step, and the partial states inherit that deadline instead of starting new ones. + +## Why It Holds + +Waiting for A **and** B is one logical wait. Implemented as a state machine it becomes several states (`WaitingForBoth`, `GotA`, `GotB`), and it is tempting to give each its own deadline. Then a slow A followed by a slow B costs two deadlines, and the bound grows with the number of partial states. One window, set when the step begins and covering every partial state, keeps the cost at one deadline however the inputs arrive. + +Waiting for A **or** B is also one wait: the first arrival ends it, and the deadline covers the step until then. + +The same shape appears without concurrency. A phase that is set up once and then passes through several states (consent link issued, callback received, code exchange about to start) often has one deadline fixed at the start of the phase. Modelling it per state would count it twice. + +## How To Declare It + +Give the window a name, a duration, the set of states it covers, and its exit. It arms on entering the set and disarms on leaving it. A window whose covered states are not contiguous on every path would re-arm, which is a design error. + +```text +window consent_window: 10m, covers [AwaitingConsent, CallbackClaimed], on deadline: Expire +window exchange: 30s, covers [Exchanging], on deadline: RecordOutcomeUnknown +``` + +## What Violating It Looks Like + +- Separate timeouts on `GotA` and `GotB`, each restarting the clock. +- A deadline stored once on the record but documented per state, so readers add it up twice. +- A join that waits for "all replies" with a per-reply timeout and no overall one. + +## What The Reviewer Must Cite + +For each join or multi-state phase: the window, the states it covers, when it arms and disarms, and its exit. For a disjunction: which arrival ends it and what happens to the losers (they are late inputs, absorbed per [terminal-states-absorb.md](terminal-states-absorb.md)). + +## The Wrong Fix It Rules Out + +Reducing per-state deadlines until their sum looks acceptable. The problem is double counting, not the values; shrinking them makes the honest single deadline too short. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/terminal-states-absorb.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/terminal-states-absorb.md new file mode 100644 index 0000000..2407893 --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/terminal-states-absorb.md @@ -0,0 +1,34 @@ +# Terminal States Absorb + +Once an instance reaches a terminal state, no input can move it again: duplicates, late replies, and late timers are refused or recorded as no-ops. + +## Why It Holds + +Messaging is at-least-once and unordered at the edges. The reply that lost the race against the deadline still arrives. The timer scheduled before the reply arrived still fires. The command retried by a client after a network blip arrives twice. If any of these can move a finished instance (reopen it, re-run a step, overwrite the outcome), then "finished" is not final, the instance can live past `T_max`, and the bound is fiction. + +Absorption has two parts: + +- **Refusal by state.** The decide function rejects inputs that do not apply in the current state, and a terminal state accepts none (or accepts them as explicit no-ops that record nothing). The same rule covers non-terminal states a timer no longer covers: a timer for `Exchanging` arriving in `Completed` is refused. +- **Deterministic identity.** Messages and events carry ids derived from the instance and the step (for example a name-based UUID from `instance_id + step + attempt`), not random ids. A redelivered command produces the same id, and the store or the decide function recognizes it as already applied. + +## Typed Outcomes + +Terminal states are typed and few: `Completed`, `Failed(reason)`, `Expired`, `Cancelled`, `Killed`. Each says why the instance ended, which is what operators and compensations need. "Done" with a free-text note is not a typed outcome. + +A kill or abort transition, available from every non-terminal state, gives operators a bounded way to end an instance early (for an urgent version cutover, for example), followed by compensation and a restart on the new version. + +## What Violating It Looks Like + +- A late reply after `Expired` that flips the instance to `Completed`. +- A late timer that moves a completed instance to `Expired`. +- Random event ids, so a redelivered command appends a second event. +- Terminal states that accept "retry" commands and become non-terminal again. +- No way to end an instance early except deleting its data. + +## What The Reviewer Must Cite + +For each terminal state: what happens to a duplicate command, a late reply, and a late timer. For each timer: what happens when it arrives in a state it does not cover. The id scheme for commands and events. + +## The Wrong Fix It Rules Out + +Cancelling timers on success and calling it handled. Cancellation is itself a message that can be lost or arrive after the timer fired. Refusal in the decide function works regardless of ordering. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/time-is-a-message.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/time-is-a-message.md new file mode 100644 index 0000000..3db4603 --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/time-is-a-message.md @@ -0,0 +1,28 @@ +# Time Is A Message + +The deadline reaches the process as an ordinary input it scheduled for itself, never as a clock reading inside a decision. + +## Why It Holds + +An event-sourced process decides from its history. If a decision reads the current time, replaying the same history on another day gives a different answer, and two replicas can disagree about whether the deadline passed. A timer message removes the clock from the decision: on entering a waiting state, the process schedules its exit input (`ExpireX`, `RecordOutcomeUnknown`) for `now + d` through a durable scheduler, addressed to the same instance. When it arrives, it is folded and decided like any reply. Replays see the recorded expiry event, not the clock. + +Because the timer is just another input, it races with the real reply, and it can arrive after the process has moved on. The process must refuse or absorb a timer whose state it has left (see [terminal-states-absorb.md](terminal-states-absorb.md)). That is simpler than cancelling timers: cancellation can fail, refusal cannot. + +## The Scheduler Is Part Of The Bound + +A timer is delivered some time after it is due: queue lag, a scheduler outage, a consumer restart. Call the worst case `delta`. The real bound is the sum of the deadlines plus `delta` for each timer on the path. If the scheduler states no delivery-delay bound, say so in the result; the number is then a target, not a guarantee. + +## What Violating It Looks Like + +- `if now() > requested_at + 10m then expire` inside a decide or fold function. +- A loop that sleeps and polls the external system until it answers. +- An in-memory timer (process-local `setTimeout`, an actor's `send_after`) with no durable record, so a restart forgets the deadline. +- Expiry decided by a query over all instances (`WHERE requested_at < now() - 10m`), which is the reaper of [deadline-and-exit.md](deadline-and-exit.md). + +## What The Reviewer Must Cite + +Who schedules each timer, when (on entering which state), what input it delivers, where it is delivered (same stream or correlation), how a late timer is refused, and the scheduler's stated delivery delay. + +## The Wrong Fix It Rules Out + +Replacing the clock read with a more precise clock. Precision is not the problem; nondeterminism under replay and the lack of a recorded exit are. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/waits-are-where-lifetime-goes.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/waits-are-where-lifetime-goes.md new file mode 100644 index 0000000..aeae8b9 --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/waits-are-where-lifetime-goes.md @@ -0,0 +1,33 @@ +# Waits Are Where Lifetime Goes + +An instance spends its life in the states where it waits for something it does not control; every other transition takes no meaningful time. + +## Why It Holds + +A process manager reacts: an input arrives, it folds the input into state, decides, emits commands, and stops. That reaction is bounded by the code that runs it. Between reactions the instance is idle, parked in a state until the next input. If the next input is something the process itself controls (an internal step that fires immediately), the state is instant. If the next input comes from another actor (a service reply, a provider callback, a person clicking, a payment network, a timer), the state is waiting, and its duration is decided outside the process. + +So the lifetime question is entirely a question about waiting states. Finding them is the first step, and missing one is the most common way a bound turns out wrong. + +## How To Spot A Waiting State + +- A command or request was just sent and the state name says so: `Requested`, `Pending`, `Awaiting...`, `Sent`, `InFlight`, `Exchanging`, `Submitted`. +- The only ways out are events produced by another service, a human, or an external provider. +- The state exists so a correlation id can be matched against a later reply. +- An "unknown outcome" state after a lost response: the process is waiting for reconciliation, which is a wait. +- A human step: approval, consent, review, signature. Human waits are the longest and the most often left unbounded. + +Instant states, by contrast, are left by an event the process emits itself in the same reaction or the next internal step (`Validated`, `Routed`, `Recorded`). They need no deadline. + +## What Violating It Looks Like + +- A state table where every state looks alike and nobody can say which ones park the instance. +- A "processing" state that actually waits on an external call, so it is treated as instant and gets no deadline. +- An outcome-unknown or reconciliation state listed as a recovery detail rather than as a state the instance can sit in. + +## What The Reviewer Must Cite + +For each non-terminal state: instant or waiting, and for waiting states, which actor the process is waiting on and which event it expects. + +## The Wrong Fix It Rules Out + +Putting a single global timeout on the whole instance and calling it bounded. One overall deadline hides which wait is slow, gives every exit the same meaning, and usually ends up much larger than the sum of honest per-wait deadlines. The global budget belongs in [longest-path.md](longest-path.md) as a check on the per-wait deadlines, not as a replacement for them. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/declare-and-check.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/declare-and-check.md new file mode 100644 index 0000000..a6e76da --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/declare-and-check.md @@ -0,0 +1,133 @@ +# Declare And Check + +How to move from a reviewed lifecycle table to a bound a program enforces. The point is determinism: whether a process is bounded must be a pure function of its declaration, so the same schema always gives the same verdict and a regression fails CI instead of waiting for a reviewer to notice. + +There is no framework here. The pattern is three small pieces any team can build: a declaration, a checker, and a conformance test. + +## 1. Declare + +Put the lifecycle next to the schema of the events it describes, so a change to the events and a change to the lifecycle land in the same diff. With protobuf, a custom message option on the aggregate's event envelope works well: + +```proto +edition = "2023"; + +package example.process.v1; + +import "google/protobuf/descriptor.proto"; +import "google/protobuf/duration.proto"; + +extend google.protobuf.MessageOptions { + // Placed on the message that holds the aggregate's `oneof event`. + // Use a field number from your organization's registered extension range. + Lifecycle lifecycle = 50100; +} + +message Lifecycle { + google.protobuf.Duration budget = 1; // promised maximum lifetime, excluding scheduler delay + string genesis_event = 2; // oneof field name of the first event + string initial_state = 3; + repeated State states = 4; + repeated Transition transitions = 5; + repeated Window windows = 6; +} + +message State { + string name = 1; + bool terminal = 2; +} + +message Transition { + string from = 1; + string event = 2; // oneof field name on the envelope + string to = 3; // equal to `from` for progress that does not change state +} + +message Window { + string name = 1; + google.protobuf.Duration within = 2; + repeated string covers = 3; // armed on entering the set, disarmed on leaving it + string on_deadline = 4; // command message delivered when the window expires +} +``` + +Annotated envelope: + +```proto +message AttemptEvent { + option (example.process.v1.lifecycle) = { + budget: { seconds: 1800 } + genesis_event: "begun" + initial_state: "AwaitingConsent" + states: [ + { name: "AwaitingConsent" }, { name: "CallbackClaimed" }, + { name: "Exchanging" }, { name: "OutcomeUnknown" }, + { name: "Completed", terminal: true }, { name: "Failed", terminal: true }, + { name: "Cancelled", terminal: true }, { name: "Expired", terminal: true } + ] + transitions: [ + { from: "AwaitingConsent", event: "callback_claimed", to: "CallbackClaimed" }, + { from: "CallbackClaimed", event: "exchange_started", to: "Exchanging" }, + { from: "Exchanging", event: "authority_captured", to: "Exchanging" }, + { from: "Exchanging", event: "outcome_unknown_recorded", to: "OutcomeUnknown" }, + { from: "Exchanging", event: "completed", to: "Completed" } + // ... every other transition from the lifecycle table + ] + windows: [ + { name: "consent_window", within: { seconds: 600 }, + covers: ["AwaitingConsent", "CallbackClaimed"], on_deadline: "ExpireAuthorization" }, + { name: "exchange", within: { seconds: 30 }, + covers: ["Exchanging"], on_deadline: "RecordOutcomeUnknown" }, + { name: "reconciliation", within: { seconds: 900 }, + covers: ["OutcomeUnknown"], on_deadline: "FailAuthorization" } + ] + }; + + oneof event { + Begun begun = 1; + CallbackClaimed callback_claimed = 2; + // ... + } +} +``` + +The same structure works as YAML or JSON next to any schema language. Protobuf has the advantage that the checker can resolve event and command names against real message types. + +## 2. Check + +A checker reads only the compiled descriptors (or the YAML): no runtime, no network, no model. Run it as a schema-lint plugin or as a unit test. + +| Rule | Fails when | +|---|---| +| R1 resolve | A transition `event` is not a field of the envelope's `oneof`; an `on_deadline` is not a command message in the package; a referenced state is undeclared. | +| R2 coverage | An envelope event appears in no transition and is not the genesis event. | +| R3 armed | A non-terminal state is covered by no window. | +| R4 terminal | A terminal state has an outgoing transition. | +| R5 reachable | A state is unreachable from the initial state, or cannot reach a terminal state. | +| R6 acyclic | The graph has a cycle other than a `from == to` self-loop (counted loops are unrolled in the declaration). | +| R7 contiguous | A window's covered states are not contiguous along every path, so it would re-arm. | +| R8 budget | The longest path, adding each window once, exceeds the budget. | + +Output names the rule and the location, so the failure reads like a review finding: + +```text +example.attempts.v1.AttemptEvent: + R3 armed: state "Exchanging" is covered by no window + R3 armed: state "OutcomeUnknown" is covered by no window +``` + +## 3. Conform + +The declaration is a claim about the hand-written state machine. A generic test, driven by the declaration, keeps the two from drifting: + +1. For each declared transition, build a history that reaches `from`, fold the event through the real fold or evolve function, and assert the state is `to`. +2. For each undeclared `(state, event)` pair, assert the fold rejects it. +3. For each window, assert its `on_deadline` command is accepted in every covered state and refused in every other state, which proves late timers are harmless. +4. Feed duplicate and reordered histories and assert terminal states do not move. + +The only per-process code is a function that maps the fold state to a state name. + +Later, if several processes share the shape, generate the state enum, the transition table, and the "schedule `on_deadline` when the window arms" calls from the declaration, which removes drift entirely. Do that only once the hand-written version has proven the declaration is useful. + +## Where A Model Fits + +Drafting the declaration from a design document's state table is a reasonable job for an assistant. Deciding whether the result is bounded is not: that is the checker's job, and the draft passes or fails it like any hand-written change. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/finding-template.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/finding-template.md new file mode 100644 index 0000000..8795aaa --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/finding-template.md @@ -0,0 +1,46 @@ +# Finding Template: Worked Example + +One finding per unbounded wait, uncounted loop, missing absorption, or missing budget. This example comes from the OAuth attempt in [lifecycle-table.md](lifecycle-table.md). + +```markdown +### Code exchange can wait forever in Exchanging + +- Location: design doc, "Code exchange" section; `attempt/decide.rs:142` (ExchangeStarted handler) +- State: Exchanging +- Waiting on: the provider's token endpoint response, relayed by the exchange worker +- Missing: deadline, exit +- Consequence: if the worker crashes after sending the code, or the response is lost, the attempt stays + in Exchanging indefinitely. A periodic sweep ("reaper over attempts stuck in Exchanging") is the only + way out, and it runs on an unstated interval, so T_max for the process is undefined, old versions of + the attempt logic can never be proven drained, and attempt streams cannot be given a retention period. +- Principle: Every Waiting State Has A Deadline And A Named Exit +- Fix: on ExchangeStarted, schedule RecordOutcomeUnknown for now + 30s (above the provider's documented + token-endpoint timeout) on the attempt's own stream. The exit leads to OutcomeUnknown, which already + has a reconciliation path. Refuse RecordOutcomeUnknown in every state except Exchanging, so a late + timer after Completed or Failed is a no-op. The reaper, if kept, only sends RecordOutcomeUnknown for + attempts whose timer was lost; it never decides an outcome itself. +- Residual: OutcomeUnknown is itself unbounded (separate finding). The bound also depends on the + scheduler's delivery delay, which is not stated. +``` + +## Writing Guidance + +- **Consequence names the operational cost**, not only "it could hang": undefined `T_max`, blocked version drain, unbounded retention, operator toil. +- **Fix names a value and its source** (provider contract, business staleness), or says the value must be decided and by whom. Never a bare "add a timeout". +- **Fix names who schedules the timer and when**, and how a late timer is refused. +- **Residual is honest**: other unbounded states, unstated scheduler delay, a budget nobody has declared. + +## Summary Block + +After the findings, close the review with: + +```markdown +## Lifetime Summary + +- Process: +- Waiting states: ( bounded, unbounded) +- Loops: ( counted) +- T_max: | undefined ( unbounded waits) +- Budget: | not declared +- Verdict: bounded within budget | bounded over budget | unbounded +``` diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/lifecycle-table.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/lifecycle-table.md new file mode 100644 index 0000000..b750bf9 --- /dev/null +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/lifecycle-table.md @@ -0,0 +1,38 @@ +# Lifecycle Table + +The lifecycle table is the skill's main artifact. It lists every state of one process type, marks which states wait, and attaches each waiting state to a window with a deadline and an exit. + +## Columns + +| Column | Meaning | +|---|---| +| State | The state name used in code or the design. | +| Kind | `initial`, `waiting`, `instant`, or `terminal`. A state can be both `initial` and `waiting`. | +| Entered by | The event that moves the instance into this state. | +| Left by | Every event that leaves it, with the target state. Self-loops are marked `(stays)`. | +| Window | The named deadline covering this state, shared across states when one deadline spans a phase. `-` for instant and terminal states. | +| Deadline | Duration, or `MISSING`. | +| On deadline | The exit input the timer delivers and the state it leads to, or `MISSING`. | + +## Filled Example: OAuth Authorization Attempt + +A process that sends a user to a provider's consent page, receives the callback, exchanges the code for tokens, and records the result. One instance per attempt. + +| State | Kind | Entered by | Left by | Window | Deadline | On deadline | +|---|---|---|---|---|---|---| +| AwaitingConsent | initial, waiting | AuthorizationBegun | CallbackClaimed -> CallbackClaimed; Failed; Cancelled; Expired | consent_window | 10m | ExpireAuthorization -> Expired | +| CallbackClaimed | waiting | CallbackClaimed | ExchangeStarted -> Exchanging; Failed; Cancelled; Expired | consent_window | (shared) | ExpireAuthorization -> Expired | +| Exchanging | waiting | ExchangeStarted | AuthorityCaptured (stays); Completed; Failed; OutcomeUnknownRecorded -> OutcomeUnknown | exchange | MISSING | MISSING | +| OutcomeUnknown | waiting | OutcomeUnknownRecorded | AuthorityCaptured (stays); Completed; Failed | reconciliation | MISSING | MISSING | +| Completed | terminal | AuthorizationCompleted | none | - | - | - | +| Failed | terminal | AuthorizationFailed | none | - | - | - | +| Cancelled | terminal | AuthorizationCancelled | none | - | - | - | +| Expired | terminal | AuthorizationExpired | none | - | - | - | + +Reading it: the consent phase is bounded by one 10 minute window set when the attempt begins. `Exchanging` and `OutcomeUnknown` both wait on the provider (a token response, then reconciliation) and have no deadline, so the instance can sit there indefinitely. Each `MISSING` becomes a finding (see [finding-template.md](finding-template.md)). Cancel and Expire are not exits from `Exchanging` on purpose: once the code is sent, the exchange cannot be un-sent, so the only honest exits are a result or "outcome unknown". + +After the fixes (`exchange` 30s exiting to `OutcomeUnknown`, `reconciliation` 15m exiting to `Failed` with a typed reason), the longest path is `AwaitingConsent -> CallbackClaimed -> Exchanging -> OutcomeUnknown -> Failed`, and `T_max = 10m + 30s + 15m + 3 * delta`. + +## Encoding It + +The table is plain data. Keep it next to the code it describes (a markdown table in the design doc, a YAML file, or a schema annotation) so that changes to the process show up as changes to the table in review. To have a program check it instead of a reviewer, read [declare-and-check.md](declare-and-check.md). From 60f7ec112047444650fa3a3c431da1ebd23c128b Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Mon, 16 Nov 2026 07:40:04 -0500 Subject: [PATCH 2/3] fix(trogonstack-eda): keep bound-process-lifetime description within the 1024 character spec limit Signed-off-by: Yordis Prieto --- .../trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md index d6c9c97..6b1f4f5 100644 --- a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md @@ -1,6 +1,6 @@ --- name: eda-bound-process-lifetime -description: "Design or review event-driven process managers, sagas, and multi-step workflows so every instance provably ends within a known maximum lifetime (T_max). Lists the waiting states, gives each one a deadline and a named exit, keeps loops counted, makes late timers and duplicates harmless, and computes T_max from the longest path. Produces a lifecycle table, findings for every unbounded wait or loop, and the T_max derivation. Use when designing a saga, process manager, approval flow, OAuth or payment flow, or any aggregate with pending or awaiting states; when reviewing a state table in an ADR or design doc; when instances get stuck, need a reaper, or block a version cutover; and when asking 'how long can this run', 'when can we delete the old version', or 'how long must we keep these streams'. Do not use for long-lived entities that never finish (accounts, sessions, connections), periodic reconcilers, event naming or payload design (use event-definition), full event modeling workflows, or race conditions (use concurrency-find-toctou)." +description: "Design or review event-driven process managers, sagas, and multi-step workflows so every instance provably ends within a known maximum lifetime (T_max). Lists the waiting states, gives each one a deadline and a named exit, keeps loops counted, makes late timers and duplicates harmless, and computes T_max from the longest path. Produces a lifecycle table, findings for every unbounded wait or loop, and the T_max derivation. Use when designing a saga, process manager, approval flow, OAuth or payment flow, or any aggregate with pending or awaiting states; when reviewing a state table; when instances get stuck, need a reaper, or block a version cutover; and when asking 'how long can this run', 'when can we delete the old version', or 'how long must we keep these streams'. Do not use for long-lived entities that never finish (accounts, sessions, connections), periodic reconcilers, event naming or payload design (use event-definition), full event modeling workflows, or races (use concurrency-find-toctou)." allowed-tools: - AskUserQuestion - Read From 01c0391367e7d1b5484a5bf17fa6c055c2d807a7 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Mon, 16 Nov 2026 08:01:06 -0500 Subject: [PATCH 3/3] fix(trogonstack-eda): close bound-process-lifetime gaps where retries, stale timers, lost timer writes and reaction time could break the computed bound Signed-off-by: Yordis Prieto --- .../eda-bound-process-lifetime/SKILL.md | 9 ++-- .../references/principles/longest-path.md | 21 +++++---- .../principles/terminal-states-absorb.md | 6 +-- .../principles/time-is-a-message.md | 10 +++- .../references/review/declare-and-check.md | 47 +++++++++++++------ .../references/review/finding-template.md | 4 +- .../references/review/lifecycle-table.md | 2 +- 7 files changed, 64 insertions(+), 35 deletions(-) diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md index 6b1f4f5..4b5ff91 100644 --- a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/SKILL.md @@ -34,7 +34,7 @@ Apply them in order. A state or loop that fails an earlier principle is a findin ### 1. Waits Are Where Lifetime Goes -Instant transitions (decide, emit, move on) cost no lifetime. Only waiting states do: a command was sent and the process needs an event it does not control (a reply, a callback, a human, a provider, a timer). The first job is to separate waiting states from instant ones, because only waiting states need deadlines and only they count toward `T_max`. +Instant transitions (decide, emit, move on) cost no lifetime. Only waiting states do: a command was sent and the process needs an event it does not control (a reply, a callback, a human, a provider, a timer). The first job is to separate waiting states from instant ones, because only waiting states need deadlines. Waits dominate `T_max`; the only other term is a small stated bound per transition for delivering and handling each input (principle 7). Read [references/principles/waits-are-where-lifetime-goes.md](references/principles/waits-are-where-lifetime-goes.md) when building the state list or when it is unclear whether a state waits. @@ -70,7 +70,7 @@ Read [references/principles/terminal-states-absorb.md](references/principles/ter ### 7. Lifetime Is The Longest Path -`T_max` is the longest path from the initial state to any terminal state, where each waiting window contributes its deadline once and instant transitions contribute zero, plus the scheduler's delivery delay for each timer on the path. Compare it to a declared budget. A budget exceeded is a design conversation, not a rounding error. +`T_max` is the longest path from the initial state to any terminal state, where each arming of a waiting window contributes its deadline (a shared window once, a retried window once per attempt), plus the scheduler's delivery delay for each arming and a stated reaction bound for each transition. Without stated delay bounds, `T_max` is a target, not a guarantee. Compare it to a declared budget. A budget exceeded is a design conversation, not a rounding error. Read [references/principles/longest-path.md](references/principles/longest-path.md) when computing `T_max`, when there is no budget yet, or when the result surprises anyone. @@ -128,6 +128,7 @@ Read [references/review/declare-and-check.md](references/review/declare-and-chec - [ ] No deadline value or timeout meaning was invented; missing ones were asked for or reported. - [ ] States sharing one window are grouped and counted once. - [ ] Every loop has a count, or a finding. -- [ ] Late timers, duplicates, and late replies are shown to be refused or absorbed in every terminal state. -- [ ] `T_max` is derived step by step, includes the timer delivery delay, and is compared with a budget. +- [ ] Late timers (including timers from an earlier arming), duplicates, and late replies are shown to be refused or absorbed in every terminal state. +- [ ] Each timer is shown to be durable together with the transition that arms it. +- [ ] `T_max` is derived step by step, counts windows per arming, includes the timer delivery delay and the reaction bound, and is compared with a budget (or the verdict says none is declared). - [ ] Any reaper or sweeper is explained as a missing deadline or justified as a backstop. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/longest-path.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/longest-path.md index 0de6dbc..102ca57 100644 --- a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/longest-path.md +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/longest-path.md @@ -1,6 +1,6 @@ # Lifetime Is The Longest Path -The maximum lifetime of an instance is the heaviest path through its state graph, where waiting windows weigh their deadline and everything else weighs zero. +The maximum lifetime of an instance is the heaviest path through its state graph, where each arming of a waiting window weighs its deadline, each transition weighs the reaction bound, and nothing else adds time. ## Why It Holds @@ -9,9 +9,10 @@ With every wait bounded (principles 2 to 5), loops counted (unrolled up to their ## Computing It 1. Unroll each counted loop to its maximum iterations. -2. Weigh each path: add each window's deadline **once** if the path passes through any state it covers. Instant transitions and self-loops add nothing. -3. Add the timer delivery delay `delta` once per window on the path. -4. `T_max` is the maximum over all paths from the initial state to a terminal state. +2. Weigh each path: add each window's deadline **once per arming**. A window arms when the path enters any state it covers and disarms when it leaves them all. Moving between states the same window covers does not re-arm it; each unrolled loop iteration that re-enters the window does. +3. Add the timer delivery delay `delta` once per arming. +4. Add the reaction bound `rho` once per transition on the path. `rho` is the stated worst case for delivering a non-timer input and running the reaction that folds it (queue lag for replies and callbacks, plus handler time). It is usually small next to the deadlines, but it is not zero. +5. `T_max` is the maximum over all paths from the initial state to a terminal state. Graphs for real process managers have a handful of states, so enumerating paths by hand or in a few lines of code is fine. @@ -21,27 +22,29 @@ Worked example: consent_window 10m covers AwaitingConsent, CallbackClaimed exchange 30s covers Exchanging reconciliation 15m covers OutcomeUnknown -delta (scheduler delivery delay) 1m per timer +delta (scheduler delivery delay) 1m per arming +rho (reaction bound) 1s per transition Longest path: AwaitingConsent -> CallbackClaimed -> Exchanging -> OutcomeUnknown -> Failed -T_max = 10m + 30s + 15m + 3 * 1m = 28m30s +Armings: consent_window, exchange, reconciliation (3); transitions: 4 +T_max = 10m + 30s + 15m + 3 * 1m + 4 * 1s = 28m34s Budget: 30m -> fits ``` ## The Budget -Declare a budget per process type: the lifetime the business is willing to promise. It is the number operations will use for version drain (`deploy_time + T_max`) and retention (`T_max` plus audit margin). When `T_max` exceeds the budget, the options are a shorter deadline, a different exit (escalate instead of wait), or splitting the process into chained instances. Raising the budget is allowed, but it is a recorded decision, not a default. +Declare a budget per process type: the lifetime the business is willing to promise, including scheduler delay and reaction time, because it is compared with `T_max`, which includes both. It is the number operations will use for version drain (`deploy_time + T_max`) and retention (`T_max` plus audit margin). When `T_max` exceeds the budget, the options are a shorter deadline, a different exit (escalate instead of wait), or splitting the process into chained instances. Raising the budget is allowed, but it is a recorded decision, not a default. ## What Violating It Looks Like - No one can state how long the process can run. - Version cutover plans that say "wait until the old instances drain" with no date. - Retention set to forever because nobody knows when an instance is safe to drop. -- A `T_max` computed without the scheduler delay, or with a shared window counted per state. +- A `T_max` computed without the scheduler delay or the reaction bound, with a shared window counted per state, or with a retried window counted once. ## What The Reviewer Must Cite -The path that yields `T_max`, the arithmetic, the `delta` used and where it comes from, and the budget it is compared with. +The path that yields `T_max`, the armings and transitions on it, the arithmetic, the `delta` and `rho` used and where each comes from, and the budget it is compared with. When the platform states no bound for `delta` or `rho`, say so: `T_max` is then a target, not a guarantee. ## The Wrong Fix It Rules Out diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/terminal-states-absorb.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/terminal-states-absorb.md index 2407893..bb27291 100644 --- a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/terminal-states-absorb.md +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/terminal-states-absorb.md @@ -8,8 +8,8 @@ Messaging is at-least-once and unordered at the edges. The reply that lost the r Absorption has two parts: -- **Refusal by state.** The decide function rejects inputs that do not apply in the current state, and a terminal state accepts none (or accepts them as explicit no-ops that record nothing). The same rule covers non-terminal states a timer no longer covers: a timer for `Exchanging` arriving in `Completed` is refused. -- **Deterministic identity.** Messages and events carry ids derived from the instance and the step (for example a name-based UUID from `instance_id + step + attempt`), not random ids. A redelivered command produces the same id, and the store or the decide function recognizes it as already applied. +- **Refusal by state.** The decide function rejects inputs that do not apply in the current state, and a terminal state accepts none (or accepts them as explicit no-ops that record nothing). The same rule covers non-terminal states a timer no longer covers: a timer for `Exchanging` arriving in `Completed` is refused. A matching state name is not enough when a state can be re-entered: each timer carries the arming it was scheduled for (for example `instance_id + window + attempt`), and the decide function refuses it unless that arming is the active one, so a timer from attempt 1 cannot expire attempt 2. +- **Deterministic identity.** Messages and events carry ids derived from the instance and the step and the input itself (for example a name-based UUID from `instance_id + step + attempt + input type + source id`), not random ids. The input part keeps two different inputs of one step apart, such as both branches of a join, so deduplication never discards one of them. A redelivered command produces the same id, and the store or the decide function recognizes it as already applied. ## Typed Outcomes @@ -27,7 +27,7 @@ A kill or abort transition, available from every non-terminal state, gives opera ## What The Reviewer Must Cite -For each terminal state: what happens to a duplicate command, a late reply, and a late timer. For each timer: what happens when it arrives in a state it does not cover. The id scheme for commands and events. +For each terminal state: what happens to a duplicate command, a late reply, and a late timer. For each timer: what happens when it arrives in a state it does not cover, and when it arrives for an arming that is no longer active. The id scheme for commands and events. ## The Wrong Fix It Rules Out diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/time-is-a-message.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/time-is-a-message.md index 3db4603..dbe012a 100644 --- a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/time-is-a-message.md +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/principles/time-is-a-message.md @@ -8,6 +8,14 @@ An event-sourced process decides from its history. If a decision reads the curre Because the timer is just another input, it races with the real reply, and it can arrive after the process has moved on. The process must refuse or absorb a timer whose state it has left (see [terminal-states-absorb.md](terminal-states-absorb.md)). That is simpler than cancelling timers: cancellation can fail, refusal cannot. +## The Timer Is Durable With The State + +Entering the waiting state and scheduling its timer must not be two independent writes. If the state change is stored and the process crashes before the timer is scheduled, the instance waits with no deadline and no exit. Use one of: + +- The transition and the timer intent are recorded atomically (the timer is an event or command in the same append). +- An outbox records the timer intent in the same transaction as the state change, and a relay delivers it to the scheduler. +- A recovery step on restart scans for waiting states whose arming has no scheduled timer and schedules it. + ## The Scheduler Is Part Of The Bound A timer is delivered some time after it is due: queue lag, a scheduler outage, a consumer restart. Call the worst case `delta`. The real bound is the sum of the deadlines plus `delta` for each timer on the path. If the scheduler states no delivery-delay bound, say so in the result; the number is then a target, not a guarantee. @@ -21,7 +29,7 @@ A timer is delivered some time after it is due: queue lag, a scheduler outage, a ## What The Reviewer Must Cite -Who schedules each timer, when (on entering which state), what input it delivers, where it is delivered (same stream or correlation), how a late timer is refused, and the scheduler's stated delivery delay. +Who schedules each timer, when (on entering which state), how the timer intent is made durable together with the state transition, what input it delivers, where it is delivered (same stream or correlation), how a late timer is refused, and the scheduler's stated delivery delay. ## The Wrong Fix It Rules Out diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/declare-and-check.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/declare-and-check.md index a6e76da..afeb40d 100644 --- a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/declare-and-check.md +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/declare-and-check.md @@ -23,17 +23,26 @@ extend google.protobuf.MessageOptions { } message Lifecycle { - google.protobuf.Duration budget = 1; // promised maximum lifetime, excluding scheduler delay + google.protobuf.Duration budget = 1; // promised maximum lifetime, including scheduler delay and reaction time string genesis_event = 2; // oneof field name of the first event string initial_state = 3; repeated State states = 4; repeated Transition transitions = 5; repeated Window windows = 6; + google.protobuf.Duration scheduler_delay = 7; // delta: worst-case timer delivery delay + google.protobuf.Duration reaction_bound = 8; // rho: worst-case non-timer delivery plus handling +} + +enum StateKind { + STATE_KIND_UNSPECIFIED = 0; + STATE_KIND_WAITING = 1; + STATE_KIND_INSTANT = 2; + STATE_KIND_TERMINAL = 3; } message State { string name = 1; - bool terminal = 2; + StateKind kind = 2; // the initial state is named by Lifecycle.initial_state } message Transition { @@ -56,13 +65,19 @@ Annotated envelope: message AttemptEvent { option (example.process.v1.lifecycle) = { budget: { seconds: 1800 } + scheduler_delay: { seconds: 60 } + reaction_bound: { seconds: 1 } genesis_event: "begun" initial_state: "AwaitingConsent" states: [ - { name: "AwaitingConsent" }, { name: "CallbackClaimed" }, - { name: "Exchanging" }, { name: "OutcomeUnknown" }, - { name: "Completed", terminal: true }, { name: "Failed", terminal: true }, - { name: "Cancelled", terminal: true }, { name: "Expired", terminal: true } + { name: "AwaitingConsent", kind: STATE_KIND_WAITING }, + { name: "CallbackClaimed", kind: STATE_KIND_WAITING }, + { name: "Exchanging", kind: STATE_KIND_WAITING }, + { name: "OutcomeUnknown", kind: STATE_KIND_WAITING }, + { name: "Completed", kind: STATE_KIND_TERMINAL }, + { name: "Failed", kind: STATE_KIND_TERMINAL }, + { name: "Cancelled", kind: STATE_KIND_TERMINAL }, + { name: "Expired", kind: STATE_KIND_TERMINAL } ] transitions: [ { from: "AwaitingConsent", event: "callback_claimed", to: "CallbackClaimed" }, @@ -98,31 +113,33 @@ A checker reads only the compiled descriptors (or the YAML): no runtime, no netw | Rule | Fails when | |---|---| +| R0 values | A state's kind is unspecified; `budget`, `scheduler_delay`, or `reaction_bound` is missing or negative; a window's `within` is missing, zero, or negative. Runs first, so a negative duration can never shrink the R8 sum. | | R1 resolve | A transition `event` is not a field of the envelope's `oneof`; an `on_deadline` is not a command message in the package; a referenced state is undeclared. | | R2 coverage | An envelope event appears in no transition and is not the genesis event. | -| R3 armed | A non-terminal state is covered by no window. | -| R4 terminal | A terminal state has an outgoing transition. | +| R3 armed | A waiting state is covered by no window, or an instant or terminal state is covered by one. | +| R4 terminal | A terminal state has an outgoing transition, or a non-terminal state has none. | | R5 reachable | A state is unreachable from the initial state, or cannot reach a terminal state. | | R6 acyclic | The graph has a cycle other than a `from == to` self-loop (counted loops are unrolled in the declaration). | | R7 contiguous | A window's covered states are not contiguous along every path, so it would re-arm. | -| R8 budget | The longest path, adding each window once, exceeds the budget. | +| R8 budget | The longest path exceeds the budget, adding per window arming its `within` plus `scheduler_delay`, and per transition the `reaction_bound`. Under R6 and R7 each window arms at most once per path. | Output names the rule and the location, so the failure reads like a review finding: ```text example.attempts.v1.AttemptEvent: - R3 armed: state "Exchanging" is covered by no window - R3 armed: state "OutcomeUnknown" is covered by no window + R3 armed: waiting state "Exchanging" is covered by no window + R3 armed: waiting state "OutcomeUnknown" is covered by no window ``` ## 3. Conform The declaration is a claim about the hand-written state machine. A generic test, driven by the declaration, keeps the two from drifting: -1. For each declared transition, build a history that reaches `from`, fold the event through the real fold or evolve function, and assert the state is `to`. -2. For each undeclared `(state, event)` pair, assert the fold rejects it. -3. For each window, assert its `on_deadline` command is accepted in every covered state and refused in every other state, which proves late timers are harmless. -4. Feed duplicate and reordered histories and assert terminal states do not move. +1. Transitions: build a history that reaches each `from`, fold the declared event through the real fold or evolve function, and assert the state is `to`. +2. Undeclared pairs: assert the fold rejects every `(state, event)` pair the declaration does not list. +3. Arming: for every transition that enters a window from outside it, run the real decide function and assert it schedules `on_deadline` for `within` after the event, addressed to the same instance and written together with the event (same append or same outbox transaction). A state machine that folds correctly but never schedules its timer fails here. +4. Late timers: assert `on_deadline` is accepted in every covered state of the active arming and refused in every other state and for any earlier arming. +5. Duplicates: feed duplicate and reordered histories and assert terminal states do not move. The only per-process code is a function that maps the fold state to a state name. diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/finding-template.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/finding-template.md index 8795aaa..6baa823 100644 --- a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/finding-template.md +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/finding-template.md @@ -40,7 +40,7 @@ After the findings, close the review with: - Process: - Waiting states: ( bounded, unbounded) - Loops: ( counted) -- T_max: | undefined ( unbounded waits) +- T_max: | target (no stated delta or rho) | undefined ( unbounded waits) - Budget: | not declared -- Verdict: bounded within budget | bounded over budget | unbounded +- Verdict: bounded within budget | bounded over budget | bounded, budget not declared | unbounded ``` diff --git a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/lifecycle-table.md b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/lifecycle-table.md index b750bf9..b6fc136 100644 --- a/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/lifecycle-table.md +++ b/plugins/trogonstack-eda/skills/eda-bound-process-lifetime/references/review/lifecycle-table.md @@ -31,7 +31,7 @@ A process that sends a user to a provider's consent page, receives the callback, Reading it: the consent phase is bounded by one 10 minute window set when the attempt begins. `Exchanging` and `OutcomeUnknown` both wait on the provider (a token response, then reconciliation) and have no deadline, so the instance can sit there indefinitely. Each `MISSING` becomes a finding (see [finding-template.md](finding-template.md)). Cancel and Expire are not exits from `Exchanging` on purpose: once the code is sent, the exchange cannot be un-sent, so the only honest exits are a result or "outcome unknown". -After the fixes (`exchange` 30s exiting to `OutcomeUnknown`, `reconciliation` 15m exiting to `Failed` with a typed reason), the longest path is `AwaitingConsent -> CallbackClaimed -> Exchanging -> OutcomeUnknown -> Failed`, and `T_max = 10m + 30s + 15m + 3 * delta`. +After the fixes (`exchange` 30s exiting to `OutcomeUnknown`, `reconciliation` 15m exiting to `Failed` with a typed reason), the longest path is `AwaitingConsent -> CallbackClaimed -> Exchanging -> OutcomeUnknown -> Failed`, and `T_max = 10m + 30s + 15m + 3 * delta + 4 * rho` (three window armings, four transitions). ## Encoding It