diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 38847e61..1733b8b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,8 +1,14 @@ name: CI -# A draft PR runs only the gate, which fails until the PR is marked ready, so work -# under review spends no CI time. Marking it ready (ready_for_review) runs the full -# CI, as does every later push to a ready PR. +# A draft PR runs no jobs: every job, the gate included, skips while the PR is a +# draft, so work under review spends no CI time. GitHub still records a run for each +# push, with every job skipped. Marking it ready (ready_for_review) runs the full CI, +# as does every later push to a ready PR. +# +# The cost: a skipped required check counts as passing, so the draft's skipped `gate` +# reads as passed until the ready run starts, when its pending `gate` blocks a merge. +# A PR merged in the seconds between marking it ready and that run starting would +# merge without CI. We accept that window to keep drafts free of runs and red checks. on: pull_request: branches: [main] @@ -24,8 +30,8 @@ env: jobs: # Detect whether anything other than docs changed. Docs-only PRs skip the Go - # lint/test/vuln/coverage/bench jobs entirely; the `gate` job below still runs - # and is the single required status check, so such PRs stay mergeable. + # lint/test/vuln/coverage/bench jobs entirely; on a ready PR the `gate` job below + # still runs and is the single required status check, so such PRs stay mergeable. changes: if: ${{ !github.event.pull_request.draft }} runs-on: ubuntu-latest @@ -597,19 +603,12 @@ jobs: # docs) as a pass — so such PRs stay mergeable without running every matrix. # `bench` is advisory and is deliberately excluded so a benchmark regression # never blocks a merge. + # It skips on a draft, like every job here; the header says why, and what it costs. gate: - if: always() + if: ${{ always() && !github.event.pull_request.draft }} needs: [changes, lint, tests, sink, source, vuln, coverage, docs] runs-on: ubuntu-latest steps: - # On a draft every other job is skipped, and a skipped required check would - # count as passing for this commit. Fail instead, so a PR can't be marked ready - # and merged before its CI has run. - - name: Fail on a draft - if: ${{ github.event.pull_request.draft }} - run: | - echo "::error::Draft PR: CI runs when it's marked ready for review." - exit 1 - name: Fail if a required job did not pass if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }} run: | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7881c94a..56931fe7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -136,8 +136,8 @@ Run `mage -l` to list everything. Each target iterates the suite's modules. Before you push, **tests, lint, vet, and `govulncheck` must all pass.** The quickest way to verify locally is `mage check`. CI runs the same gates across a -OS matrix on every ready PR. A draft PR runs only the `gate` check, which fails until -the PR is marked ready for review; marking it ready runs the full CI. +OS matrix on every ready PR. A draft PR runs no jobs, the `gate` check included; +marking it ready for review runs the full CI. Docs-only pull requests (changing only `*.md`, `docs/`, `LICENSE`, or `NOTICE`) skip the Go matrix automatically and are gated solely by the aggregate `gate` diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index 15ea16e8..8a0c6af0 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -72,8 +72,8 @@ the first time, and replayed verbatim on recovery: | Seam | Wire with | Recorded as | | --- | --- | --- | | **Clock** (timers) | `WithRunnerClock` | `JournalClockRead`, replayed so timers fire at the same recorded instants, wall-clock-independent; armed deadlines survive checkpoint compaction | -| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; the service runs once, then recovery replays its result through the kernel's settle seam | -| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; the behavior runs once, then recovery re-fires the recorded parent transition | +| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; a recorded result replays through the kernel's settle seam without re-running the service, and an unrecorded one (a context canceled during the service or its settle, a crash, or a failed `Append` whose write didn't land) runs again when the host calls `RunService` | +| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled or stopped actor doesn't re-run; a running `InvokeActor` actor restarts from its initial state on any `Recover`, and a `Spawn` actor doesn't return | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written: a @@ -140,16 +140,20 @@ context not derived from the step's. A step waiting for the lock stops when its ends. Read the instance with `View`, which takes the lock; `Instance()` is outside it. -A step that may not have been recorded fails the Handle with `ErrHandleFailed`. So does an -effect handler that returns an error or panics. Before `Recover`, call `Handle.Drain`, -which waits until no step of the failed Handle is still recording and no effect is still -being sent, so the recovered Handle loads every recorded step and can't send an effect -twice. Give `Drain` a context of its own, not the failed call's, and don't `Recover` -until it returns nil: an error means it didn't finish draining. A step that was recording when another goroutine failed the Handle returns -`ErrHandleFailed` saying it was recorded; `Recover` sends any of its effects. To move a healthy Handle's instance to a new Handle, stop -calling the old one and let its calls return first: a step can start after `Drain` -returns. `Recover` a new Handle with the same options to continue, unless the cause is `ErrFenced`: then a newer owner holds the -instance, so stop. +A step that may not have been recorded fails the Handle with `ErrHandleFailed`. So does a +`Tick`, `RunService` or `DeliverToActor` whose context ended during the step, and any of +the four, `Fire` included, that drove a Fire refused because a context ended, the caller's +or one middleware derived from it. So does an effect handler +that returns an error or panics. Before `Recover`, call `Handle.Drain`, which waits until no +step of the failed Handle is still recording and no effect is still being sent, so the +recovered Handle loads every recorded step and can't send an effect twice. Give `Drain` a +context of its own, not the failed call's, and don't `Recover` until it returns nil: an +error means it didn't finish draining. A step that was recording when another goroutine +failed the Handle returns `ErrHandleFailed` saying it was recorded; `Recover` sends any of +its effects. To move a healthy Handle's instance to a new Handle, stop calling the old one +and let its calls return first: a step can start after `Drain` returns. `Recover` a new +Handle with the same options to continue, unless the cause is `ErrFenced`: then a newer +owner holds the instance, so stop. ## A note on serialized payloads diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 08003135..60405754 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -9,6 +9,22 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Added +- **`Record.EndedActors` and `ActorSet`** record the declared child-machine actors that + ran and have ended, settled or stopped, so `Recover` doesn't spawn them again. A Store + must keep an empty set distinct from nil. +- **`Record.UnstartedActors`** records the declared actors that aren't running and + haven't ended, because their spawn failed with no onError declared, or its + onError was refused because a context ended, so `Recover` can tell them + from the actors that were running. A Store must keep an empty set distinct from nil. +- **`Record.Format`** records the journal format of the version that wrote the Record, + which is 1 from this version. Replay arms the timers and services an actor-driven + parent Fire's state declares only for a Record of format 1 or later. + **For Store authors:** a Store must keep `Format`, `EndedActors` and + `UnstartedActors`, and keep an empty set distinct from nil. A Store that drops them, or + maps an empty set to nil as an SQL array column or a protobuf repeated field can, + makes `Recover` spawn ended actors again, and replay arm nothing for a Record without + its `Format`. MemStore and FileStore keep all three. + - **Fencing.** `WithFence` on `Store.Append` and `WithCheckpointFence` on `Store.Checkpoint` carry a caller-issued token, and a Store refuses a token lower than the highest it has seen for the instance with `ErrFenced`, writing nothing. @@ -48,7 +64,26 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Changed +- **A journal this version writes isn't for an older one.** An actor entry can now say + its parent Fire was refused, which an older `durable` fails `Recover` on, or, for an + entry with no event, replays as the zero event. An older `durable` also ignores the + recorded ended actors and spawns them again, and replays a step that records actor + entries as a delivery, skipping its event, settle or tick. It also spawns a running + actor as new, so a message the actor sent its parent as it started applies twice. Don't downgrade a Store this version has + written to. +- **A journal an older version wrote replays as it did.** Its actor entries carry no + refusal, so `Recover` still fails on one whose parent Fire was refused, and an output + recorded with a delivery's last Fire still replays into that transition. Only steps + this version records get the fixes below. - Requires Go 1.27.4. +- **`Start` fails on a context refusal.** If a context's ending (ctx's, or one + middleware derived from it) refuses a parent Fire an initial actor drove, such as a + failed spawn's onError, `Start` returns an error wrapping the context's error and no + Handle. It used to return a Handle whose state lacked that Fire, while `Recover` + would apply it. The baseline is recorded, so `Recover` the instance. A ctx that ends + with no Fire refused doesn't fail `Start`. `Recover` likewise fails when a context's + ending refuses a parent Fire its own spawns drove, rather than returning a Handle the + journal can't reach. - **A Handle's steps are serialized across goroutines.** `Fire`, `Tick`, `RunService` and `DeliverToActor` hold a lock while they apply to the kernel and record the step, so a host's timer loop no longer loses acknowledged steps. Effects dispatch after the lock @@ -107,6 +142,23 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Fixed +- **`Recover` and `StateAt` fail when a Store loses `Record.Format`.** The Start baseline + and every checkpoint record the journal format too, and a Record after one with a lower + format fails replay, where it used to replay as an older journal's and silently skip + the timers and services an actor-driven Fire armed. +- **A step that touches no actor doesn't recompute the actor sets.** Each append rebuilt + the declared actors from every active state; it now reuses the last sets while the + configuration, the running actors and the step's spawns are unchanged. +- **A running actor whose respawn fails isn't recorded as unstarted.** A failed `Recover` + respawn with no onError to catch it made the next `Recover` spawn the actor as new, so + its start message applied twice. It now stays out of both sets and respawns quietly. +- **A chained timer's deadline is the one the scheduler armed it at.** A `Tick` recorded + the deadline of a timer its fired transition chained from the tick's last clock read, + which is later than the read the scheduler armed it at. With a real clock, a checkpoint + persisted the later deadline, so after `Recover` the timer fired late, and the drift + grew along an `after` chain. `Tick` and its replay now take each chained timer's + deadline from the scheduler, with `state`'s new `Scheduler.Due`, so a fired + transition that reads the clock itself doesn't move it. - **A failed checkpoint no longer makes the next step conflict.** `Tick`, `RunService` and `DeliverToActor` now advance the next step as soon as the append lands. - **A deferred checkpoint survives an unrelated caller's cancel.** A checkpoint that @@ -116,6 +168,115 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. the step that tried it. A retry the Store refuses as not advancing means the first write landed, and counts as written. Any other checkpoint failure is returned, and after that only the next step the policy makes due tries again. +- **A Tick, RunService or DeliverToActor whose context ended partway isn't journaled.** A canceled `RunService`, `Tick` + or `DeliverToActor` used to record a result the live instance never applied, which + recovery then committed, or for an actor, failed on. Each now returns `ErrHandleFailed` + wrapping the error and records nothing. One rule covers them: a step records nothing + once its context ended by the end of the step, or a Fire it drove was refused with a + context's error, which catches a context middleware derived from the caller's. A + guard binding, action or middleware of that Fire that returns its own context error, such as + an HTTP client's timeout, counts as a context ending too. A service function's error + doesn't: a service that returns one settles through its onError, and the step + journals. + A Fire refused for another reason, such as a failing guard, is still recorded, and + replay now meets the same refusal instead of failing Recover on it. After `Recover` + the service stays in flight and must tolerate running again, the timer is re-armed, an + `InvokeActor` actor restarts from its initial state, and a `Spawn` actor doesn't + return. `Recover` and `StateAt` now fail on a context that ends before the journal is + replayed, rather than returning state short of the journal. A context that ends once + `Recover` has spawned its actors, with no parent Fire refused, doesn't fail it, as for + `Start`, since their behaviors already ran. A `DeliverToActor` whose context ended by + the end of the delivery records nothing, even when it drove no parent Fire: the + ending may have made the kernel refuse the actor's own Fire, losing the event. +- **`Fire` follows the same rule for the actors it spawns.** When an actor a Fire's + state spawned failed to start and a context's ending refused its onError, the Fire was + recorded, and `Recover` then applied the onError live never applied. Now `Fire` returns + `ErrHandleFailed` and records nothing, though its event applied: fire it again on the + recovered Handle. A Fire that drove no Fire a context refused still records, even when its + context ends once the kernel has applied the event. +- **An actor's output replays with the Fire that carried it.** When one delivery drove + several parent Fires, such as an onDone entering a state whose actor then failed to + start, the output was recorded with the last Fire, so replay gave it to the wrong + transition. It's recorded with the settling Fire, which `state`'s new + `ActorSystem.WithParentFireObserver` identifies. +- **`Recover` doesn't spawn an actor the live run had ended.** It spawned every actor + the recovered state declared, so an actor that had settled or been stopped while its + parent stayed in that state ran again: a settle the parent refused, one that applied + without leaving the state, or an explicit stop. Each step now records the declared + actors that ran and ended, in the new `Record.EndedActors`, and a checkpoint keeps the + set, so `Recover` spawns the declared actors that aren't in it. An actor whose spawn + failed with no onError declared never ran, so `Recover` tries it again, as before, + and so does one whose onError a context's ending refused, since the step that drove + it records nothing; one whose onError applied counts as ended, since the journal + holds that onError, and, from the refused-onError fix below, so does one whose + onError was refused for another reason replay meets again. A journal from before this + records no set, and `Recover` spawns every declared actor, as before. +- **A failed spawn's onError, and a settle an absorb drove, are journaled.** When an + actor a `Fire`, `RunService`, `Start` or `Recover` spawned couldn't start and its + onError applied, nothing recorded the onError, so `Recover` either applied it again + by retrying the spawn, or, once the spawn worked, never applied it. Likewise a settle + a Fire's effects drove, such as one from a `SendTo` to a running actor, wasn't + recorded, so `Recover` lost it. These are now recorded with their step, or, for + `Start`'s and `Recover`'s spawns, with the step after, and replay re-fires each where + it ran. An actor output that has no JSON form now fails the Handle here too, as it + does for a delivery. +- **A spawn whose onError was refused deterministically isn't retried.** A failed + spawn counted as handled only when its onError Fire applied, so one whose onError + was refused for a reason other than a context ending — a guard returning false — + landed in `UnstartedActors`, and every `Recover` spawned it again: the behavior, + and any side effect it ran, re-executed each time, and each recovery journaled + another refused onError. Such a refusal now counts as handled — the journal + already records it, and replay meets it again — so the actor counts as ended and + `Recover` leaves it alone. A spawn whose onError a context's ending refused still + retries, since the step that drove it records nothing, as does one with no onError + declared, as before. An invoked actor with no onError fires the zero event, which the + parent refuses as having no transition, and `durable` reads that refusal + (`state.ErrNoTransition`) as "none declared". So a declared onError the parent has no + transition for retries too, and a wildcard or a transition that takes the zero event + counts as caught; #250 tracks a better way to tell them apart. A host refusal worded + like the kernel's counts as handled. +- **A message an actor sends its parent as it spawns applies once.** A `Fire`, + `RunService`, `Start` or `Recover` didn't journal it, and `Recover` spawned the actor + again to send it again: it landed after the steps that followed it live, or never, if + it had ended the actor. A delivery did journal it, for an actor its onDone or onError + spawned, so `Recover` applied it twice. Every step now journals every parent Fire it + drove, and `Start`'s and `Recover`'s go with the step after, so replay re-fires each + where it ran. `Recover` spawns an actor that was running with `state`'s new + `ActorSystem.AbsorbRespawn`, which keeps such messages from the parent, and the onDone + or onError of a nested actor its start spawns, which the journal holds too. An actor whose + spawn failed with no onError never ran, so its messages are new: they reach the parent + and are journaled with the next step. A journal from before this records no unstarted + actors, and `Recover` spawns every actor as new, as before. +- **A state an actor's onDone, onError or message enters runs its timers and services.** + The actor system armed only that state's actors, so its service wasn't in flight, and + `RunService` reported none, and its timer never fired; a checkpoint then recorded the + service as settled, so `Recover` didn't start it either. Such a Fire now arms them, + live, at `Start` and `Recover`, and on replay, as a host `Fire` does. Replay arms them + only for a Record this version wrote, which records its `Format`: an older version + took no clock read for them, and its Records replay as they did. A service's + settle re-arms its state's timers on replay too, and `DeliverToActor` and `RunService` + now journal the clock reads their step took, so a checkpoint on that step can't leave + a read for the next to replay. `Recover` re-arms a checkpoint's timers before it + spawns the running actors, so a Fire one of theirs drives can cancel one. A `Tick` + drops from the timers a checkpoint records exactly the ones it fired, live and on + replay: one that came due between its clock reads, and a chained one it armed and + fired, used to stay, so a `Recover` from a later checkpoint fired it again. +- **A delivery journals each parent Fire under the actor that drove it,** where it used to + record every one under the actor delivered to. It no longer copies the instance's + history twice per delivery to do it. +- **`Recover` doesn't start a service that settled while its state stayed active.** A + checkpoint taken after such a settle, on a state that stayed put, left the service in flight again on recovery, so + `RunService` ran it a second time. A checkpoint now records the declared services that + settled while their state stayed active, and `Recover` doesn't start them. One that + never settled, such as one whose state a `Tick` entered or re-entered (a `Tick` + starts no service), isn't recorded, so `Recover` starts it, as before. A checkpoint + from before this records none, and `Recover` starts every declared service. +- **A parent Fire that middleware denied replays.** Denied before the kernel saw it, it + is recorded as refused, and replay meets the same refusal instead of failing `Recover`. +- **A panic during a step fails the Handle.** A panic in host code under the step lock, + such as an actor behavior a Fire's absorb started, left the Handle healthy but ahead of + its journal, so the next step recorded on top of state the journal never held and + `Recover` failed. The Handle now fails first, and the panic goes on to the caller. - **The next step survives a checkpoint that compacts tick barriers.** A checkpoint now records the step that follows it, in a `nextStep` field of its envelope. Recovery used the Trace count, which runs low past a tick barrier, so the next Fire could reuse a @@ -124,7 +285,8 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. with `ErrStepConflict`, and an identical one is acknowledged without a new Record. - **`WithEventData` survives recovery.** `Handle.Fire` records the payload in the new `Record.EventData` and `Record.EventDataError`, and `Recover` and `StateAt` supply it - on replay. This needs `state.FireEventData`, so `durable` requires `state` v1.1.0 or + on replay. This needs `state.FireEventData` (and the observer above needs + `state.ActorSystem.WithParentFireObserver`), so `durable` requires `state` v1.1.0 or later, and its `require` must move there before a `durable` tag. - **Recording-clock buffer race.** Closing a step's `Record` (draining the recording clock) and the clock-read index reads used to mirror timer deadlines diff --git a/durable/README.md b/durable/README.md index 4f113340..643d40cc 100644 --- a/durable/README.md +++ b/durable/README.md @@ -82,8 +82,8 @@ the first time, and replayed verbatim on recovery: | Seam | Wire with | Recorded as | | --- | --- | --- | | **Clock** (timers) | `WithRunnerClock` | `JournalClockRead`, replayed so timers fire at the same recorded instants, wall-clock-independent; armed deadlines survive checkpoint compaction | -| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; the service runs once, then recovery replays its result through the kernel's settle seam | -| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; the behavior runs once, then recovery re-fires the recorded parent transition | +| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; a recorded result replays through the kernel's settle seam without re-running the service, and an unrecorded one (a context canceled during the service or its settle, a crash, or a failed `Append` whose write didn't land) runs again when the host calls `RunService` | +| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled or stopped actor doesn't re-run; a running `InvokeActor` actor restarts from its initial state on any `Recover`, and a `Spawn` actor doesn't return | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written (a @@ -151,16 +151,20 @@ context not derived from the step's. A step waiting for the lock stops when its ends. Read the instance with `View`, which takes the lock; `Instance()` is outside it. -A step that may not have been recorded fails the Handle with `ErrHandleFailed`. So does an -effect handler that returns an error or panics. Before `Recover`, call `Handle.Drain`, -which waits until no step of the failed Handle is still recording and no effect is still -being sent, so the recovered Handle loads every recorded step and can't send an effect -twice. Give `Drain` a context of its own, not the failed call's, and don't `Recover` -until it returns nil: an error means it didn't finish draining. A step that was recording when another goroutine failed the Handle returns -`ErrHandleFailed` saying it was recorded; `Recover` sends any of its effects. To move a healthy Handle's instance to a new Handle, stop -calling the old one and let its calls return first: a step can start after `Drain` -returns. `Recover` a new Handle with the same options to continue, unless the cause is `ErrFenced`: then a newer owner holds the -instance, so stop. +A step that may not have been recorded fails the Handle with `ErrHandleFailed`. So does a +`Tick`, `RunService` or `DeliverToActor` whose context ended during the step, and any of +the four, `Fire` included, that drove a Fire refused because a context ended, the caller's +or one middleware derived from it. So does an effect handler +that returns an error or panics. Before `Recover`, call `Handle.Drain`, which waits until no +step of the failed Handle is still recording and no effect is still being sent, so the +recovered Handle loads every recorded step and can't send an effect twice. Give `Drain` a +context of its own, not the failed call's, and don't `Recover` until it returns nil: an +error means it didn't finish draining. A step that was recording when another goroutine +failed the Handle returns `ErrHandleFailed` saying it was recorded; `Recover` sends any of +its effects. To move a healthy Handle's instance to a new Handle, stop calling the old one +and let its calls return first: a step can start after `Drain` returns. `Recover` a new +Handle with the same options to continue, unless the cause is `ErrFenced`: then a newer +owner holds the instance, so stop. ## Caveat: serialized payloads diff --git a/durable/actor.go b/durable/actor.go index 496a2878..03ffcc87 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -17,15 +17,15 @@ import ( // NOT a pure function of (configuration, context, event payload, machine // definition) and MUST be recorded to reproduce a run. // -// # Run exactly once, replay the result +// # Run once per recorded result, replay the result // -// A durable actor's behavior runs exactly once, on the live path, and the result -// it routes into the parent is recorded; on recovery the recorded result is -// replayed back through the SAME parent transition the live run drove, and the -// actor behavior is NEVER re-instantiated. This is the standard durable-execution -// guarantee: the child machine (with its side effects and its nondeterministic -// output) runs once, and recovery is a pure replay against the parent kernel rather -// than a re-execution of the actor tree. +// A durable actor's behavior runs on the live path and the result it routes into the +// parent is recorded; on recovery the recorded result is replayed back through the SAME +// parent transition the live run drove, so a settled actor never re-runs. This is the +// standard durable-execution guarantee: recovery is a pure replay against the parent +// kernel rather than a re-execution of the actor tree. An InvokeActor actor still running +// at recovery restarts from its initial state, because its own state isn't journaled, and +// a Spawn actor doesn't return. // // The Runner wraps the kernel's reusable host driver, state.ActorSystem, which // turns SpawnActor / StopActor effects into running child actors, owns each actor's @@ -88,32 +88,45 @@ type actorMessagePayload struct { // it; a message-driven fire (SendParent) leaves it false so replay re-fires the // parent plainly, letting the event itself supply the assign's data. HasData bool `json:"hasData,omitempty"` + // Refused reports that the live parent Fire was refused (a guard failed, no + // transition matched, ...), so replay expects the same refusal instead of failing + // on it. A refusal because a context ended is never recorded: that step fails the + // Handle instead. + Refused bool `json:"refused,omitempty"` + // Before reports a parent Fire that ran before the step's own work: one a spawn at + // Start or Recover drove, recorded with the step that followed. Replay re-fires it + // first. + Before bool `json:"before,omitempty"` } -// DeliverToActor routes event into the running actor identified by ref exactly -// once, runs the actor (settling it when it reaches its final state), records each -// parent transition the delivery drove, and persists the produced step. The actor +// DeliverToActor routes event into the running actor identified by ref, runs the +// actor (settling it when it reaches its final state), records each parent +// transition the delivery drove, and persists the produced step. The actor // behavior is resolved and run against the palette supplied with WithActorPalette; // the done-data, error, or parent-driving message it routes is journaled as a // JournalActorMessage correlated by the actor id so recovery replays it without // re-instantiating the actor. // -// It returns false for a ref that names no live actor (already settled, stopped, or -// never spawned), and false with the error when the Handle had already failed or ctx -// has ended. If the actor received the event but the delivery couldn't be recorded or -// appended, it returns true and ErrHandleFailed: the Handle has failed. If another -// goroutine failed the Handle while this step was recording, it returns true and -// ErrHandleFailed saying the step was recorded. A failed checkpoint returns true and -// that error, and the Handle carries on. The kernel -// transitions the delivery drove do not themselves fail. When a delivery wasn't -// recorded, on a recovered Handle an InvokeActor actor restarts from its initial state, -// and a Spawn actor doesn't return. Resending a recorded delivery repeats -// any message it sends the parent. +// It returns whether the actor was found running: false for a ref that names no live +// actor (already settled, stopped, or never spawned), or false and an error when no +// palette is wired, the Handle has failed, or ctx ended before the delivery. Once the +// actor ran it returns true with any error. A result that won't encode, a ctx that ended +// by the end of the delivery, or a parent Fire refused because a context ended (ctx, or +// one middleware derived from it) returns ErrHandleFailed and records nothing: a ctx +// that ended before the actor handled the event made the kernel refuse the actor's own +// Fire, and the event was lost. On a +// recovered Handle an InvokeActor actor restarts from its initial state, and a Spawn +// actor doesn't return. A failed Append also returns ErrHandleFailed, but the write may +// have landed anyway, and Recover finds out which. If another goroutine failed the Handle while this step was +// recording, it returns true and ErrHandleFailed saying the step was recorded. A failed +// Checkpoint returns the plain error, and the delivery is recorded. Resending a recorded +// delivery repeats any message it sends the parent. func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef, event any) (bool, error) { if err := h.acquire(ctx); err != nil { return false, err } defer h.release() + defer h.failOnPanic() if err := h.refuse(ctx); err != nil { return false, err } @@ -121,23 +134,33 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef return false, fmt.Errorf("durable: no actor palette wired for %q (supply WithActorPalette)", h.id) } - before := len(h.inst.History()) - delivered := h.actors.Deliver(h.stepContext(ctx), ref, event) + stepCtx := h.stepContext(ctx) + // Restore in a defer, so a panic out of host code doesn't leave the collector driving + // under this step's context. + delivered := func() bool { + defer h.actorFires.driving(stepCtx)() + return h.actors.Deliver(stepCtx, ref, event) + }() + fires := h.actorFires.take() if !delivered { return false, nil } + // A context that ended during the delivery can make the kernel refuse the actor's + // own Fire, losing the event, or a parent Fire it drove. A refused Fire rolls back, + // so live never applied it, but journaling the delivery would replay it under a live + // context, where it applies. Record nothing. + if err := stepCanceled(ctx, parentFireErrs(fires)...); err != nil { + return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) + } - output, settled, settleErr := h.actorOutcome() - entries, err := recordActorTransitions(ref.ID, h.inst.History(), before, output, settled, settleErr) + entries, err := recordParentFires(fires, false) if err != nil { return true, h.fail(fmt.Errorf("durable: recording actor %q result for %q: %w", ref.ID, h.id, err)) } - if h.actorBuf != nil { - *h.actorBuf = append(*h.actorBuf, entries...) - } step := h.nextStep - rec := Record{Step: step, Entries: h.drainActors()} + // A parent Fire the delivery drove can arm a timer, which reads the clock. + rec := Record{Step: step, Entries: append(h.drainClock(), entries...)} if err := h.persistStep(ctx, step, &rec); err != nil { return true, err } @@ -161,80 +184,72 @@ func (h *Handle[S, E, C]) ActorRef(id string) (state.ActorRef, bool) { return h.actors.Ref(id) } -// actorOutcome reads the most recently settled actor's output / error from the -// underlying ActorSystem, the outcome the settling parent fire carried. It reports -// whether a settlement occurred at all (so a delivery that only sent a message and -// did not complete the actor records no settle data). -func (h *Handle[S, E, C]) actorOutcome() (output any, settled bool, settleErr error) { - if h.actors == nil { - return nil, false, nil +// recordParentFires builds the JournalActorMessage entries for the parent Fires an +// actor system drove, in fire order, each under the actor it came from. before marks +// Fires that ran before the step's own work. +func recordParentFires[S comparable](fires []state.ParentFire[S], before bool) ([]state.JournalEntry, error) { + entries := make([]state.JournalEntry, 0, len(fires)) + for _, pf := range fires { + entry, err := actorEntry(pf, before) + if err != nil { + return nil, err + } + entries = append(entries, entry) } - if err := h.actors.LastError(); err != nil { - return nil, true, err + return entries, nil +} + +// actorEntry builds one JournalActorMessage entry: the parent Fire's event payload, +// whether the live Fire was refused, and, for a Fire that settled an actor, the +// actor's outcome, which it passed as event data, so replay re-fires the same onDone +// or onError with it. +func actorEntry[S comparable](pf state.ParentFire[S], before bool) (state.JournalEntry, error) { + var mp actorMessagePayload + mp.Event = append(json.RawMessage(nil), pf.Result.Trace.EventPayload...) + mp.Refused = pf.Result.Err != nil + mp.Before = before + if pf.Settle { + mp.HasData = true + switch { + case pf.Err != nil: + msg := pf.Err.Error() + mp.Error = &msg + case pf.Output != nil: + raw, err := json.Marshal(pf.Output) + if err != nil { + return state.JournalEntry{}, fmt.Errorf("marshaling actor output: %w", err) + } + mp.Data = raw + } } - if out, ok := h.actors.LastOutput(); ok { - return out, true, nil + payload, err := json.Marshal(mp) + if err != nil { + return state.JournalEntry{}, fmt.Errorf("marshaling actor transition: %w", err) } - return nil, false, nil + return state.JournalEntry{Kind: state.JournalActorMessage, CorrelationID: pf.ActorID, Payload: payload}, nil } -// drainActors returns and clears the actor transitions recorded since the last -// drain, so each persisted step carries exactly the transitions that resolved -// during it, in fire order. -func (h *Handle[S, E, C]) drainActors() []state.JournalEntry { - if h.actorBuf == nil || len(*h.actorBuf) == 0 { - return nil - } - out := make([]state.JournalEntry, len(*h.actorBuf)) - copy(out, *h.actorBuf) - *h.actorBuf = (*h.actorBuf)[:0] - return out +// decodedActorEntry is a recorded actor entry with its payload decoded once. +type decodedActorEntry struct { + actorID string + mp actorMessagePayload } -// recordActorTransitions builds the JournalActorMessage entries for the parent -// Traces the just-completed delivery appended (those at index before..len). Each -// new Trace is one parent transition the actor system drove; the entry carries that -// transition's event payload. When the actor settled (output or error present), the -// settling onDone / onError fire is the LAST of those Traces — a SendParent message -// fires the parent before the actor drains and completes — so the outcome is -// attributed to the last entry, which records HasData; earlier entries are -// message-driven and carry no separate payload. -func recordActorTransitions(id string, history []state.Trace, before int, output any, settled bool, settleErr error) ([]state.JournalEntry, error) { - if before >= len(history) { - return nil, nil - } - traces := history[before:] - entries := make([]state.JournalEntry, 0, len(traces)) - for i, tr := range traces { - var mp actorMessagePayload - mp.Event = append(json.RawMessage(nil), tr.EventPayload...) - // Attribute the actor outcome to the settling fire — the last parent Trace — - // so the onDone / onError transition replays with the recorded done-data / - // error, while a message-driven fire that preceded it replays plainly. - if settled && i == len(traces)-1 { - mp.HasData = true - if settleErr != nil { - msg := settleErr.Error() - mp.Error = &msg - } else if output != nil { - raw, err := json.Marshal(output) - if err != nil { - return nil, fmt.Errorf("marshaling actor output: %w", err) - } - mp.Data = raw - } +// splitActorEntries decodes a Record's actor entries, in recorded order, and returns the +// ones that ran before the step's own work apart from the rest. +func splitActorEntries(rec *Record) (before, rest []decodedActorEntry, err error) { + for _, e := range actorEntries(rec) { + d := decodedActorEntry{actorID: e.CorrelationID} + if err := json.Unmarshal(e.Payload, &d.mp); err != nil { + return nil, nil, fmt.Errorf("durable: decoding recorded actor %q transition: %w", e.CorrelationID, err) } - payload, err := json.Marshal(mp) - if err != nil { - return nil, fmt.Errorf("marshaling actor transition: %w", err) + if d.mp.Before { + before = append(before, d) + } else { + rest = append(rest, d) } - entries = append(entries, state.JournalEntry{ - Kind: state.JournalActorMessage, - CorrelationID: id, - Payload: payload, - }) } - return entries, nil + return before, rest, nil } // replayActor re-fires one recorded parent transition directly through the @@ -242,31 +257,42 @@ func recordActorTransitions(id string, history []state.Trace, before int, output // re-fires the parent's event — carrying the recorded done-data / error via // WithEventData for a settling fire, or plainly for a message-driven fire — so the // kernel re-derives the same parent transition with the same data, running no actor -// behavior. It reports an error only when the recorded entry cannot be decoded or -// the re-fired transition fails (a corrupt or mis-ordered journal). -func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry state.JournalEntry) error { - var mp actorMessagePayload - if err := json.Unmarshal(entry.Payload, &mp); err != nil { - return fmt.Errorf("durable: decoding recorded actor %q transition: %w", entry.CorrelationID, err) +// behavior. It returns the effects of a re-fired transition that applied, so the caller +// arms the timers and services it declares, as the live run did. It reports an error +// only when the recorded entry cannot be decoded or the re-fired transition fails (a +// corrupt or mis-ordered journal). +func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry decodedActorEntry) ([]state.Effect, error) { + mp := entry.mp + // A Fire refused before the kernel saw it (middleware that denied it) has no event + // to re-fire; replay is refused the same way. + if mp.Refused && len(mp.Event) == 0 { + return nil, nil } event, err := codec.Decode(mp.Event) if err != nil { - return fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.CorrelationID, err) + return nil, fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.actorID, err) } var res state.FireResult[S] if mp.HasData { data, derr := replayActorData(mp) if derr != nil { - return fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.CorrelationID, derr) + return nil, fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.actorID, derr) } res = inst.Fire(ctx, event, state.WithEventData(data)) } else { res = inst.Fire(ctx, event) } - if res.Err != nil { - return fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, res.Err) + // The kernel reports every refusal with an error, so the error alone says whether + // replay was refused, as it said for the live Fire. + switch { + case res.Err != nil && mp.Refused: + return nil, nil // the live run was refused the same way + case res.Err != nil: + return nil, fmt.Errorf("durable: replaying actor %q transition: %w", entry.actorID, res.Err) + case mp.Refused: + return nil, fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.actorID) } - return nil + return res.Effects, nil } // replayActorData reconstructs the actor outcome a settling fire carried into the @@ -301,15 +327,3 @@ func actorEntries(rec *Record) []state.JournalEntry { } return out } - -// hasActorEntry reports whether a Record carries any recorded actor transition, so -// replay can route it to the actor re-fire path rather than re-firing an external -// event. -func hasActorEntry(rec *Record) bool { - for _, e := range rec.Entries { - if e.Kind == state.JournalActorMessage { - return true - } - } - return false -} diff --git a/durable/actor_driven_drivers_test.go b/durable/actor_driven_drivers_test.go new file mode 100644 index 00000000..0942bf7e --- /dev/null +++ b/durable/actor_driven_drivers_test.go @@ -0,0 +1,445 @@ +package durable_test + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestActorDrivenFire_ArmsServicesAndTimers proves a state that an actor-driven parent +// Fire enters, by the onDone a delivery settles or by the message an actor sends as Start +// spawns it, has its service in flight and its timer armed, live and on Recover, with and +// without checkpoints: RunService runs the service and a Tick at the deadline fires the +// timer, as for a state a Fire enters. So does one a service's settle enters. Recover +// runs at the deadline, and a checkpoint lands on the step that enters armed, so a clock +// read that step left to the next would move the deadline. +func TestActorDrivenFire_ArmsServicesAndTimers(t *testing.T) { + ctx := context.Background() + m := armedMachine() + svcID := state.InvokeID("armed", "armed", 0) + for _, by := range []string{"delivery", "Start", "RunService"} { + for _, where := range []string{"live", "Recover", "Recover/every=2"} { + for _, check := range []string{"service", "timer"} { + t.Run(fmt.Sprintf("%s/%s/%s", by, where, check), func(t *testing.T) { + clk := state.NewFakeClock(epoch) + opts := armedOptions(clk, true) + if where == "Recover/every=2" { + // The checkpoint lands on the step that enters armed, so the tail + // holds only the poke after it. + opts = append(opts, durable.WithCheckpointEvery[string, string, actorCtx](2)) + } + store, id := durable.NewMemStore(), durable.InstanceID("armed") + initial := map[string]string{"delivery": "working", "Start": "going", "RunService": "loading"}[by] + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("first Fire(poke): %v", err) + } + switch by { + case "delivery": + if found, deliverErr := h.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("armed", "working", 0)}, "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActor = %v, %v", found, deliverErr) + } + case "RunService": + if _, ran, runErr := h.RunService(ctx, state.InvokeID("armed", "loading", 0)); !ran || runErr != nil { + t.Fatalf("RunService(loading) = %v, %v", ran, runErr) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if check == "timer" { + clk.Advance(10 * time.Second) + } + if where != "live" { + if h, err = durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + } + want := "fetched" + switch check { + case "service": + if _, ran, runErr := h.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v, want it to run the service the state invokes", ran, runErr) + } + case "timer": + want = "timedOut" + if _, tickErr := h.Tick(ctx); tickErr != nil { + t.Fatalf("Tick: %v", tickErr) + } + } + if got := h.Instance().Current(); got != want { + t.Fatalf("state = %q, want %q", got, want) + } + }) + } + } + } +} + +// armedMachine enters "armed", which invokes a service and arms a 10s timer, by the +// onDone of the finisher "working" runs, by the "go" the goer "going" runs sends as it +// starts, or by the onDone of the service "loading" invokes. +func armedMachine() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("armed"). + Service("fetch", fetchOK). + Actor("finisher"). + Actor("goer"). + State("working").InvokeActor("finisher", state.WithInvokeOnDone("childDone")). + State("going").InvokeActor("goer"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("loaded")). + State("armed").Invoke("fetch", state.WithInvokeOnDone("fetched")). + State("fetched"). + State("timedOut"). + Initial("working"). + Transition("working").On("childDone").GoTo("armed"). + Transition("working").On("poke").GoTo("working"). + Transition("loading").On("poke").GoTo("loading"). + Transition("going").On("go").GoTo("armed"). + Transition("loading").On("loaded").GoTo("armed"). + Transition("armed").On("poke").GoTo("armed"). + Transition("armed").On("fetched").GoTo("fetched"). + Transition("armed").After(10 * time.Second).On("elapsed").GoTo("timedOut"). + Quench() +} + +// armedOptions wires clk, the fetch service, and the finisher and goer, with a goer that +// can't start unless goerStarts. +func armedOptions(clk state.Clock, goerStarts bool) []greetOption { + goer := failingSpawn(nil) + if goerStarts { + goer = func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "go"}, nil } + } + return []greetOption{ + durable.WithRunnerClock[string, string, actorCtx](clk), + durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("fetch", fetchOK)), + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "finisher": finishingChild(), + "goer": goer, + }), + } +} + +// TestRecover_ASpawnsFireArmsATimerAtItsRead proves a timer a parent Fire arms when +// Recover's retried spawn drives it, here the go of a goer that couldn't start live, is +// due 10s after the clock read Recover took, and that the next step journals that read: +// a later Recover, its clock 5s past that read, replays the Fire's arming at it, so the +// timer comes due 5s on, and the service the state invokes is in flight. +func TestRecover_ASpawnsFireArmsATimerAtItsRead(t *testing.T) { + ctx := context.Background() + m := armedMachine() + clk := state.NewFakeClock(epoch) + store, id := durable.NewMemStore(), durable.InstanceID("retried") + if _, err := durable.NewRunner(m, store, armedOptions(clk, false)...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")); err != nil { + t.Fatalf("Start: %v", err) + } + clk.Advance(time.Hour) + h, err := durable.Recover(ctx, m, store, id, armedOptions(clk, true)...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := h.Instance().Current(); got != "armed" { + t.Fatalf("Recover left %q, want armed by the retried goer's go", got) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + clk.Advance(5 * time.Second) + again, err := durable.Recover(ctx, m, store, id, armedOptions(clk, true)...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + clk.Advance(5 * time.Second) + if _, err = again.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := again.Instance().Current(); got != "timedOut" { + t.Fatalf("state = %q, want timedOut 10s after the first Recover's read", got) + } +} + +// TestTick_DropsTheTimerItFiredPastAStartsRead proves a Tick reconciles the Handle's +// timer table at its own clock read, not at an earlier read the step also records, here +// the one Start took arming the timer a starting actor's go entered. The timer's +// transition stays in its state, so no cancel drops it: the tick must, or the checkpoint +// holds it and a recovered Handle fires it again. +func TestTick_DropsTheTimerItFiredPastAStartsRead(t *testing.T) { + ctx := context.Background() + m := tickingMachine() + clk := state.NewFakeClock(epoch) + opts := append(armedOptions(clk, true), durable.WithCheckpointEvery[string, string, actorCtx](1)) + store, id := durable.NewMemStore(), durable.InstanceID("tick") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")) + if err != nil { + t.Fatalf("Start: %v", err) + } + clk.Advance(10 * time.Second) + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v, want the timer to fire", len(results), tickErr) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if results, tickErr := recovered.Tick(ctx); tickErr != nil || len(results) != 0 { + t.Fatalf("recovered Tick = %d results, %v, want none: the timer already fired", len(results), tickErr) + } +} + +// tickingMachine enters "ticking" by the go the goer "going" runs sends as it starts. +// Its 10s timer's transition stays in "ticking", so nothing cancels the timer. +func tickingMachine() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("tick"). + Actor("goer"). + State("going").InvokeActor("goer"). + State("ticking"). + Initial("going"). + Transition("going").On("go").GoTo("ticking"). + Transition("ticking").After(10 * time.Second).On("elapsed").GoTo("ticking"). + Transition("ticking").On("poke").GoTo("ticking"). + Quench() +} + +// TestRecover_DropsTheTimerAReplayedTickFired proves Recover's replay of a tick drops the +// timer it fired from the recovered Handle's timer table at the tick's own clock read, +// not at the earlier read Start took arming it, which the tick's step also records: a +// checkpoint the recovered Handle takes doesn't hold the timer, so a Recover from it +// doesn't fire it again. +func TestRecover_DropsTheTimerAReplayedTickFired(t *testing.T) { + ctx := context.Background() + m := tickingMachine() + clk := state.NewFakeClock(epoch) + store, id := durable.NewMemStore(), durable.InstanceID("replayedTick") + h, err := durable.NewRunner(m, store, armedOptions(clk, true)...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")) + if err != nil { + t.Fatalf("Start: %v", err) + } + clk.Advance(10 * time.Second) + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v, want the timer to fire", len(results), tickErr) + } + checkpointing := append(armedOptions(clk, true), durable.WithCheckpointEvery[string, string, actorCtx](1)) + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the checkpoint: %v", err) + } + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 0 { + t.Fatalf("Tick = %d results, %v, want none: the timer already fired", len(results), tickErr) + } +} + +// TestRecover_KeepsAReplayedActorFiresTimerDeadline proves the deadline of a timer that +// replay arms for an actor-driven parent Fire, here the go a goer sent as Start spawned +// it, is the one the live run armed: a checkpoint the recovered Handle takes persists +// it, so a Recover from that checkpoint fires the timer at its deadline, not before. +func TestRecover_KeepsAReplayedActorFiresTimerDeadline(t *testing.T) { + ctx := context.Background() + m := armedMachine() + clk := state.NewFakeClock(epoch) + store, id := durable.NewMemStore(), durable.InstanceID("deadline") + h, err := durable.NewRunner(m, store, armedOptions(clk, true)...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + clk.Advance(5 * time.Second) + checkpointing := append(armedOptions(clk, true), durable.WithCheckpointEvery[string, string, actorCtx](1)) + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the checkpoint: %v", err) + } + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 0 { + t.Fatalf("Tick 5s before the deadline = %d results, %v, want none", len(results), tickErr) + } + clk.Advance(5 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick at the deadline: %v", err) + } + if got := h.Instance().Current(); got != "timedOut" { + t.Fatalf("state = %q, want timedOut at the deadline", got) + } +} + +// TestRecover_StartsAServiceAnActorsMessageReentered proves a service that settled, then +// started again because an actor's message re-entered its state, is recorded as in +// flight, not settled, so Recover starts it: by a checkpoint the live run took, and by +// one a recovered Handle took after replaying the run. +func TestRecover_StartsAServiceAnActorsMessageReentered(t *testing.T) { + t.Skip("Start and Recover start only the active leaves' services and actors, not a compound state's; #249") + ctx := context.Background() + m := state.ForgeFor[actorCtx]("relay"). + Service("fetch", fetchOK). + Actor("pinger"). + SuperState("outer").InvokeActor("pinger"). + SubState("fetching").Invoke("fetch", state.WithInvokeOnDone("fetched")). + Initial("fetching"). + EndSuperState(). + Initial("outer"). + Transition("fetching").On("fetched").GoTo("fetching"). + Transition("fetching").On("pong").GoTo("fetching").Reenter(). + Transition("fetching").On("poke").GoTo("fetching"). + Quench() + svcID := state.InvokeID("relay", "fetching", 0) + for _, where := range []string{"live checkpoint", "replayed checkpoint"} { + t.Run(where, func(t *testing.T) { + var msgs int64 + opts := []greetOption{ + durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("fetch", fetchOK)), + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{"pinger": pingerChild(&msgs)}), + } + checkpointing := append(opts[:len(opts):len(opts)], durable.WithCheckpointEvery[string, string, actorCtx](1)) + live := checkpointing + if where == "replayed checkpoint" { + live = opts + } + store, id := durable.NewMemStore(), durable.InstanceID("relay") + h, err := durable.NewRunner(m, store, live...).Start(ctx, id, actorCtx{}, state.WithInitialState("fetching")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, ran, runErr := h.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v", ran, runErr) + } + if found, deliverErr := h.DeliverToActorByID(ctx, state.ActorID("relay", "outer", 0), "ping"); !found || deliverErr != nil { + t.Fatalf("DeliverToActorByID = %v, %v", found, deliverErr) + } + if where == "replayed checkpoint" { + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the journal: %v", err) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, checkpointing...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, runErr := recovered.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService after Recover = %v, %v, want the service the pong restarted in flight", ran, runErr) + } + }) + } +} + +// TestRecover_ReplaysAnOlderJournalsActorFireWithoutArming proves a journal an older +// version wrote, which didn't arm the timers an actor-driven parent Fire's state +// declares and took no clock read for them, replays as it did, in Recover and in +// StateAt: the Fire arms nothing, so it doesn't take the read a later step recorded, +// and the timer that step armed comes due at its recorded deadline, when a recorded +// Tick fires it. The journal is this version's, put back in the older shape: no clock +// read for the onDone's timer, and no recorded actor sets. +func TestRecover_ReplaysAnOlderJournalsActorFireWithoutArming(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[actorCtx]("older"). + Actor("finisher"). + State("working").InvokeActor("finisher", state.WithInvokeOnDone("childDone")). + State("armed"). + State("waiting"). + State("timedOut"). + State("late"). + Initial("working"). + Transition("working").On("childDone").GoTo("armed"). + Transition("armed").After(10 * time.Second).On("elapsed").GoTo("timedOut"). + Transition("armed").On("leave").GoTo("waiting"). + Transition("waiting").After(30 * time.Second).On("overdue").GoTo("late"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []greetOption{ + durable.WithRunnerClock[string, string, actorCtx](clk), + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{"finisher": finishingChild()}), + } + written, id := durable.NewMemStore(), durable.InstanceID("older") + h, err := durable.NewRunner(m, written, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if found, deliverErr := h.DeliverToActorByID(ctx, state.ActorID("older", "working", 0), "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActorByID = %v, %v", found, deliverErr) + } + clk.Advance(5 * time.Second) + if _, err = h.Fire(ctx, "leave"); err != nil { + t.Fatalf("Fire(leave): %v", err) + } + clk.Advance(30 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := h.Instance().Current(); got != "late" { + t.Fatalf("live state = %q, want late", got) + } + + baseline, tail, err := written.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(tail) != 3 { + t.Fatalf("journal holds %d Records, want the delivery, the leave and the tick", len(tail)) + } + older := durable.NewMemStore() + // An older version's baseline records no journal format. + var env map[string]json.RawMessage + if err = json.Unmarshal(baseline, &env); err != nil { + t.Fatalf("decoding the baseline: %v", err) + } + delete(env, "format") + if baseline, err = json.Marshal(env); err != nil { + t.Fatalf("encoding the baseline: %v", err) + } + if err = older.Checkpoint(ctx, id, baseline, durable.BaselineStep); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + for i, rec := range tail { + rec.EndedActors, rec.UnstartedActors, rec.Format = nil, nil, 0 + if i == 0 { + // The older version armed nothing for the onDone, so took no read. + var entries []state.JournalEntry + for _, e := range rec.Entries { + if e.Kind != state.JournalClockRead { + entries = append(entries, e) + } + } + if len(entries) == len(rec.Entries) { + t.Fatal("the delivery recorded no clock read for the onDone's timer") + } + rec.Entries = entries + } + if _, err = older.Append(ctx, id, rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + + view, err := durable.StateAt(ctx, m, older, id, tail[2].Step+tail[2].TickSteps, opts...) + if err != nil { + t.Fatalf("StateAt: %v", err) + } + if got := view.Instance().Current(); got != "late" { + t.Fatalf("StateAt state = %q, want late: the recorded Tick should fire waiting's timer", got) + } + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "late" { + t.Fatalf("recovered state = %q, want late: the recorded Tick should fire waiting's timer", got) + } +} diff --git a/durable/actor_fire_effects_test.go b/durable/actor_fire_effects_test.go new file mode 100644 index 00000000..d9e4612b --- /dev/null +++ b/durable/actor_fire_effects_test.go @@ -0,0 +1,47 @@ +package durable_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestFire_DispatchesTheEffectsOfAParentFireAnActorDrove pins that a domain effect a +// parent Fire emits, where an actor drove that Fire, is dispatched like the event +// Fire's own: here a failed spawn's onError transition emits a notify. +func TestFire_DispatchesTheEffectsOfAParentFireAnActorDrove(t *testing.T) { + t.Skip("a parent Fire an actor drove has its timers and services armed, but its domain effects aren't dispatched; #235 fixes it") + ctx := context.Background() + type cx struct{} + m := state.ForgeFor[cx]("actorEffects"). + Action("notify", func(state.ActionCtx[cx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + Actor("child"). + State("idle"). + State("spawning").InvokeActor("child", state.WithInvokeOnError("spawnFailed")). + State("failed"). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed").Do("notify"). + Quench() + rec := newEffectRecorder() + h, err := durable.NewRunner(m, durable.NewMemStore(), + durable.WithEffectHandler[string, string, cx](rec.handler()), + durable.WithActorPalette[string, string, cx](map[string]state.ActorBehavior{"child": failingSpawn(nil)}), + ).Start(ctx, "actor-effects", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if got := h.Instance().Current(); got != "failed" { + t.Fatalf("state = %q, want failed by the onError", got) + } + if got := len(rec.values); got != 1 { + t.Fatalf("dispatched %d effects, want the onError transition's notify", got) + } +} diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go new file mode 100644 index 00000000..cc5d4008 --- /dev/null +++ b/durable/actor_lifecycle_test.go @@ -0,0 +1,511 @@ +package durable_test + +// The Recover tests for actors whose lifecycle a step journals: an actor spawned and +// stopped within one step, and failed spawns on re-entry, by a Fire, a settle, or a +// recovered Handle, which Recover retries as it always has. + +import ( + "context" + "errors" + "fmt" + "sync/atomic" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// driverChild: on "go" it sends the parent "toZ" then "kill" in one step. +func driverChild() state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + child := state.ForgeFor[actorCtx]("driver"). + State("ready"). + Initial("ready"). + Transition("ready").On("go").GoTo("ready").SendParent("toZ").SendParent("kill"). + Quench() + return state.NewActor(child.Cast(actorCtx{}, state.WithInitialState[string]("ready")), nil), nil + } +} + +func flipMachine() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("flip"). + Actor("spawnDriver"). + Actor("spawnChild"). + State("y").InvokeActor("spawnDriver"). + State("z").InvokeActor("spawnChild"). + Initial("y"). + Transition("y").On("toZ").GoTo("z"). + Transition("z").On("kill").GoTo("z").StopActor(state.ActorID("flip", "z", 0)). + Transition("z").On("poke").GoTo("z"). + Quench() +} + +// An actor spawned and stopped within one delivery is never seen at a step boundary, +// so the ended set misses it and Recover spawns it though live has it stopped. +func TestRecover_ActorSpawnedAndStoppedInOneStep_StaysEnded(t *testing.T) { + ctx := context.Background() + childID := state.ActorID("flip", "z", 0) + driverID := state.ActorID("flip", "y", 0) + for _, every := range []int{0, 1, 2, 3} { + t.Run(fmt.Sprintf("checkpoint every %d", every), func(t *testing.T) { + var runs int64 + pal := map[string]state.ActorBehavior{"spawnDriver": driverChild(), "spawnChild": counterChild(&runs)} + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](pal)} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, actorCtx](every)) + } + m := flipMachine() + store := durable.NewMemStore() + id := durable.InstanceID(fmt.Sprintf("flip-%d", every)) + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("y")) + if err != nil { + t.Fatal(err) + } + ref, ok := h.ActorRef(driverID) + if !ok { + t.Fatal("no driver") + } + if _, err = h.DeliverToActor(ctx, ref, "go"); err != nil { + t.Fatal(err) + } + if got := h.Instance().Current(); got != "z" { + t.Fatalf("live state %v", got) + } + if _, ok := h.ActorRef(childID); ok { + t.Fatal("live: child should be stopped") + } + rec, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatal(err) + } + if _, ok := rec.ActorRef(childID); ok { + t.Error("Recover: child is running, live had it stopped") + } + // A step on the recovered Handle, then a second Recover. + if _, err = rec.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + again, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatal(err) + } + if _, ok := again.ActorRef(childID); ok { + t.Error("second Recover: child is running, live had it stopped") + } + }) + } +} + +type probeCtx struct { + Notes []string `json:"notes"` +} + +func probeChild() state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + child := state.ForgeFor[probeCtx]("child"). + State("working").State("done").Final().Initial("working"). + Transition("working").On("finish").GoTo("done").Quench() + inst := child.Cast(probeCtx{}, state.WithInitialState[string]("working")) + return state.NewActor(inst, func(*state.Instance[string, string, probeCtx]) any { return "out" }), nil + } +} + +func probeMachine() *state.Machine[string, string, probeCtx] { + return state.ForgeFor[probeCtx]("probe"). + Actor("spawnChild"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("done").Final(). + Initial("working"). + Transition("working").On("re").GoTo("working").Reenter(). + Transition("working").On("poke").GoTo("working"). + Transition("working").On("childDone").GoTo("done"). + Quench() +} + +// First spawn succeeds, later ones fail. +func TestRecover_RetriesAFailedReentrySpawn(t *testing.T) { + ctx := context.Background() + m := probeMachine() + store := durable.NewMemStore() + id := durable.InstanceID("p1") + var n int64 + pal := map[string]state.ActorBehavior{"spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 1 { + return nil, errors.New("can't start") + } + return probeChild()(in) + }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, probeCtx](pal)). + Start(ctx, id, probeCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + if _, err = h.Fire(ctx, "re"); err != nil { + t.Fatal(err) + } + aid := state.ActorID("probe", "working", 0) + if _, ok := h.ActorRef(aid); ok { + t.Fatal("setup: respawn should have failed") + } + good := map[string]state.ActorBehavior{"spawnChild": probeChild()} + rec, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := rec.ActorRef(aid); !ok { + t.Fatal("Recover didn't retry the actor whose re-entry spawn failed live") + } +} + +// Live: running at crash. Recover #1 spawn fails; a step; Recover #2 succeeds. +func TestRecover_RetriesASpawnThatFailedAtRecover(t *testing.T) { + ctx := context.Background() + m := probeMachine() + store := durable.NewMemStore() + id := durable.InstanceID("p2") + good := map[string]state.ActorBehavior{"spawnChild": probeChild()} + bad := map[string]state.ActorBehavior{"spawnChild": func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("x") }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, probeCtx](good)). + Start(ctx, id, probeCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + r1, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](bad)) + if err != nil { + t.Fatal(err) + } + if _, err = r1.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + r2, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := r2.ActorRef(state.ActorID("probe", "working", 0)); !ok { + t.Fatal("second Recover didn't retry") + } +} + +// Running at crash, recovered handle re-enters and its respawn fails, then Recover. +func TestRecover_RetriesAFailedReentrySpawnOnARecoveredHandle(t *testing.T) { + ctx := context.Background() + m := probeMachine() + store := durable.NewMemStore() + id := durable.InstanceID("p3") + good := map[string]state.ActorBehavior{"spawnChild": probeChild()} + var n int64 + once := map[string]state.ActorBehavior{"spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 1 { + return nil, errors.New("can't start") + } + return probeChild()(in) + }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, probeCtx](good)). + Start(ctx, id, probeCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + r1, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](once)) + if err != nil { + t.Fatal(err) + } + if _, err = r1.Fire(ctx, "re"); err != nil { + t.Fatal(err) + } + r2, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := r2.ActorRef(state.ActorID("probe", "working", 0)); !ok { + t.Fatal("Recover didn't retry") + } +} + +func TestRecover_RetriesASpawnThatFailedWhenASettleReentered(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[probeCtx]("probe2"). + Actor("spawnChild"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + Initial("working"). + Transition("working").On("childDone").GoTo("working").Reenter(). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("p4") + var n int64 + pal := map[string]state.ActorBehavior{"spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 1 { + return nil, errors.New("can't start") + } + return probeChild()(in) + }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, probeCtx](pal)). + Start(ctx, id, probeCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + aid := state.ActorID("probe2", "working", 0) + ref, _ := h.ActorRef(aid) + if found, derr := h.DeliverToActor(ctx, ref, "finish"); !found || derr != nil { + t.Fatalf("deliver: %v %v", found, derr) + } + if _, ok := h.ActorRef(aid); ok { + t.Fatal("setup: respawn should have failed") + } + good := map[string]state.ActorBehavior{"spawnChild": probeChild()} + rec, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := rec.ActorRef(aid); !ok { + t.Fatal("Recover didn't retry the actor whose re-entry spawn (via settle) failed live") + } +} + +type rsCtx struct { + N int `json:"n"` +} + +func rsChild() state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + c := state.ForgeFor[rsCtx]("rschild"). + State("w").Initial("w"). + Transition("w").On("go").GoTo("w").SendParent("re").SendParent("re"). + Quench() + return state.NewActor(c.Cast(rsCtx{}, state.WithInitialState[string]("w")), nil), nil + } +} + +func rsMachine() *state.Machine[string, string, rsCtx] { + return state.ForgeFor[rsCtx]("rs"). + Actor("spawnChild"). + State("working").InvokeActor("spawnChild"). + Initial("working"). + Transition("working").On("re").GoTo("working").Reenter(). + Transition("working").On("poke").GoTo("working"). + Quench() +} + +// In one delivery the state is re-entered twice: the first respawn starts, the +// second fails. Live ends with no actor; Recover should retry it. +func TestRecover_RetriesAnActorWhoseSecondReentrySpawnFailed(t *testing.T) { + for _, poke := range []bool{false, true} { + ctx := context.Background() + m := rsMachine() + store := durable.NewMemStore() + id := durable.InstanceID("rs") + var n int64 + pal := map[string]state.ActorBehavior{"spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 2 { + return nil, errors.New("can't start") + } + return rsChild()(in) + }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, rsCtx](pal)). + Start(ctx, id, rsCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + aid := state.ActorID("rs", "working", 0) + ref, ok := h.ActorRef(aid) + if !ok { + t.Fatal("no child") + } + if _, err = h.DeliverToActor(ctx, ref, "go"); err != nil { + t.Fatal(err) + } + if got := atomic.LoadInt64(&n); got != 3 { + t.Fatalf("setup: spawns %d, want 3", got) + } + if _, ok := h.ActorRef(aid); ok { + t.Fatal("setup: last respawn should have failed") + } + if poke { + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + } + good := map[string]state.ActorBehavior{"spawnChild": rsChild()} + rec, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, rsCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := rec.ActorRef(aid); !ok { + t.Errorf("poke=%v: Recover didn't retry the actor whose last respawn failed", poke) + } + } +} + +func driver3() state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + child := state.ForgeFor[actorCtx]("driver").State("ready").Initial("ready"). + Transition("ready").On("go").GoTo("ready").SendParent("toZ").SendParent("kill").SendParent("re"). + Quench() + return state.NewActor(child.Cast(actorCtx{}, state.WithInitialState[string]("ready")), nil), nil + } +} + +// Non-blocker probe: in one delivery the z child spawns, is stopped, and its re-entry +// spawn fails. Live: not running. Is it retried by Recover (the stated rule for a failed +// spawn), or recorded as ended? +func TestRecover_RetriesAnActorWhoseLatestSpawnInAStepFailed(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[actorCtx]("flip"). + Actor("spawnDriver").Actor("spawnChild"). + State("y").InvokeActor("spawnDriver"). + State("z").InvokeActor("spawnChild"). + Initial("y"). + Transition("y").On("toZ").GoTo("z"). + Transition("z").On("kill").GoTo("z").StopActor(state.ActorID("flip", "z", 0)). + Transition("z").On("re").GoTo("z").Reenter(). + Quench() + var n, runs int64 + pal := map[string]state.ActorBehavior{"spawnDriver": driver3(), "spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 1 { + return nil, errors.New("no") + } + return counterChild(&runs)(in) + }} + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, actorCtx](pal)).Start(ctx, "x", actorCtx{}, state.WithInitialState("y")) + if err != nil { + t.Fatal(err) + } + ref, _ := h.ActorRef(state.ActorID("flip", "y", 0)) + if _, err = h.DeliverToActor(ctx, ref, "go"); err != nil { + t.Fatal(err) + } + cid := state.ActorID("flip", "z", 0) + good := map[string]state.ActorBehavior{"spawnDriver": driver3(), "spawnChild": counterChild(&runs)} + rec, err := durable.Recover(ctx, m, store, "x", durable.WithActorPalette[string, string, actorCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, rr := rec.ActorRef(cid); !rr { + t.Fatal("Recover didn't retry the actor whose latest spawn failed") + } +} + +// TestRecover_SpawnsASuperstatesActor proves an actor a compound state declares runs +// while one of its children is active: Start spawns it, and so does Recover after a +// step moved between the children. +func TestRecover_SpawnsASuperstatesActor(t *testing.T) { + t.Skip("Start and Recover start only the active leaves' services and actors, not a compound state's; #249") + ctx := context.Background() + m := state.ForgeFor[actorCtx]("nest"). + Actor("spawnChild"). + SuperState("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + SubState("a"). + SubState("b"). + Initial("a"). + EndSuperState(). + State("done").Final(). + Initial("working"). + Transition("a").On("next").GoTo("b"). + Transition("working").On("childDone").GoTo("done"). + Quench() + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + store := durable.NewMemStore() + id := durable.InstanceID("nest") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + childID := state.ActorID("nest", "working", 0) + if _, ok := h.ActorRef(childID); !ok { + t.Fatal("Start didn't spawn the superstate's actor") + } + if _, err = h.Fire(ctx, "next"); err != nil { + t.Fatalf("Fire: %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if found, _ := recovered.DeliverToActor(ctx, state.ActorRef{ID: childID}, "finish"); !found { + t.Fatal("Recover didn't spawn the superstate's actor") + } + if got := recovered.Instance().Current(); got != "done" { + t.Fatalf("state = %q, want done after the actor finished", got) + } +} + +// greeter is an actor that sends its parent "hello" as it spawns, then keeps running. +type greeter struct{ sent bool } + +func (g *greeter) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (g *greeter) ChildEffects() []state.Effect { + if g.sent { + return nil + } + g.sent = true + return []state.Effect{state.SendParent{Event: "hello"}} +} +func (g *greeter) Output() any { return nil } + +// TestRecover_AppliesASpawnMessageOnce proves a message a running actor sends its parent +// as it spawns is journaled with the step that spawned it, or the step after Start, and +// Recover spawns the actor again without sending it again, so it applies once. +func TestRecover_AppliesASpawnMessageOnce(t *testing.T) { + ctx := context.Background() + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { return &greeter{}, nil }, + })} + for _, initial := range []string{"idle", "greeting"} { + t.Run("from "+initial, func(t *testing.T) { + m := state.ForgeFor[actorCtx]("greet"). + Reducer("noteHello", note("hello")). + Reducer("notePoke", note("poke")). + Actor("greeter"). + State("idle"). + State("greeting").InvokeActor("greeter"). + Initial(initial). + Transition("idle").On("go").GoTo("greeting"). + Transition("greeting").On("hello").GoTo("greeting").Assign("noteHello"). + Transition("greeting").On("poke").GoTo("greeting").Assign("notePoke"). + Quench() + store, id := durable.NewMemStore(), durable.InstanceID("greet") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + if initial == "idle" { + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + hellos := 0 + for _, n := range recovered.Instance().Entity().Notes { + if n == "hello" { + hellos++ + } + } + if hellos != 1 { + t.Fatalf("recovered notes = %v, want the spawn's hello once", recovered.Instance().Entity().Notes) + } + }) + } +} diff --git a/durable/actor_sets_cost_test.go b/durable/actor_sets_cost_test.go new file mode 100644 index 00000000..c9d55622 --- /dev/null +++ b/durable/actor_sets_cost_test.go @@ -0,0 +1,48 @@ +package durable_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestFire_AStepThatTouchesNoActorCostsLittleExtra pins that a machine declaring actors +// pays little extra on a step that touches no actor: a Fire that only moves within the +// state allocates about as much with an actor palette as without one. +func TestFire_AStepThatTouchesNoActorCostsLittleExtra(t *testing.T) { + ctx := context.Background() + allocs := func(withActors bool) float64 { + b := state.ForgeFor[stepCtx]("cost") + if withActors { + b = b.Actor("a").Actor("b").Actor("c") + } + b = b.State("working") + if withActors { + b = b.InvokeActor("a").InvokeActor("b").InvokeActor("c") + } + m := b.Initial("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + var opts []stepOption + if withActors { + beh := func(map[string]any) (state.ActorInstance, error) { return &reentryGreeter{sent: true}, nil } + opts = append(opts, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"a": beh, "b": beh, "c": beh})) + } + h, err := durable.NewRunner(m, durable.NewMemStore(), opts...).Start(ctx, "cost", stepCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + return testing.AllocsPerRun(50, func() { + if _, err := h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire: %v", err) + } + }) + } + without, with := allocs(false), allocs(true) + t.Logf("allocations per Fire: %.0f without actors, %.0f with three", without, with) + if with > without+10 { + t.Fatalf("a Fire that touches no actor allocates %.0f with three declared actors, %.0f without: the actor sets are recomputed every step", with, without) + } +} diff --git a/durable/actor_sets_internal_test.go b/durable/actor_sets_internal_test.go new file mode 100644 index 00000000..2b21c129 --- /dev/null +++ b/durable/actor_sets_internal_test.go @@ -0,0 +1,104 @@ +package durable + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +type setsCtx struct { + Notes []string `json:"notes"` +} + +// TestActorSets_FollowTheActorsState proves a step that touched no actor leaves both +// actor sets as they were, while a step that leaves the actor's state ends it. +func TestActorSets_FollowTheActorsState(t *testing.T) { + ctx := context.Background() + child := state.ForgeFor[setsCtx]("child"). + State("working"). + State("done").Final(). + Initial("working"). + Transition("working").On("finish").GoTo("done"). + Quench() + m := state.ForgeFor[setsCtx]("sets"). + Actor("child"). + State("working").InvokeActor("child"). + State("idle"). + Initial("working"). + Transition("working").On("poke").GoTo("working"). + Transition("working").On("leave").GoTo("idle"). + Quench() + palette := map[string]state.ActorBehavior{"child": func(map[string]any) (state.ActorInstance, error) { + return state.NewActor(child.Cast(setsCtx{}, state.WithInitialState("working")), nil), nil + }} + h, err := NewRunner(m, NewMemStore(), WithActorPalette[string, string, setsCtx](palette)). + Start(ctx, "sets", setsCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + ended, unstarted := h.actorSets() + if len(ended.IDs) != 0 || len(unstarted.IDs) != 0 { + t.Fatalf("sets = %v, %v, want none: the actor is running", ended.IDs, unstarted.IDs) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if ended, unstarted = h.actorSets(); len(ended.IDs) != 0 || len(unstarted.IDs) != 0 { + t.Fatalf("sets = %v, %v after a step that touched no actor, want none", ended.IDs, unstarted.IDs) + } + if _, err = h.Fire(ctx, "leave"); err != nil { + t.Fatalf("Fire(leave): %v", err) + } + if ended, unstarted = h.actorSets(); len(ended.IDs) != 0 || len(unstarted.IDs) != 0 { + t.Fatalf("sets = %v, %v after leaving the actor's state, want none: idle declares no actor", ended.IDs, unstarted.IDs) + } +} + +// TestActorSets_ListsAnEndedActorOnce proves an actor id two active states declare is +// listed once when the actor has ended. +func TestActorSets_ListsAnEndedActorOnce(t *testing.T) { + ctx := context.Background() + child := state.ForgeFor[setsCtx]("child"). + State("working"). + State("done").Final(). + Initial("working"). + Transition("working").On("finish").GoTo("done"). + Quench() + m := state.ForgeFor[setsCtx]("twice"). + Actor("child"). + State("off"). + SuperState("par"). + Region("left"). + Initial("p"). + SubState("p").InvokeActor("child", state.WithInvokeID("v")). + EndRegion(). + Region("right"). + Initial("q"). + SubState("q").InvokeActor("child", state.WithInvokeID("v")). + EndRegion(). + EndSuperState(). + Initial("off"). + Transition("off").On("go").GoTo("par"). + Quench() + palette := map[string]state.ActorBehavior{"child": func(map[string]any) (state.ActorInstance, error) { + return state.NewActor(child.Cast(setsCtx{}, state.WithInitialState("working")), nil), nil + }} + h, err := NewRunner(m, NewMemStore(), WithActorPalette[string, string, setsCtx](palette)). + Start(ctx, "twice", setsCtx{}, state.WithInitialState("off")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + if found, deliverErr := h.DeliverToActorByID(ctx, "v", "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActorByID = %v, %v", found, deliverErr) + } + if ended, _ := h.actorSets(); len(ended.IDs) != 1 || ended.IDs[0] != "v" { + t.Fatalf("ended = %v, want [v]", ended.IDs) + } +} diff --git a/durable/actor_test.go b/durable/actor_test.go index f8af0cd5..35bd209a 100644 --- a/durable/actor_test.go +++ b/durable/actor_test.go @@ -2,6 +2,7 @@ package durable_test import ( "context" + "errors" "fmt" "sync/atomic" "testing" @@ -704,3 +705,143 @@ func TestActor_Determinism(t *testing.T) { t.Fatalf("two live runs diverged:\n run1=%s\n run2=%s", s1, s2) } } + +// TestDeliverToActor_ContextEndedPartway_RecordsNothing proves a delivery whose context +// ended records nothing, so every later Recover still works. +func TestDeliverToActor_ContextEndedPartway_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := supervisorMachine() + store := durable.NewMemStore() + id := durable.InstanceID("sup-cancel") + turn, cancel := context.WithCancel(ctx) + defer cancel() + behavior := func(map[string]any) (state.ActorInstance, error) { + child := state.ForgeFor[actorCtx]("child"). + State("working"). + State("done").Final(). + Initial("working"). + Transition("working").On("finish").GoTo("done"). + Quench() + inst := child.Cast(actorCtx{}, state.WithInitialState[string]("working")) + return state.NewActor(inst, func(*state.Instance[string, string, actorCtx]) any { + cancel() // the turn ends after the child finishes, before the parent settles + return "late" + }), nil + } + opts := []durable.Option[string, string, actorCtx]{ + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{"spawnChild": behavior}), + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for spawned child") + } + before := tailLen(t, store, id) + if _, err = h.DeliverToActor(turn, ref, "finish"); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("DeliverToActor = %v, want ErrHandleFailed", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "supervising" { + t.Fatalf("recovered state %q, want supervising: the canceled delivery was committed", got) + } +} + +// supervisorUsing is supervisorMachine with mw installed and, if refuseDone, a +// childDone transition whose guard always fails. +func supervisorUsing(mw state.Middleware[string, string, actorCtx], refuseDone bool) *state.Machine[string, string, actorCtx] { + b := state.ForgeFor[actorCtx]("supervisor"). + Guard("never", func(state.GuardCtx[actorCtx]) bool { return false }). + Actor("spawnChild"). + State("supervising").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone"), state.WithInvokeOnError("childFail")). + State("complete").Final(). + State("failed").Final(). + Initial("supervising") + if mw != nil { + b = b.Use(mw) + } + t := b.Transition("supervising").On("childDone").GoTo("complete") + if refuseDone { + t = t.When("never") + } + return t.Transition("supervising").On("childFail").GoTo("failed").Quench() +} + +// TestDeliverToActor_RefusedByADerivedContext_RecordsNothing proves a delivery whose +// parent Fire is refused because a context middleware derived from the caller's ended, +// while the caller's is still live, fails the Handle and records nothing. +func TestDeliverToActor_RefusedByADerivedContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + cancelOnDone := func(next state.FireFunc[string, string, actorCtx]) state.FireFunc[string, string, actorCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + if event == "childDone" { + derived, cancel := context.WithCancel(ctx) + cancel() + return next(derived, event) + } + return next(ctx, event) + } + } + m := supervisorUsing(cancelOnDone, false) + store := durable.NewMemStore() + id := durable.InstanceID("sup-derived") + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for spawned child") + } + before := tailLen(t, store, id) + if _, err = h.DeliverToActor(ctx, ref, "finish"); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("DeliverToActor = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } +} + +// TestDeliverToActor_DeterministicRefusal_Recovers proves a parent Fire refused for a +// reason replay meets again (a guard that fails) is journaled, and Recover replays it +// to the live state instead of failing on the refusal. +func TestDeliverToActor_DeterministicRefusal_Recovers(t *testing.T) { + ctx := context.Background() + m := supervisorUsing(nil, true) + store := durable.NewMemStore() + id := durable.InstanceID("sup-refused") + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for spawned child") + } + before := tailLen(t, store, id) + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + if after := tailLen(t, store, id); after != before+1 { + t.Fatalf("journal grew from %d to %d records, want one", before, after) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if live, got := h.Instance().Current(), recovered.Instance().Current(); got != live || live != "supervising" { + t.Fatalf("recovered %q, live %q, want both supervising", got, live) + } +} diff --git a/durable/bench_test.go b/durable/bench_test.go index 4b474f9a..0562721d 100644 --- a/durable/bench_test.go +++ b/durable/bench_test.go @@ -80,3 +80,42 @@ func BenchmarkMemStore_Append(b *testing.B) { } } } + +// BenchmarkHandle_Fire_ActorIdleStep measures what a machine that declares actors pays +// on a step that touches none: the actor sets the step records come from a cache, so +// the difference from the no-actor case is the cache check. +func BenchmarkHandle_Fire_ActorIdleStep(b *testing.B) { + ctx := context.Background() + for _, tc := range []struct { + name string + actors bool + }{{"noActors", false}, {"threeActors", true}} { + b.Run(tc.name, func(b *testing.B) { + bl := state.ForgeFor[stepCtx]("cost") + if tc.actors { + bl = bl.Actor("a").Actor("b").Actor("c") + } + bl = bl.State("working") + if tc.actors { + bl = bl.InvokeActor("a").InvokeActor("b").InvokeActor("c") + } + m := bl.Initial("working").Transition("working").On("poke").GoTo("working").Quench() + var opts []stepOption + if tc.actors { + beh := func(map[string]any) (state.ActorInstance, error) { return &reentryGreeter{sent: true}, nil } + opts = append(opts, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"a": beh, "b": beh, "c": beh})) + } + h, err := durable.NewRunner(m, durable.NewMemStore(), opts...).Start(ctx, "cost", stepCtx{}, state.WithInitialState("working")) + if err != nil { + b.Fatalf("Start: %v", err) + } + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if _, err := h.Fire(ctx, "poke"); err != nil { + b.Fatalf("Fire: %v", err) + } + } + }) + } +} diff --git a/durable/chained_deadline_internal_test.go b/durable/chained_deadline_internal_test.go new file mode 100644 index 00000000..39ee3313 --- /dev/null +++ b/durable/chained_deadline_internal_test.go @@ -0,0 +1,303 @@ +package durable + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/stablekernel/crucible/state" +) + +// steppingClock advances one millisecond on every read while stepping, so each read in a +// Tick is a distinct instant, as a real clock's are; with stepping off it holds still. +type steppingClock struct { + mu sync.Mutex + now time.Time + stepping bool +} + +func (c *steppingClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + t := c.now + if c.stepping { + c.now = c.now.Add(time.Millisecond) + } + return t +} + +func (c *steppingClock) After(time.Duration) <-chan time.Time { return make(chan time.Time) } + +func (c *steppingClock) set(t time.Time, stepping bool) { + c.mu.Lock() + c.now, c.stepping = t, stepping + c.mu.Unlock() +} + +// TestTick_RecordsAChainedTimersDeadlineAsTheSchedulerArmedIt pins that the deadline the +// Handle records for a chained timer, which a checkpoint persists and Recover re-arms, +// is the one the scheduler armed it at: the scheduler must not fire the timer before the +// recorded deadline. +func TestTick_RecordsAChainedTimersDeadlineAsTheSchedulerArmedIt(t *testing.T) { + ctx := context.Background() + type cx struct{} + m := state.ForgeFor[cx]("chain"). + State("idle"). + State("a"). + State("b"). + State("c"). + Initial("idle"). + Transition("idle").On("go").GoTo("a"). + Transition("a").After(time.Second).On("toB").GoTo("b"). + Transition("b").After(time.Second).On("toC").GoTo("c"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := &steppingClock{now: base} + h, err := NewRunner(m, NewMemStore(), WithRunnerClock[string, string, cx](clk)). + Start(ctx, "chain", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + // Tick with a moving clock: the timer into b fires, and b's timer is chained. + clk.set(base.Add(2*time.Second), true) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := h.inst.Current(); got != "b" { + t.Fatalf("state = %q, want b", got) + } + var recorded time.Time + for _, pt := range h.timers { + recorded = pt.due + } + if len(h.timers) != 1 { + t.Fatalf("timer table holds %d timers, want b's alone", len(h.timers)) + } + // Just before the recorded deadline, the scheduler must not consider b's timer due. + clk.set(recorded.Add(-time.Millisecond), false) + if fired := h.sched.Tick(ctx); len(fired) != 0 { + t.Fatalf("the scheduler fired b's timer at %v, before the recorded deadline %v: a checkpoint would re-arm it later than live", recorded.Add(-time.Millisecond), recorded) + } +} + +// TestTick_RecordsEachChainedDeadlineInATwoTimerTick pins the same for two timers that +// fire in one Tick, each chaining another, and that Recover's replay of that Tick ends +// with the same timer table as the live Handle. +func TestTick_RecordsEachChainedDeadlineInATwoTimerTick(t *testing.T) { + ctx := context.Background() + type cx struct{} + m := state.ForgeFor[cx]("pair"). + State("idle"). + SuperState("both"). + Region("left"). + Initial("l1"). + SubState("l1"). + SubState("l2"). + EndRegion(). + Region("right"). + Initial("r1"). + SubState("r1"). + SubState("r2"). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("both"). + Transition("l1").After(time.Second).On("toL2").GoTo("l2"). + Transition("l2").After(time.Second).On("lDone").GoTo("l2"). + Transition("r1").After(time.Second).On("toR2").GoTo("r2"). + Transition("r2").After(time.Second).On("rDone").GoTo("r2"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := &steppingClock{now: base} + store := NewMemStore() + opts := []Option[string, string, cx]{WithRunnerClock[string, string, cx](clk)} + h, err := NewRunner(m, store, opts...).Start(ctx, "pair", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + clk.set(base.Add(2*time.Second), true) + fired, err := h.Tick(ctx) + if err != nil || len(fired) != 2 { + t.Fatalf("Tick fired %d timers, err %v; want both", len(fired), err) + } + if len(h.timers) != 2 { + t.Fatalf("timer table holds %d timers, want the two chained ones", len(h.timers)) + } + earliest := time.Time{} + for _, pt := range h.timers { + if earliest.IsZero() || pt.due.Before(earliest) { + earliest = pt.due + } + } + clk.set(earliest.Add(-time.Millisecond), false) + if got := h.sched.Tick(ctx); len(got) != 0 { + t.Fatalf("the scheduler fired a chained timer before its recorded deadline %v", earliest) + } + live := map[string]time.Time{} + for id, pt := range h.timers { + live[id] = pt.due + } + recovered, err := Recover(ctx, m, store, "pair", WithRunnerClock[string, string, cx](state.NewFakeClock(base.Add(time.Hour)))) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if len(recovered.timers) != len(live) { + t.Fatalf("recovered timer table holds %d timers, want %d", len(recovered.timers), len(live)) + } + for id, due := range live { + if got := recovered.timers[id].due; !got.Equal(due) { + t.Fatalf("recovered deadline for %s = %v, want the live %v", id, got, due) + } + } +} + +// TestTick_AChainedDeadlineHoldsWhenAFiredTransitionReadsTheClock pins that the +// recorded deadline of a chained timer is still the scheduler's when the fired +// transition's own action reads the instance's clock, adding a read to the Tick. +func TestTick_AChainedDeadlineHoldsWhenAFiredTransitionReadsTheClock(t *testing.T) { + ctx := context.Background() + type cx struct{} + var h *Handle[string, string, cx] + m := state.ForgeFor[cx]("readingAction"). + Action("look", func(state.ActionCtx[cx]) (state.Effect, error) { + _ = h.inst.Clock().Now() + return nil, nil + }). + State("idle"). + State("a"). + State("b"). + State("c"). + Initial("idle"). + Transition("idle").On("go").GoTo("a"). + Transition("a").After(time.Second).On("toB").GoTo("b").Do("look"). + Transition("b").After(time.Second).On("toC").GoTo("c"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := &steppingClock{now: base} + var err error + h, err = NewRunner(m, NewMemStore(), WithRunnerClock[string, string, cx](clk)). + Start(ctx, "reading-action", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + clk.set(base.Add(2*time.Second), true) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + var recorded time.Time + for _, pt := range h.timers { + recorded = pt.due + } + clk.set(recorded.Add(-time.Millisecond), false) + if fired := h.sched.Tick(ctx); len(fired) != 0 { + t.Fatalf("the scheduler fired b's timer before the recorded deadline %v", recorded) + } + clk.set(recorded, false) + if fired := h.sched.Tick(ctx); len(fired) != 1 { + t.Fatalf("the scheduler didn't fire b's timer at the recorded deadline %v: it holds a different one", recorded) + } +} + +// TestFire_ADeadlineHoldsWhenTheTransitionReadsTheClock pins that a timer a Fire arms is +// recorded at the scheduler's deadline when the transition's action reads the instance +// clock first, live and after Recover's replay. +func TestFire_ADeadlineHoldsWhenTheTransitionReadsTheClock(t *testing.T) { + ctx := context.Background() + type cx struct{} + var h *Handle[string, string, cx] + look := func(state.ActionCtx[cx]) (state.Effect, error) { + if h != nil { + _ = h.inst.Clock().Now() + } + return nil, nil + } + m := state.ForgeFor[cx]("fireReads"). + Action("look", look). + State("idle"). + State("a"). + State("b"). + Initial("idle"). + Transition("idle").On("go").GoTo("a").Do("look"). + Transition("a").After(time.Second).On("toB").GoTo("b"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := &steppingClock{now: base, stepping: true} + store := NewMemStore() + var err error + h, err = NewRunner(m, store, WithRunnerClock[string, string, cx](clk)). + Start(ctx, "fire-reads", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + id := state.ScheduleID("fireReads", "a", 0) + want, ok := h.sched.Due(id) + if !ok { + t.Fatalf("no timer pending under %s", id) + } + if got := h.timers[id].due; !got.Equal(want) { + t.Fatalf("live recorded deadline %v, scheduler %v", got, want) + } +} + +// TestRecover_ReplaysAStepWhoseHostCodeReadTheInstanceClock pins what Recover does with +// a step whose host code read the Handle's instance clock: the read is journaled with +// the step's own, but Recover can't run that host read against the replay clock, so +// replay's reads shift by one and the timer comes back at another deadline. +func TestRecover_ReplaysAStepWhoseHostCodeReadTheInstanceClock(t *testing.T) { + t.Skip("a host read of Instance().Clock() during a step is journaled but can't be replayed; #247") + ctx := context.Background() + type cx struct{} + var h *Handle[string, string, cx] + look := func(state.ActionCtx[cx]) (state.Effect, error) { + if h != nil { + _ = h.inst.Clock().Now() + } + return nil, nil + } + m := state.ForgeFor[cx]("fireReads"). + Action("look", look). + State("idle"). + State("a"). + State("b"). + Initial("idle"). + Transition("idle").On("go").GoTo("a").Do("look"). + Transition("a").After(time.Second).On("toB").GoTo("b"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + store := NewMemStore() + var err error + h, err = NewRunner(m, store, WithRunnerClock[string, string, cx](&steppingClock{now: base, stepping: true})). + Start(ctx, "fire-reads", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + id := state.ScheduleID("fireReads", "a", 0) + want, _ := h.sched.Due(id) + h = nil + recovered, err := Recover(ctx, m, store, "fire-reads", WithRunnerClock[string, string, cx](&steppingClock{now: base.Add(time.Hour)})) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.timers[id].due; !got.Equal(want) { + t.Fatalf("recovered deadline %v, want the live %v", got, want) + } + if got, _ := recovered.sched.Due(id); !got.Equal(want) { + t.Fatalf("recovered scheduler holds %v, want the live %v", got, want) + } +} diff --git a/durable/checkpoint.go b/durable/checkpoint.go index c65eb830..1239204d 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -84,14 +84,31 @@ type checkpointEnvelope struct { // Zero means none was recorded: a Start baseline, or a checkpoint from before this // field. NextStep int `json:"nextStep,omitempty"` + // EndedActors is the set of declared actors that had ended at the checkpoint (see + // Record.EndedActors), so a recovery whose compacted tail no longer records it still + // doesn't spawn them. Nil means none was recorded: no actor palette, a Start + // baseline, or an older checkpoint. + EndedActors *ActorSet `json:"endedActors,omitempty"` + // UnstartedActors is the set of declared actors that weren't running and hadn't + // ended at the checkpoint (see Record.UnstartedActors). Nil means none was recorded. + UnstartedActors *ActorSet `json:"unstartedActors,omitempty"` + // EndedServices are the invoked services the active states declared that had settled + // in the current activation of the state that declares each, sorted, so Recover + // doesn't start them again. A declared service that wasn't in flight but never + // settled isn't one. None, as in a Start baseline or an older checkpoint, means + // Recover starts every declared service. + EndedServices []string `json:"endedServices,omitempty"` + // Format is the journal format of the version that wrote the checkpoint, as + // Record.Format is. Zero means a checkpoint from before this field. A Record after + // it with a lower Format means the Store lost the field, and replay fails. + Format int `json:"format,omitempty"` } -// marshalCheckpoint wraps the marshaled kernel snapshot and the armed pending -// timers into a checkpoint envelope's bytes. Timers are emitted in scheduleID -// order so the persisted form is deterministic regardless of the map iteration -// order they were collected in. nextStep is the ordinal that follows the checkpoint. -func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int) ([]byte, error) { - env := checkpointEnvelope{Snapshot: snap, NextStep: nextStep} +// marshalCheckpoint adds the armed pending timers to env, which carries the marshaled +// kernel snapshot and the rest of the checkpoint, and returns the envelope's bytes. +// Timers are emitted in scheduleID order so the persisted form is deterministic +// regardless of the map iteration order they were collected in. +func marshalCheckpoint(env checkpointEnvelope, timers map[string]pendingTimer) ([]byte, error) { if len(timers) > 0 { ids := make([]string, 0, len(timers)) for id := range timers { @@ -125,14 +142,14 @@ func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int // are returned as the snapshot with no timers and a zero ordinal, so an older // checkpoint still restores. A checkpoint envelope is distinguished by carrying a // non-empty "snapshot" member. -func unmarshalCheckpoint(b []byte) ([]byte, []pendingTimerWire, int, error) { +func unmarshalCheckpoint(b []byte) checkpointEnvelope { var env checkpointEnvelope if err := json.Unmarshal(b, &env); err != nil || len(env.Snapshot) == 0 { // Not an envelope (or an envelope without the wrapped snapshot member): treat // the bytes as a bare kernel snapshot, the pre-timer-survival checkpoint form. - return b, nil, 0, nil + return checkpointEnvelope{Snapshot: b} } - return env.Snapshot, env.Timers, env.NextStep, nil + return env } // decodeTimerEvent decodes a persisted timer event wire back into the machine's diff --git a/durable/checkpoint_internal_test.go b/durable/checkpoint_internal_test.go index 5ae66b4f..282ee6a3 100644 --- a/durable/checkpoint_internal_test.go +++ b/durable/checkpoint_internal_test.go @@ -17,14 +17,11 @@ func TestMarshalCheckpoint_RoundTrip(t *testing.T) { timers := map[string]pendingTimer{ "m:a:after:0": {id: "m:a:after:0", due: due, event: "elapsed"}, } - b, err := marshalCheckpoint(snap, timers, 0) + b, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap}, timers) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } - gotSnap, gotWires, _, err := unmarshalCheckpoint(b) - if err != nil { - t.Fatalf("unmarshalCheckpoint: %v", err) - } + gotSnap, gotWires, _ := unmarshalCheckpointParts(b) if string(gotSnap) != string(snap) { t.Fatalf("snapshot round-trip: want %s, got %s", snap, gotSnap) } @@ -45,7 +42,7 @@ func TestMarshalCheckpoint_RoundTrip(t *testing.T) { // armed, so an event-driven checkpoint's envelope stays minimal. func TestMarshalCheckpoint_NoTimers(t *testing.T) { snap := []byte(`{"machine":"m"}`) - b, err := marshalCheckpoint(snap, nil, 0) + b, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap}, nil) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } @@ -64,10 +61,7 @@ func TestMarshalCheckpoint_NoTimers(t *testing.T) { // checkpoint still restores. func TestUnmarshalCheckpoint_BareSnapshotFallback(t *testing.T) { bare := []byte(`{"machine":"m","current":"a","configuration":["a"]}`) - snap, wires, _, err := unmarshalCheckpoint(bare) - if err != nil { - t.Fatalf("unmarshalCheckpoint: %v", err) - } + snap, wires, _ := unmarshalCheckpointParts(bare) if string(snap) != string(bare) { t.Fatalf("bare snapshot not passed through: want %s, got %s", bare, snap) } @@ -81,10 +75,7 @@ func TestUnmarshalCheckpoint_BareSnapshotFallback(t *testing.T) { // any real decode failure when it unmarshals the kernel snapshot). func TestUnmarshalCheckpoint_Garbage(t *testing.T) { garbage := []byte(`not json`) - snap, wires, _, err := unmarshalCheckpoint(garbage) - if err != nil { - t.Fatalf("unmarshalCheckpoint should tolerate garbage: %v", err) - } + snap, wires, _ := unmarshalCheckpointParts(garbage) if string(snap) != string(garbage) || wires != nil { t.Fatalf("garbage not passed through: snap=%s wires=%+v", snap, wires) } @@ -155,37 +146,28 @@ func TestMarshalCheckpoint_BadEventErrors(t *testing.T) { timers := map[string]pendingTimer{ "bad": {id: "bad", due: time.Unix(0, 1), event: make(chan int)}, } - if _, err := marshalCheckpoint([]byte(`{}`), timers, 0); err == nil { + if _, err := marshalCheckpoint(checkpointEnvelope{Snapshot: []byte(`{}`)}, timers); err == nil { t.Fatal("want encode error for unmarshalable timer event, got nil") } } -// TestTickInstant covers the no-clock-read branch (a tick that fired nothing -// records no read) alongside the happy path. -func TestTickInstant(t *testing.T) { - if _, ok := tickInstant(nil); ok { - t.Fatal("empty entries should report no instant") - } - entries := []state.JournalEntry{ - {Kind: state.JournalClockRead, ClockUnixNano: 42}, - } - got, ok := tickInstant(entries) - if !ok || got.UnixNano() != 42 { - t.Fatalf("tickInstant: ok=%v got=%d", ok, got.UnixNano()) - } -} - // TestCheckpoint_NextStepRoundTrips proves the envelope carries the ordinal after // the checkpoint, and that a checkpoint without one reports zero, the old form. func TestCheckpoint_NextStepRoundTrips(t *testing.T) { - b, err := marshalCheckpoint([]byte(`{"v":1}`), nil, 9) + b, err := marshalCheckpoint(checkpointEnvelope{Snapshot: []byte(`{"v":1}`), NextStep: 9}, nil) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } - if _, _, next, err := unmarshalCheckpoint(b); err != nil || next != 9 { - t.Fatalf("unmarshalCheckpoint = (%d, %v), want (9, nil)", next, err) + if _, _, next := unmarshalCheckpointParts(b); next != 9 { + t.Fatalf("unmarshalCheckpoint next = %d, want 9", next) } - if _, _, next, err := unmarshalCheckpoint([]byte(`{"snapshot":{"v":1}}`)); err != nil || next != 0 { - t.Fatalf("old envelope = (%d, %v), want (0, nil)", next, err) + if _, _, next := unmarshalCheckpointParts([]byte(`{"snapshot":{"v":1}}`)); next != 0 { + t.Fatalf("old envelope next = %d, want 0", next) } } + +// unmarshalCheckpointParts is unmarshalCheckpoint split into the parts these tests check. +func unmarshalCheckpointParts(b []byte) ([]byte, []pendingTimerWire, int) { + env := unmarshalCheckpoint(b) + return env.Snapshot, env.Timers, env.NextStep +} diff --git a/durable/clock.go b/durable/clock.go index ad5081f4..7351d69f 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -125,6 +125,7 @@ type replayClock struct { readings []int64 cursor int fallback state.Clock + last time.Time // the reading Now last returned } // newReplayClock builds a replayClock over the recorded readings, falling through @@ -139,11 +140,20 @@ func (c *replayClock) Now() time.Time { c.mu.Lock() defer c.mu.Unlock() if c.cursor < len(c.readings) { - t := time.Unix(0, c.readings[c.cursor]).UTC() + c.last = time.Unix(0, c.readings[c.cursor]).UTC() c.cursor++ - return t + return c.last } - return c.fallback.Now() + c.last = c.fallback.Now() + return c.last +} + +// lastRead returns the reading Now last returned: the instant a replayed timer arming +// or tick computed its deadlines against. +func (c *replayClock) lastRead() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.last } // After delegates to the fallback clock; replay drives elapses through Now + Tick diff --git a/durable/deliver_ctx_test.go b/durable/deliver_ctx_test.go new file mode 100644 index 00000000..1dd8119d --- /dev/null +++ b/durable/deliver_ctx_test.go @@ -0,0 +1,63 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// cancelingActor wraps an actor and ends the step's context just before the actor +// handles a delivered event, as a deadline passing mid-delivery would. +type cancelingActor struct { + inner state.ActorInstance + cancel context.CancelFunc +} + +func (a *cancelingActor) DeliverFire(ctx context.Context, ev any) (bool, any) { + a.cancel() + return a.inner.DeliverFire(ctx, ev) +} +func (a *cancelingActor) ChildEffects() []state.Effect { return a.inner.ChildEffects() } +func (a *cancelingActor) Output() any { return a.inner.Output() } + +// TestDeliverToActor_AContextThatEndsBeforeTheActorHandlesItFails pins that a delivery +// whose context ends before the actor handles the event, so the actor's own Fire is +// refused and the event is lost, fails rather than reporting a delivery that never +// happened. +func TestDeliverToActor_AContextThatEndsBeforeTheActorHandlesItFails(t *testing.T) { + ctx := context.Background() + turn, cancel := context.WithCancel(ctx) + defer cancel() + child := state.ForgeFor[stepCtx]("kid"). + State("working"). + State("noted"). + Initial("working"). + Transition("working").On("note").GoTo("noted"). + Quench() + m := state.ForgeFor[stepCtx]("deliverCtx"). + Actor("kid"). + State("working").InvokeActor("kid", state.WithInvokeID("kid")). + Initial("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "kid": func(map[string]any) (state.ActorInstance, error) { + inner := state.NewActor(child.Cast(stepCtx{}, state.WithInitialState("working")), nil) + return &cancelingActor{inner: inner, cancel: cancel}, nil + }, + })} + h, err := durable.NewRunner(m, durable.NewMemStore(), opts...).Start(ctx, "deliver-ctx", stepCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + found, err := h.DeliverToActorByID(turn, "kid", "note") + if !found { + t.Fatal("the kid isn't running") + } + if !errors.Is(err, context.Canceled) { + t.Fatalf("DeliverToActor = %v, want an error wrapping context.Canceled: the kid never handled the event", err) + } +} diff --git a/durable/deliver_panic_internal_test.go b/durable/deliver_panic_internal_test.go new file mode 100644 index 00000000..0cf02995 --- /dev/null +++ b/durable/deliver_panic_internal_test.go @@ -0,0 +1,65 @@ +package durable + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// messenger is an actor that sends its parent "boom" when it's delivered an event. +type messenger struct{ out []state.Effect } + +func (a *messenger) DeliverFire(context.Context, any) (bool, any) { + a.out = []state.Effect{state.SendParent{Event: "boom"}} + return false, nil +} + +func (a *messenger) ChildEffects() []state.Effect { + out := a.out + a.out = nil + return out +} +func (a *messenger) Output() any { return nil } + +// TestDeliverToActor_APanicLeavesNoStepContextBehind pins that a panic during a +// delivery, here in the parent's middleware for a message the actor sent, doesn't leave the actor collector holding the dead step's context, which a +// later parent Fire on the system would arm its timers and services under. +func TestDeliverToActor_APanicLeavesNoStepContextBehind(t *testing.T) { + ctx := context.Background() + type cx struct{} + m := state.ForgeFor[cx]("panicky"). + Use(func(next state.FireFunc[string, string, cx]) state.FireFunc[string, string, cx] { + return func(ctx context.Context, ev string) state.FireResult[string] { + if ev == "boom" { + panic("the parent's middleware panicked") + } + return next(ctx, ev) + } + }). + Actor("kid"). + State("working").InvokeActor("kid", state.WithInvokeID("kid")). + Initial("working"). + Transition("working").On("boom").GoTo("working"). + Quench() + h, err := NewRunner(m, NewMemStore(), WithActorPalette[string, string, cx](map[string]state.ActorBehavior{ + "kid": func(map[string]any) (state.ActorInstance, error) { return &messenger{}, nil }, + })).Start(ctx, "panicky", cx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + panicked := false + func() { + defer func() { panicked = recover() != nil }() + _, _ = h.DeliverToActorByID(ctx, "kid", "go") + }() + if !panicked { + t.Skip("no host panic reaches DeliverToActor: the kernel and the actor system recover them") + } + h.actorFires.mu.Lock() + left := h.actorFires.ctx + h.actorFires.mu.Unlock() + if left != nil { + t.Fatal("the actor collector still holds the panicked step's context") + } +} diff --git a/durable/doc.go b/durable/doc.go index 2a0bff56..559ca3b4 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -99,17 +99,20 @@ // was compacted out of the tail is re-armed from its persisted deadline rather // than lost. // -// Invoked services (WithServiceRegistry): a service (`invoke`) runs exactly once -// on the live path; its result is journaled as a JournalServiceResult. On -// recovery the recorded result is replayed back through the same kernel settle -// seam — the service is never re-invoked and the same onDone or onError event -// re-fires with the same data. -// -// Child-machine actors (WithActorPalette): an actor's behavior runs exactly once -// on the live path; each parent transition the delivery drives is journaled as a -// JournalActorMessage. On recovery the recorded transition is re-fired directly -// through the parent with the recorded done-data — the actor behavior is never -// re-instantiated. +// Invoked services (WithServiceRegistry): a service (`invoke`) runs on the live path; +// its result is journaled as a JournalServiceResult. On recovery the recorded result is +// replayed back through the same kernel settle seam — that service is never re-invoked +// and the same onDone or onError event re-fires with the same data. A result that +// wasn't recorded has nothing to replay, so the service runs again when the host calls +// RunService. +// +// Child-machine actors (WithActorPalette): an actor's behavior runs on the live path; +// each parent transition the delivery drives is journaled as a JournalActorMessage. On +// recovery the recorded transition is re-fired directly through the parent with the +// recorded done-data, so a settled actor never re-runs. Each step records the declared +// actors that ran and ended, settled or stopped, and Recover doesn't spawn those. An +// InvokeActor actor still running at recovery restarts from its initial state, because +// its own state isn't journaled, and a Spawn actor doesn't return. // // # Idempotent effect dispatch // diff --git a/durable/errors.go b/durable/errors.go index 111a4bd7..f24f15e3 100644 --- a/durable/errors.go +++ b/durable/errors.go @@ -56,8 +56,17 @@ var ( ErrRecordTooLarge = errors.New(errorPrefix + errorRecordTooLarge) // ErrHandleFailed is reported by a Handle's Fire, Tick, RunService, DeliverToActor - // and View once a step applied to the live instance but may not have been recorded, - // or an effect handler failed, on that call and every later one. It wraps the cause. + // and View, on the call that failed the Handle and every later one. It wraps the + // cause, which is one of: + // - a step applied to the live instance but may not have been recorded; + // - a Tick, RunService or DeliverToActor ran while its context ended, so a Fire it + // drove may have been refused: it had already consumed the timer, service or + // delivery, so it can't simply refuse the way Fire does; + // - a step, Fire included, drove a Fire that a context's ending refused, such as a + // spawned actor's onError: Recover restores the state from before the step, so a + // Fire's event must be fired again; + // - host code panicked during a step; + // - an effect handler failed. // Call Handle.Drain, then Recover a new Handle with the same options to continue, // unless the cause is ErrFenced: then a newer owner holds the instance, so stop. ErrHandleFailed = errors.New(errorPrefix + errorHandleFailed) diff --git a/durable/integration_test.go b/durable/integration_test.go index c5426a39..270414c9 100644 --- a/durable/integration_test.go +++ b/durable/integration_test.go @@ -22,7 +22,8 @@ var errInjectedEffectCrash = errors.New("injected: crashed mid effect dispatch") // a delayed (`after`) timer — driven through the Runner over both the in-memory and // the on-disk Store, with crashes injected at each seam boundary. It proves the // seams compose: a recovery at any point reaches a snapshot byte-identical to a -// never-crashed reference, each external call (service, actor) happens exactly once, +// never-crashed reference, each external call (service, actor) happens once per +// recorded result (none of these crash points falls inside a call), // each domain effect is applied exactly once, and the timer fires from its recorded // deadline regardless of the wall clock at recovery. @@ -458,7 +459,8 @@ func finishPipeline(t *testing.T, ctx context.Context, h *durable.Handle[string, // TestIntegration_CrashMatrix_MemStore is the capstone over the in-memory Store: the // pipeline machine — service + actor + effect + timer — recovers byte-identically to -// a never-crashed reference at every crash point, invoking each seam exactly once. +// a never-crashed reference at every crash point, invoking each seam once per +// recorded result. func TestIntegration_CrashMatrix_MemStore(t *testing.T) { newStore := func() durable.Store { return durable.NewMemStore() } runCrashMatrix(t, "MemStore", newStore) diff --git a/durable/memstore.go b/durable/memstore.go index fd2105ac..f89a7ecc 100644 --- a/durable/memstore.go +++ b/durable/memstore.go @@ -386,7 +386,7 @@ func cloneBytes(b []byte) []byte { // json.RawMessage payloads within entries/effects are immutable by convention, // so the slice headers are copied without cloning each payload's bytes. func cloneRecord(rec Record) Record { - out := Record{Step: rec.Step, Tick: rec.Tick, TickSteps: rec.TickSteps} + out := Record{Step: rec.Step, Tick: rec.Tick, TickSteps: rec.TickSteps, Format: rec.Format} if rec.Event != nil { out.Event = append([]byte(nil), rec.Event...) } @@ -406,5 +406,11 @@ func cloneRecord(rec Record) Record { if rec.Snapshot != nil { out.Snapshot = append([]byte(nil), rec.Snapshot...) } + if rec.EndedActors != nil { + out.EndedActors = &ActorSet{IDs: append([]string{}, rec.EndedActors.IDs...)} + } + if rec.UnstartedActors != nil { + out.UnstartedActors = &ActorSet{IDs: append([]string{}, rec.UnstartedActors.IDs...)} + } return out } diff --git a/durable/older_checkpoint_compound_test.go b/durable/older_checkpoint_compound_test.go new file mode 100644 index 00000000..f9882098 --- /dev/null +++ b/durable/older_checkpoint_compound_test.go @@ -0,0 +1,165 @@ +package durable_test + +import ( + "context" + "encoding/json" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// olderCheckpoint returns the store's latest checkpoint rewritten in the shape an +// older version wrote, with no journal format and no actor or service sets, in a new +// store, at the same step. +func olderCheckpoint(t *testing.T, store *durable.MemStore, id durable.InstanceID) *durable.MemStore { + t.Helper() + ctx := context.Background() + snap, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(tail) != 0 { + t.Fatalf("tail holds %d Records, want the checkpoint to cover every step", len(tail)) + } + step, ok, err := store.LastStep(ctx, id) + if err != nil || !ok { + t.Fatalf("LastStep = %d, %v, %v", step, ok, err) + } + var env map[string]json.RawMessage + if err = json.Unmarshal(snap, &env); err != nil { + t.Fatalf("decoding the checkpoint: %v", err) + } + for _, k := range []string{"format", "endedServices", "endedActors", "unstartedActors"} { + delete(env, k) + } + if snap, err = json.Marshal(env); err != nil { + t.Fatalf("encoding the checkpoint: %v", err) + } + older := durable.NewMemStore() + if err = older.Checkpoint(ctx, id, snap, step); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + return older +} + +// TestRecover_FromAnOlderCheckpointDoesNotRerunACompoundStatesSettledService pins that +// Recover from a checkpoint an older version wrote starts what that version would have: +// the active leaves' services, not a compound state's, which the older version never +// started and which, here, already settled into a child. The service doesn't run again. +func TestRecover_FromAnOlderCheckpointDoesNotRerunACompoundStatesSettledService(t *testing.T) { + ctx := context.Background() + runs := 0 + load := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { runs++; return "ok", nil } + m := state.ForgeFor[stepCtx]("olderCompound"). + Service("load", load). + State("idle"). + SuperState("outer").Invoke("load", state.WithInvokeOnDone("loaded")). + SubState("loading"). + SubState("ready"). + Initial("loading"). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("outer"). + Transition("loading").On("loaded").GoTo("ready"). + Transition("ready").On("poke").GoTo("ready"). + Quench() + opts := []stepOption{ + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("load", load)), + durable.WithCheckpointEvery[string, string, stepCtx](1), + } + store, id := durable.NewMemStore(), durable.InstanceID("older-compound") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + svcID := state.InvokeID("olderCompound", "outer", 0) + if _, ran, runErr := h.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v", ran, runErr) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + older := olderCheckpoint(t, store, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, runErr := recovered.RunService(ctx, svcID); ran || runErr != nil { + t.Fatalf("RunService after Recover from an older checkpoint = ran %v, %v (runs %d), want the settled compound service left alone", ran, runErr, runs) + } + // A step this version records on top, and the checkpoint it lands, keep it settled. + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + again, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if _, ran, runErr := again.RunService(ctx, svcID); ran || runErr != nil { + t.Fatalf("RunService after a second Recover = ran %v, %v (runs %d), want the service still settled", ran, runErr, runs) + } +} + +// TestRecover_FromAnOlderCheckpointDoesNotRespawnACompoundStatesSettledActor pins the +// same for a compound state's actor that finished into a child: Recover from an older +// checkpoint, which records no ended actors, doesn't spawn it again. +func TestRecover_FromAnOlderCheckpointDoesNotRespawnACompoundStatesSettledActor(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("olderCompoundActor"). + Actor("kid"). + State("idle"). + SuperState("outer").InvokeActor("kid", state.WithInvokeOnDone("kidDone"), state.WithInvokeID("kid")). + SubState("loading"). + SubState("ready"). + Initial("loading"). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("outer"). + Transition("loading").On("kidDone").GoTo("ready"). + Transition("ready").On("poke").GoTo("ready"). + Quench() + opts := []stepOption{ + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"kid": finishingChild()}), + durable.WithCheckpointEvery[string, string, stepCtx](1), + } + store, id := durable.NewMemStore(), durable.InstanceID("older-compound-actor") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + if ok, deliverErr := h.DeliverToActorByID(ctx, "kid", "finish"); !ok || deliverErr != nil { + t.Fatalf("DeliverToActorByID = %v, %v", ok, deliverErr) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("state = %q, want ready by the kid's onDone", got) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + older := olderCheckpoint(t, store, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, running := recovered.ActorRef("kid"); running { + t.Fatal("Recover from an older checkpoint spawned the compound state's kid again, which had finished") + } + // A step this version records on top, and the checkpoint it lands, keep it ended. + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + again, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if _, running := again.ActorRef("kid"); running { + t.Fatal("a second Recover spawned the finished kid again") + } +} diff --git a/durable/recover_ctx_respawn_test.go b/durable/recover_ctx_respawn_test.go new file mode 100644 index 00000000..12ca73e7 --- /dev/null +++ b/durable/recover_ctx_respawn_test.go @@ -0,0 +1,44 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestRecover_AContextThatEndsWhileARespawnRunsWithNoFireRefused pins that Recover, like +// Start, doesn't fail when its context ends while it spawns an actor and no parent Fire +// was refused: the actor's behavior already ran, and failing would make the caller's +// retry run it again. +func TestRecover_AContextThatEndsWhileARespawnRunsWithNoFireRefused(t *testing.T) { + ctx := context.Background() + m := spawnRuleMachine(false, nil) + store, id := durable.NewMemStore(), durable.InstanceID("recover-ctx") + calls := 0 + var cancel context.CancelFunc + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": func(in map[string]any) (state.ActorInstance, error) { + calls++ + if calls == 1 { + return nil, errors.New("the child can't start yet") + } + cancel() // the deadline passes as the retried spawn runs + return finishingChild()(in) + }, + })} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + turn, c := context.WithCancel(ctx) + cancel = c + if _, err = durable.Recover(turn, m, store, id, opts...); err != nil { + t.Fatalf("Recover = %v after the retried spawn ran (behavior ran %d times); want it to succeed, as Start does, so a retry doesn't run the behavior again", err, calls) + } +} diff --git a/durable/recover_respawn_failure_test.go b/durable/recover_respawn_failure_test.go new file mode 100644 index 00000000..aedc2ae8 --- /dev/null +++ b/durable/recover_respawn_failure_test.go @@ -0,0 +1,188 @@ +package durable_test + +// The Recover tests for a running actor whose respawn fails: the journal already holds +// every parent Fire its start drove, so it stays running in the journal, and a later +// Recover spawns it again quietly rather than as new. + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// flakyGreeterPalette binds a greeter that fails to start while *fail is set, and the +// finisher. +func flakyGreeterPalette(fail *bool, opts ...greetOption) []greetOption { + palette := durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { + if *fail { + return nil, errors.New("the greeter can't start yet") + } + return &greeter{}, nil + }, + "spawnChild": finishingChild(), + }) + return append([]greetOption{palette}, opts...) +} + +// TestRecover_ARunningActorWhoseRespawnFailsStaysRunning proves a greeter that was +// running, whose respawn fails at one or more Recovers with no onError to catch it, +// stays running in the journal, with and without checkpoints: the next Recover spawns +// it again without sending its hello, so the hello applies once. +func TestRecover_ARunningActorWhoseRespawnFailsStaysRunning(t *testing.T) { + ctx := context.Background() + for _, every := range []int{0, 1} { + for _, failures := range []int{1, 2} { + t.Run(fmt.Sprintf("every=%d/failures=%d", every, failures), func(t *testing.T) { + fail := false + var extra []greetOption + if every > 0 { + extra = append(extra, durable.WithCheckpointEvery[string, string, actorCtx](every)) + } + opts := flakyGreeterPalette(&fail, extra...) + m := greetMachine(false) + store, id := durable.NewMemStore(), durable.InstanceID("respawn-fails") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("greeting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + wantHellos(t, "live", h) + + fail = true + for round := 1; round <= failures; round++ { + failed, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d with the greeter failing: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d with the greeter failing", round), failed) + if _, err = failed.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } + + fail = false + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d with the greeter starting: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d with the greeter starting", round), recovered) + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after the greeter started again: %v", err) + } + } + }) + } + } +} + +// anyGreetMachine is greetMachine(false)'s greeting state for a machine whose events +// are interfaces, so its invoke's onError is nil rather than the zero event, and a +// failed spawn escalates with no parent Fire. +func anyGreetMachine() *state.Machine[string, any, actorCtx] { + return state.Forge[string, any, actorCtx]("anyGreet"). + Reducer("noteHello", func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, "hello") + return c + }). + Actor("greeter"). + State("greeting").InvokeActor("greeter"). + Initial("greeting"). + Transition("greeting").On("hello").GoTo("greeting").Assign("noteHello"). + Transition("greeting").On("poke").GoTo("greeting"). + Quench() +} + +// hellosAfterAFailedRespawn runs a greeter live in m's greeting, then Recovers on +// failCtx with the greeter's behavior returning fail's error, steps that Handle with +// poke when the Recover succeeds, and returns the hellos a last Recover, with the +// greeter starting, holds. +func hellosAfterAFailedRespawn[E comparable](t *testing.T, m *state.Machine[string, E, actorCtx], poke E, failCtx context.Context, fail func() error) int { + t.Helper() + ctx := context.Background() + failing := false + opts := []durable.Option[string, E, actorCtx]{durable.WithActorPalette[string, E, actorCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { + if failing { + return nil, fail() + } + return &greeter{}, nil + }, + })} + store, id := durable.NewMemStore(), durable.InstanceID("respawn-failure") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("greeting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, poke); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + + failing = true + if failed, recoverErr := durable.Recover(failCtx, m, store, id, opts...); recoverErr == nil { + // The Handle outlives the Recover's context: its next step journals what it holds. + if _, err = failed.Fire(ctx, poke); err != nil { + t.Fatalf("Fire(poke) after the failed respawn: %v", err) + } + } else if !errors.Is(recoverErr, failCtx.Err()) || failCtx.Err() == nil { + t.Fatalf("Recover with the greeter failing = %v, want success, or the error of its ended context", recoverErr) + } + + failing = false + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover with the greeter starting: %v", err) + } + hellos := 0 + for _, n := range recovered.Instance().Entity().Notes { + if n == "hello" { + hellos++ + } + } + return hellos +} + +// TestRecover_ARunningActorWhoseRespawnEscalatesStaysRunning proves a running greeter +// with no onError at all, whose failed respawn escalates and fires the parent nothing, +// stays running in the journal: the next Recover spawns it again without its hello. +func TestRecover_ARunningActorWhoseRespawnEscalatesStaysRunning(t *testing.T) { + transient := func() error { return errors.New("the greeter can't start yet") } + if got := hellosAfterAFailedRespawn(t, anyGreetMachine(), any("poke"), context.Background(), transient); got != 1 { + t.Fatalf("hellos = %d, want the live spawn's one", got) + } +} + +// TestRecover_ARunningActorWhoseRespawnAContextEndsStaysRunning proves a running greeter +// whose respawn fails because Recover's context ended, as a behavior that heeds its +// context reports, stays running in the journal: with the zero-event onError the +// Recover fails, and with none it succeeds, and either way the next Recover spawns the +// greeter again without its hello. +func TestRecover_ARunningActorWhoseRespawnAContextEndsStaysRunning(t *testing.T) { + ended := func() (context.Context, func() error) { + turn, cancel := context.WithCancel(context.Background()) + return turn, func() error { + cancel() // the deadline passes as the respawn runs + return turn.Err() + } + } + t.Run("zero-event onError", func(t *testing.T) { + turn, fail := ended() + if got := hellosAfterAFailedRespawn(t, greetMachine(false), "poke", turn, fail); got != 1 { + t.Fatalf("hellos = %d, want the live spawn's one", got) + } + }) + t.Run("no onError", func(t *testing.T) { + turn, fail := ended() + if got := hellosAfterAFailedRespawn(t, anyGreetMachine(), any("poke"), turn, fail); got != 1 { + t.Fatalf("hellos = %d, want the live spawn's one", got) + } + }) +} diff --git a/durable/recover_tail_ctx_test.go b/durable/recover_tail_ctx_test.go new file mode 100644 index 00000000..6f92ef99 --- /dev/null +++ b/durable/recover_tail_ctx_test.go @@ -0,0 +1,69 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestRecover_FailsWhenItsContextEndsDuringTheLastRecord pins that Recover fails when its +// context ends while it replays the journal's last Record, here a Tick that fires two +// timers whose first transition ends the context, so the kernel refuses the second: the +// recovered instance would otherwise be short of the journal with no error. +func TestRecover_FailsWhenItsContextEndsDuringTheLastRecord(t *testing.T) { + ctx := context.Background() + var cancel context.CancelFunc + m := state.ForgeFor[stepCtx]("tailCtx"). + Action("end", func(state.ActionCtx[stepCtx]) (state.Effect, error) { + if cancel != nil { + cancel() + } + return nil, nil + }). + State("idle"). + SuperState("both"). + Region("left"). + Initial("l1"). + SubState("l1"). + SubState("l2"). + EndRegion(). + Region("right"). + Initial("r1"). + SubState("r1"). + SubState("r2"). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("both"). + Transition("l1").After(time.Second).On("toL2").GoTo("l2").Do("end"). + Transition("r1").After(time.Second).On("toR2").GoTo("r2"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []stepOption{durable.WithRunnerClock[string, string, stepCtx](clk)} + store, id := durable.NewMemStore(), durable.InstanceID("tail-ctx") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + clk.Advance(2 * time.Second) + if fired, tickErr := h.Tick(ctx); tickErr != nil || len(fired) != 2 { + t.Fatalf("Tick fired %d, %v; want both timers", len(fired), tickErr) + } + turn, c := context.WithCancel(ctx) + cancel = c + recovered, err := durable.Recover(turn, m, store, id, opts...) + if !errors.Is(err, context.Canceled) { + got := "no Handle" + if recovered != nil { + got = recovered.Instance().Snapshot().Current + } + t.Fatalf("Recover = %v (state %v), want context.Canceled: the last Record's second timer was refused", err, got) + } +} diff --git a/durable/reentry_respawn_test.go b/durable/reentry_respawn_test.go new file mode 100644 index 00000000..1aff23ec --- /dev/null +++ b/durable/reentry_respawn_test.go @@ -0,0 +1,77 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// reentryGreeter is an actor that sends its parent "hello" as it starts. +type reentryGreeter struct{ sent bool } + +func (g *reentryGreeter) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (g *reentryGreeter) ChildEffects() []state.Effect { + if g.sent { + return nil + } + g.sent = true + return []state.Effect{state.SendParent{Event: "hello"}} +} +func (g *reentryGreeter) Output() any { return nil } + +// TestRecover_ARetriedReentrySpawnDoesNotRepeatTheFirstStartsMessage pins that when an +// actor started, sent its parent a message, and then failed to start again on a +// re-entry with no onError, Recover's retry doesn't apply that first message again: the +// journal already holds it, and a retry that still fails sends nothing. +func TestRecover_ARetriedReentrySpawnDoesNotRepeatTheFirstStartsMessage(t *testing.T) { + ctx := context.Background() + note := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, fmt.Sprint(in.Event)) + return c + } + m := state.ForgeFor[stepCtx]("reentryRespawn"). + Reducer("note", note). + Actor("greeter"). + State("greeting").InvokeActor("greeter"). + Initial("greeting"). + Transition("greeting").On("hello").GoTo("greeting").Assign("note"). + Transition("greeting").On("re").GoTo("greeting").Reenter().Assign("note"). + Transition("greeting").On("poke").GoTo("greeting").Assign("note"). + Quench() + var calls int + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { + calls++ + if calls > 1 { + return nil, errors.New("the greeter can't start again") + } + return &reentryGreeter{}, nil + }, + })} + store, id := durable.NewMemStore(), durable.InstanceID("reentry-respawn") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("greeting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for _, ev := range []string{"poke", "re", "poke"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire(%s): %v", ev, err) + } + } + live := fmt.Sprint(h.Instance().Entity().Notes) + if live != "[hello poke re poke]" { + t.Fatalf("live notes = %s, want the first start's hello, then poke, re and poke", live) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != live { + t.Fatalf("recovered notes = %s, want the live %s (behavior ran %d times)", got, live, calls) + } +} diff --git a/durable/respawn_nested_test.go b/durable/respawn_nested_test.go new file mode 100644 index 00000000..9f9ab866 --- /dev/null +++ b/durable/respawn_nested_test.go @@ -0,0 +1,166 @@ +package durable_test + +import ( + "context" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// starting is an actor that emits start from its initial entry, then keeps running. +type starting struct{ start []state.Effect } + +func (a *starting) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (a *starting) ChildEffects() []state.Effect { + out := a.start + a.start = nil + return out +} +func (a *starting) Output() any { return nil } + +// TestRecover_ANestedChildsStartFireAppliesOnce proves a parent Fire that a running +// actor's start drives through a nested child it spawns, the onError of a nested spawn +// that can't start or the onDone of one the actor ends at once, is journaled live and +// applied exactly once across repeated Recovers: Recover spawns the running actor again, +// and its nested child fails or settles again, but that parent Fire is part of the +// actor's start, which the journal already holds. +func TestRecover_ANestedChildsStartFireAppliesOnce(t *testing.T) { + ctx := context.Background() + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + m := state.ForgeFor[actorCtx]("nested"). + Reducer("noteNested", note("nested")). + Reducer("notePoke", note("poke")). + Actor("host"). + State("hosting").InvokeActor("host"). + Initial("hosting"). + Transition("hosting").On("nestedFailed").GoTo("hosting").Assign("noteNested"). + Transition("hosting").On("nestedDone").GoTo("hosting").Assign("noteNested"). + Transition("hosting").On("poke").GoTo("hosting").Assign("notePoke"). + Quench() + starts := map[string][]state.Effect{ + "fails": {state.SpawnActor{ID: "child", Src: state.Ref{Name: "broken"}, OnError: "nestedFailed"}}, + "settles": { + state.SpawnActor{ID: "child", Src: state.Ref{Name: "finisher"}, OnDone: "nestedDone"}, + state.SendTo{TargetID: "child", Event: "finish"}, + }, + } + for _, how := range []string{"fails", "settles"} { + t.Run(how, func(t *testing.T) { + opts := []greetOption{durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "host": func(map[string]any) (state.ActorInstance, error) { + return &starting{start: starts[how]}, nil + }, + "broken": failingSpawn(nil), + "finisher": finishingChild(), + })} + store, id := durable.NewMemStore(), durable.InstanceID("nested") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("hosting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + want := fmt.Sprint([]string{"nested", "poke"}) + if got := fmt.Sprint(h.Instance().Entity().Notes); got != want { + t.Fatalf("live notes = %s, want %s", got, want) + } + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != want { + t.Fatalf("Recover %d notes = %s, want %s: the nested child's parent Fire is part of the host's start", round, got, want) + } + } + }) + } +} + +// relay is an actor that sends its parent "pong" each time it's delivered "ping", and +// keeps running. +type relay struct{ out []state.Effect } + +func (r *relay) DeliverFire(_ context.Context, ev any) (bool, any) { + if ev == "ping" { + r.out = append(r.out, state.SendParent{Event: "pong"}) + } + return false, nil +} + +func (r *relay) ChildEffects() []state.Effect { + out := r.out + r.out = nil + return out +} +func (r *relay) Output() any { return nil } + +// TestRecover_DropsAPongLiveNeverSent proves Recover's respawn of the running actors, +// which follows the order the configuration declares them in, not the order they +// spawned live, can't apply a parent Fire live never did. Live, the pinger in the right +// region spawned first and pinged the relay as it started, but the relay, in the left +// region, wasn't running yet, so the ping went nowhere; the relay spawned later. Recover +// spawns the relay first, so the pinger's ping reaches it, and its pong is part of a +// running actor's start, which the parent doesn't hear. +func TestRecover_DropsAPongLiveNeverSent(t *testing.T) { + ctx := context.Background() + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + m := state.ForgeFor[actorCtx]("order"). + Reducer("notePong", note("pong")). + Actor("relay"). + Actor("pinger"). + SuperState("par"). + Region("left"). + Initial("l1"). + SubState("l1"). + SubState("l2").InvokeActor("relay", state.WithInvokeID("relay")). + EndRegion(). + Region("right"). + Initial("r1"). + SubState("r1").InvokeActor("pinger"). + EndRegion(). + EndSuperState(). + Initial("par"). + Transition("l1").On("go").GoTo("l2"). + Transition("par").On("pong").GoTo("par").Assign("notePong"). + Quench() + opts := []greetOption{durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "relay": func(map[string]any) (state.ActorInstance, error) { return &relay{}, nil }, + "pinger": func(map[string]any) (state.ActorInstance, error) { + return &starting{start: []state.Effect{state.SendTo{TargetID: "relay", Event: "ping"}}}, nil + }, + })} + store, id := durable.NewMemStore(), durable.InstanceID("order") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("par")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + if notes := h.Instance().Entity().Notes; len(notes) != 0 { + t.Fatalf("live notes = %v, want none: the relay wasn't running when the pinger pinged", notes) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if notes := recovered.Instance().Entity().Notes; len(notes) != 0 { + t.Fatalf("recovered notes = %v, want none: live never heard a pong", notes) + } +} diff --git a/durable/runner.go b/durable/runner.go index 6c4a71c5..7af0b366 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "reflect" + "slices" "sync" "time" @@ -40,20 +41,24 @@ import ( // deadline or testing dueness — is journaled and returned verbatim on recovery, // making timer-driven transitions durable and replay wall-clock-independent. // -// Invoked services are the second recorded seam: a service runs exactly once on -// the live path (Handle.RunService, against the registry supplied with -// WithServiceRegistry) and its result is journaled as a JournalServiceResult; on -// recovery the recorded result is replayed back through the kernel's settle seam, -// so the service is never re-invoked and the same onDone / onError event re-fires -// with the same data. +// Invoked services are the second recorded seam: a service runs on the live path +// (Handle.RunService, against the registry supplied with WithServiceRegistry) and its +// result is journaled as a JournalServiceResult; on recovery the recorded result is +// replayed back through the kernel's settle seam, so that service is never re-invoked +// and the same onDone / onError event re-fires with the same data. A result that wasn't +// recorded has nothing to replay, so the service runs again when the host calls +// RunService. // // Child-machine actors are the third recorded seam: an actor's behavior runs -// exactly once on the live path (Handle.DeliverToActor, against the palette +// on the live path (Handle.DeliverToActor, against the palette // supplied with WithActorPalette) and each parent transition the delivery drives — // the actor's onDone / onError, or a message it sends — is journaled as a // JournalActorMessage; on recovery the recorded transition is replayed by re-firing // the parent directly with the recorded done-data, so the actor behavior is never -// re-instantiated. A purely event-driven machine records no Entries. +// re-instantiated. A Fire's or RunService's Record also journals the settles and +// failed spawns' onErrors its absorb drove, replayed after its own work, and the step +// after Start or Recover journals the ones their spawns drove, replayed first. A +// purely event-driven machine records no Entries. type Runner[S comparable, E comparable, C any] struct { machine *state.Machine[S, E, C] store Store @@ -102,12 +107,15 @@ func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st // Handle, so it isn't serialized with this one. // // A step that applied to the kernel but may not have been recorded leaves the Handle out -// of step with the journal. That call and every later one return ErrHandleFailed, -// wrapping the cause, which can be a context that ended during the Store write. Before -// recovering, call Drain: a step on another goroutine may still be recording, which a -// recovered Handle wouldn't load, or sending an effect, which it would send again. Recovering a healthy Handle's instance -// instead needs this Handle's calls to have returned first. Recover a new Handle with the same -// options to continue. A service +// of step with the journal, and so does one that panicked in host code; the panic +// reaches the caller after the Handle fails. So does a Tick, RunService or DeliverToActor whose context +// ended during the step, and any step, Fire included, that drove a Fire refused because +// a context ended, the caller's or one middleware derived from it. That call and every later one return ErrHandleFailed, wrapping the cause, +// which can be a context that ended during the Store write. Before recovering, call +// Drain: a step on another goroutine may still be recording, which a recovered Handle +// wouldn't load, or sending an effect, which it would send again. Recovering a healthy +// Handle's instance instead needs this Handle's calls to have returned first. Recover a +// new Handle with the same options to continue. A service // whose result wasn't recorded is in flight again, so RunService runs it a second time. // A running InvokeActor actor restarts from its initial state on any Recover, losing every // delivery so far, and a Spawn actor doesn't return. If the cause is ErrFenced, a @@ -128,9 +136,20 @@ type Handle[S comparable, E comparable, C any] struct { svc *state.ServiceRunner[S, E, C] // host driver for invoked services, nil when none wired svcBuf *[]state.JournalEntry // recording service-result accumulator, flushed per step - - actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired - actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step + // settled holds the services that settled in the current activation of the state + // that declares them, so a checkpoint records them and Recover doesn't start them. + settled map[string]bool + + actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired + ended recordedSet // the ended actors the journal last recorded + unstarted recordedSet // the unstarted actors the journal last recorded + seen map[string]bool // declared actors seen running, so a stopped one counts as ended + // respawnFailed holds the declared actors that aren't running because a respawn of + // them failed: the journal holds their start, so they stay out of the unstarted set. + respawnFailed map[string]bool + sets actorSetsCache[S] // the last actorSets result, reused while nothing it reads changed + pending []state.ParentFire[S] // parent Fires Start's or Recover's spawns drove, journaled with the next step + actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step out outbox // what a step leaves behind once it releases the step lock } @@ -333,6 +352,7 @@ func (h *Handle[S, E, C]) drainClock() []state.JournalEntry { // effects is a no-op when that driver is not wired or the effects name none of its // kind. func (h *Handle[S, E, C]) absorbDrivers(ctx context.Context, effects []state.Effect) { + forgetSettled(h.settled, effects) // Arm or cancel timers only when the effects actually schedule or cancel one: the // kernel Scheduler reads the clock unconditionally on Absorb, so skipping the call // for a timer-free transition keeps a non-timer machine free of clock reads. @@ -343,10 +363,27 @@ func (h *Handle[S, E, C]) absorbDrivers(ctx context.Context, effects []state.Eff h.svc.Absorb(ctx, effects) } if h.actors != nil { + h.actorFires.attempt(effects) + defer h.actorFires.driving(ctx)() h.actors.Absorb(ctx, effects) } } +// absorbParentFire arms or cancels the timers and services a parent Fire the actor +// system drove declares, which the system itself leaves alone: the state an actor's +// onDone, onError or message enters runs its timers and services, as one a Fire enters +// does. Replay arms them the same way, in the same order, so the clock reads match. ctx +// is the context of the step that drove the system. +func (h *Handle[S, E, C]) absorbParentFire(ctx context.Context, effects []state.Effect) { + forgetSettled(h.settled, effects) + if hasTimerEffect(effects) { + h.absorbTimers(ctx, effects) + } + if h.svc != nil { + h.svc.Absorb(ctx, effects) + } +} + // absorbTimers arms or cancels the step's delayed (`after`) timers on the kernel // scheduler and mirrors the same arming into the Handle's own timer table, so each // armed timer's absolute deadline is available to persist at a checkpoint. It must @@ -396,47 +433,27 @@ func (h *Handle[S, E, C]) armNow(before int) time.Time { return h.runner.cfg.clock.Now() } -// armTimersFrom mirrors the ScheduleAfter/CancelScheduled effects a chained timer -// transition emitted into the Handle's timer table at the tick instant now, so a -// timer a fired transition re-armed (the next link in an `after` chain) is tracked -// for the next checkpoint. It is the Tick-side analog of absorbTimers, sharing the -// tick's single recorded instant rather than reading the clock again. -func (h *Handle[S, E, C]) armTimersFrom(effects []state.Effect, now time.Time) { - for _, eff := range effects { - switch e := eff.(type) { - case state.ScheduleAfter: - if h.timers == nil { - h.timers = map[string]pendingTimer{} - } - h.timers[e.ID] = pendingTimer{id: e.ID, due: now.Add(e.Delay), event: e.Event} - case state.CancelScheduled: - delete(h.timers, e.ID) +// dropUnscheduled removes from timers each one sched no longer holds. +func dropUnscheduled[S comparable, E comparable, C any](timers map[string]pendingTimer, sched *state.Scheduler[S, E, C]) { + for id := range timers { + if !sched.HasPending(id) { + delete(timers, id) } } } -// tickInstant returns the single clock instant a tick's recorded reads share (the -// FakeClock does not advance within a tick; a SystemClock's intra-tick drift is -// sub-timer). It reads the first recorded JournalClockRead. ok is false when the -// tick recorded no clock read (it fired nothing), so the caller skips reconciliation. -func tickInstant(entries []state.JournalEntry) (time.Time, bool) { - for _, e := range entries { - if e.Kind == state.JournalClockRead { - return time.Unix(0, e.ClockUnixNano).UTC(), true - } +// forgetSettled removes from settled each service effects start or stop: a state that +// declares it was entered or exited, so the service is new or gone. +func forgetSettled(settled map[string]bool, effects []state.Effect) { + if len(settled) == 0 { + return } - return time.Time{}, false -} - -// dropFiredTimers removes from the Handle's timer table the timers a Tick fired, so -// a checkpoint taken after the tick does not persist an already-fired timer. The -// scheduler removes a due timer before re-firing it; the Handle mirrors that by -// dropping every timer whose deadline is at or before now, matching the scheduler's -// dueLocked selection. -func (h *Handle[S, E, C]) dropFiredTimers(now time.Time) { - for id, pt := range h.timers { - if !pt.due.After(now) { - delete(h.timers, id) + for _, eff := range effects { + switch e := eff.(type) { + case state.StartService: + delete(settled, e.ID) + case state.StopService: + delete(settled, e.ID) } } } @@ -475,6 +492,12 @@ func (h *Handle[S, E, C]) ID() InstanceID { return h.id } // state.WithInitialState) configure the initial configuration. Starting an // InstanceID that already exists in the Store reports ErrInstanceExists rather // than clobbering its recorded baseline. +// +// If a context ending (ctx's, or one middleware derived from it) refuses a parent Fire +// an initial actor drove, such as a failed spawn's onError, Start returns an error +// wrapping the context's error and no Handle. The baseline is recorded by then, so +// Recover the instance rather than Start it again. A ctx that ends with no Fire refused +// doesn't fail Start. func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opts ...state.CastOption[S]) (*Handle[S, E, C], error) { if _, _, err := r.store.Load(ctx, id); err == nil { return nil, fmt.Errorf("%w: %q", ErrInstanceExists, id) @@ -505,7 +528,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt } // Wrap the baseline snapshot in a checkpoint envelope (no timers armed yet) so // every checkpoint a recover loads carries the same durable envelope shape. - baseEnv, err := marshalCheckpoint(snap, nil, 0) + baseEnv, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap, Format: journalFormat}, nil) if err != nil { return nil, fmt.Errorf("durable: marshaling start checkpoint envelope for %q: %w", id, err) } @@ -518,38 +541,61 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // the first RunService. The service buffer journals each settled outcome for // replay. A machine with no service registry wired runs no services and records // no service entries. + starts := inst.StartEffects() svcBuf := make([]state.JournalEntry, 0) svc := r.newServiceRunner(inst) if svc != nil { - svc.Absorb(ctx, inst.StartEffects()) + svc.Absorb(ctx, starts) } // Install the child-machine actor host driver and spawn the initial // configuration's actors, so an actor declared on the very first state is running // before the first DeliverToActor. The actor buffer journals each parent // transition a delivery drives for replay. A machine with no actor palette wired - // spawns no actor and records no actor entries. - actorBuf := make([]state.JournalEntry, 0) - actors := r.newActorSystem(inst) + // spawns no actor and records no actor entries. A parent Fire a starting actor + // drives arms its state's timers and services on the Handle's drivers. + actors, actorFires := r.newActorSystem(inst) + h := &Handle[S, E, C]{ + runner: r, + id: id, + inst: inst, + nextStep: 0, + sched: state.NewScheduler(inst), + recClock: recClock, + timers: map[string]pendingTimer{}, + svc: svc, + svcBuf: &svcBuf, + actors: actors, + actorFires: actorFires, + lock: make(chan struct{}, 1), + out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, + } if actors != nil { - actors.Absorb(ctx, inst.StartEffects()) - } - - return &Handle[S, E, C]{ - runner: r, - id: id, - inst: inst, - nextStep: 0, - sched: state.NewScheduler(inst), - recClock: recClock, - timers: map[string]pendingTimer{}, - svc: svc, - svcBuf: &svcBuf, - actors: actors, - actorBuf: &actorBuf, - lock: make(chan struct{}, 1), - out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, - }, nil + actorFires.arm = h.absorbParentFire + actorFires.attempt(starts) + func() { + defer actorFires.driving(ctx)() + actors.Absorb(ctx, starts) + }() + } + // A parent Fire a starting actor drove (a message it sent as it started, or a failed + // spawn's onError) applied to the instance after its baseline, so the first step + // journals it, ahead of its own work. One a context's ending refused never applied, + // and replaying it under a live context would apply it, so Start fails: Recover + // starts from the baseline. A context that ended with no Fire refused cost nothing. + startFires := actorFires.take() + if refused := refusedByContext(parentFireErrs(startFires)...); refused != nil { + return nil, fmt.Errorf("durable: starting %q: %w", id, refused) + } + // The actors that started are seen running, so one later stopped counts as ended. + h.seen = map[string]bool{} + if actors != nil { + for _, id := range actors.IDs() { + h.seen[id] = true + } + } + h.pending = startFires + return h, nil } // newServiceRunner builds the kernel host driver for invoked services bound to @@ -563,17 +609,185 @@ func (r *Runner[S, E, C]) newServiceRunner(inst *state.Instance[S, E, C]) *state } // newActorSystem builds the kernel host driver for child-machine actors bound to -// inst, registering each behavior in the configured palette, or nil when no actor -// palette was wired (a machine that spawns no actor needs none). -func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) *state.ActorSystem[S, E, C] { +// inst, registering each behavior in the configured palette, and the collector of the +// parent Fires it drives. Both are nil when no actor palette was wired (a machine +// that spawns no actor needs none). +func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) (*state.ActorSystem[S, E, C], *parentFires[S]) { if len(r.cfg.actorPalette) == 0 { - return nil + return nil, nil } - sys := state.NewActorSystem(inst) + fires := &parentFires[S]{} + sys := state.NewActorSystem(inst).WithParentFireObserver(fires.note). + WithActorInspector(state.InspectorFunc(fires.inspect)) for src, behavior := range r.cfg.actorPalette { sys.Register(src, behavior) } - return sys + return sys, fires +} + +// parentFires collects the parent Fires an actor system drives, so the step that drove +// them can check and record them, and the actors it spawned, so an actor spawned and +// stopped inside one step still counts as having run. +type parentFires[S comparable] struct { + // arm, when set, arms the timers and services a parent Fire's effects declare, as a + // host Fire's absorb does: the actor system handles only their actors. It's set + // before any spawn and runs on the goroutine driving the system, with the context + // driving names. + arm func(ctx context.Context, effects []state.Effect) + + mu sync.Mutex + ctx context.Context // the context of the step driving the system, for arm + fires []state.ParentFire[S] + spawned map[string]bool // actors whose latest spawn this step started + attempted map[string]bool // actors the system was asked to spawn this step + failed map[string]bool // actors whose latest spawn failed and whose declared onError applied, or was refused for a reason other than a context ending + respawned map[string]bool // actors whose latest spawn was a respawn of one running at the journal's end, whose start the journal holds +} + +// actorLifecycle is what a step did to the actors: the ones it asked the system to +// spawn, and of those, the ones that started, failed with an onError the journal holds, +// or were respawned, so the journal already holds their start. +type actorLifecycle struct { + spawned, attempted, failed, respawned map[string]bool +} + +// empty reports whether the step did nothing to the actors. +func (l actorLifecycle) empty() bool { + return len(l.attempted) == 0 && len(l.spawned) == 0 && len(l.failed) == 0 && len(l.respawned) == 0 +} + +// attempt notes the actors effects ask the system to spawn. +func (p *parentFires[S]) attempt(effects []state.Effect) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok { + if p.attempted == nil { + p.attempted = map[string]bool{} + } + p.attempted[sp.ID] = true + // The latest attempt decides: until it starts, the actor hasn't run again. + delete(p.spawned, sp.ID) + delete(p.failed, sp.ID) + delete(p.respawned, sp.ID) + } + } +} + +// respawning notes the actors effects respawn: each was running at the journal's end, +// so the journal holds every parent Fire its start drove, even if this spawn fails. +// Call it after attempt, which forgets the mark. It's safe on a nil collector. +func (p *parentFires[S]) respawning(effects []state.Effect) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok { + if p.respawned == nil { + p.respawned = map[string]bool{} + } + p.respawned[sp.ID] = true + } + } +} + +// takeLifecycle returns what the steps since the last call did to the actors, and +// forgets it. It's safe on a nil collector, which has none. +func (p *parentFires[S]) takeLifecycle() actorLifecycle { + if p == nil { + return actorLifecycle{} + } + p.mu.Lock() + defer p.mu.Unlock() + lc := actorLifecycle{spawned: p.spawned, attempted: p.attempted, failed: p.failed, respawned: p.respawned} + p.spawned, p.attempted, p.failed, p.respawned = nil, nil, nil, nil + return lc +} + +// inspect notes each actor the system spawned. The system reports a spawn only once +// the actor started, so a spawn that failed isn't noted. +func (p *parentFires[S]) inspect(ev state.InspectionEvent) { + if ev.Kind != state.InspectActor || ev.ActorPhase != state.ActorSpawned { + return + } + p.mu.Lock() + if p.spawned == nil { + p.spawned = map[string]bool{} + } + p.spawned[ev.ActorID] = true + p.mu.Unlock() +} + +func (p *parentFires[S]) note(pf state.ParentFire[S]) { + p.mu.Lock() + p.fires = append(p.fires, pf) + // A spawn whose onError applied, or was refused for a reason other than a context + // ending, such as a failing guard, is handled: the journal holds the onError or its + // refusal, and a retry would run the behavior again. One a context's ending refused + // isn't: the step that drove it recorded nothing. Nor is one the parent had no + // transition for: an invoked actor with no onError declared routes the zero event, + // which the parent refuses that way, and nothing caught the failure. Telling the two + // apart by a no-transition refusal is a stopgap; see #250. + if pf.SpawnFailed && !isContextErr(pf.Result.Err) && !errors.Is(pf.Result.Err, state.ErrNoTransition) { + if p.failed == nil { + p.failed = map[string]bool{} + } + p.failed[pf.ActorID] = true + } + ctx := p.ctx + p.mu.Unlock() + if p.arm != nil { + if ctx == nil { + ctx = context.Background() + } + p.arm(ctx, pf.Result.Effects) + } + // The system absorbs a parent Fire's effects next, which spawns what they declare. + p.attempt(pf.Result.Effects) +} + +// driving notes ctx as the context of the step about to drive the system, so arm gets +// it, and returns the func that restores the one before. It's safe on a nil collector. +func (p *parentFires[S]) driving(ctx context.Context) (restore func()) { + if p == nil { + return func() {} + } + p.mu.Lock() + prev := p.ctx + p.ctx = ctx + p.mu.Unlock() + return func() { + p.mu.Lock() + p.ctx = prev + p.mu.Unlock() + } +} + +// take returns the Fires noted since the last take, in fire order, and forgets them. +// It's safe on a nil collector, which has none. +func (p *parentFires[S]) take() []state.ParentFire[S] { + if p == nil { + return nil + } + p.mu.Lock() + defer p.mu.Unlock() + fires := p.fires + p.fires = nil + return fires +} + +// parentFireErrs returns each parent Fire's error, nil ones included. +func parentFireErrs[S comparable](fires []state.ParentFire[S]) []error { + errs := make([]error, len(fires)) + for i := range fires { + errs[i] = fires[i].Result.Err + } + return errs } // Fire drives one event through a durable instance identified by id, loading and @@ -603,6 +817,17 @@ func (r *Runner[S, E, C]) Fire(ctx context.Context, id InstanceID, event E, opts // goroutine failed the Handle while this step was recording, Fire returns // ErrHandleFailed saying the step was recorded; Recover sends its effects. // +// A Fire the kernel refuses, because ctx ended or for any other reason, returns that +// error, records nothing and leaves the Handle usable. When the event applies, an actor +// the step spawned can fail and route its onError through the instance; if a context +// ending, ctx or one derived from it, refuses that onError, Fire fails the Handle with +// ErrHandleFailed and records nothing, though the event applied. Recover restores the +// state from before the event, so fire it again on the recovered Handle, and don't act +// on the result Fire returned with that error. A Fire that drove no Fire a context +// refused records, even if ctx ends after the kernel applied it. A panic in host code +// during the step fails the Handle, then reaches the caller: recover it, then Drain +// and Recover as for ErrHandleFailed. +// // A state.WithEventData payload reaches the transition's Assign as the Runner's // EventDataDecoder rebuilds it from the payload's JSON form, live and on replay alike, so // both see the same value. Decode it as the type the caller passed: a payload that @@ -630,10 +855,11 @@ func (h *Handle[S, E, C]) Fire(ctx context.Context, event E, opts ...state.FireO return res, h.finishStep(ctx, rec, des) } -// lockedFireStep runs fireStep and releases the step lock however it returns, a panic -// in host code included. +// lockedFireStep runs fireStep and releases the step lock however it returns. A panic +// in host code fails the Handle first, since the kernel may have applied the event. func (h *Handle[S, E, C]) lockedFireStep(ctx context.Context, event E, opts []state.FireOption) (state.FireResult[S], *Record, []dispatchableEffect, error) { defer h.release() + defer h.failOnPanic() return h.fireStep(h.stepContext(ctx), event, opts) } @@ -662,6 +888,23 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi // timer, and each driver must see its effects. h.absorbDrivers(ctx, res.Effects) + // An actor the absorb spawned can fail and route its onError through the parent. + // A context that ended can refuse that Fire, so live never applied it, and + // journaling this step would let Recover re-spawn the actor under a live context, + // where the onError applies. Record nothing. A Fire that drove no Fire a context refused + // applied whole, so it records even when ctx ended afterward. + fires := h.actorFires.take() + if refused := refusedByContext(parentFireErrs(fires)...); refused != nil { + return res, nil, nil, h.fail(fmt.Errorf("durable: firing %q: %w", h.id, refused)) + } + // Every parent Fire the absorb drove (a message an actor sent as it spawned, a + // settle, a failed spawn's onError) applied after the event, so the step journals + // them, and replay re-fires them after it. + driven, err := recordParentFires(fires, false) + if err != nil { + return res, nil, nil, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) + } + step := h.nextStep // Stamp this step's domain effects with their deterministic ids and carry them // in the Record so the write-ahead append durably names every effect that must @@ -671,7 +914,7 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi if err != nil { return res, nil, nil, h.fail(err) } - rec := &Record{Step: step, Event: []byte(res.Trace.EventPayload), EventData: payload.data, EventDataError: payload.errMsg, Entries: h.drainClock(), Effects: effEnvs} + rec := &Record{Step: step, Event: []byte(res.Trace.EventPayload), EventData: payload.data, EventDataError: payload.errMsg, Entries: append(h.drainClock(), driven...), Effects: effEnvs} if err := h.appendStep(ctx, step, rec); err != nil { return res, nil, nil, h.fail(err) } @@ -739,30 +982,49 @@ func (h *Handle[S, E, C]) dispatchGuarded(ctx context.Context, step int, des []d // recorded instants. It returns the FireResults of the timers it fired, in order. A // failed checkpoint returns them with that error, and the Handle carries on. If another // goroutine failed the Handle while this step was recording, it returns them with -// ErrHandleFailed saying the step was recorded. +// ErrHandleFailed saying the step was recorded. If ctx ends during the Tick, or a +// context derived from it (by middleware, say) refuses a timer's Fire, it fails the +// Handle with ErrHandleFailed and records nothing, even for timers that applied: the +// results it returns weren't recorded, so don't act on their effects; a recovered +// Handle re-arms those timers and fires them again. A timer's Fire refused for another +// reason, such as a failing guard, is recorded, and replay meets the same refusal. func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], error) { if err := h.acquire(ctx); err != nil { return nil, err } defer h.release() + defer h.failOnPanic() if err := h.refuse(ctx); err != nil { return nil, err } results := h.sched.Tick(h.stepContext(ctx)) + // A context that ended partway can make the kernel refuse a due timer's Fire after + // the scheduler consumed it. Journaling that would commit on recovery what live never + // applied, so record nothing: Recover re-arms the timers. + // A tick that fired no timer consumed nothing, so an ended ctx can't have cost it + // anything: it records as usual. + if err := consumedCanceled(ctx, len(results) > 0, append(resultErrs(results), parentFireErrs(h.actorFires.take())...)...); err != nil { + return results, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, err)) + } step := h.nextStep rec := Record{Step: step, Tick: true, TickSteps: len(results), Entries: h.drainClock()} - // Reconcile the Handle's timer table with the tick: drop the timers it fired and - // arm any a chained transition scheduled, so a checkpoint after the tick persists - // exactly the still-pending deadlines. The clock does not advance within one tick - // (a FakeClock advances only between ticks; a SystemClock's intra-tick drift is - // sub-timer), so the tick's recorded reads share one instant: use it for both the - // drop (timers due at or before it fired) and any chained re-arm. - if now, ok := tickInstant(rec.Entries); ok { - h.dropFiredTimers(now) - for i := range results { - h.armTimersFrom(results[i].Effects, now) + // Reconcile the Handle's timer table with the tick: arm any timer a chained + // transition scheduled, then drop the ones the tick fired, by id, so a checkpoint + // after the tick persists exactly the still-pending deadlines. A chained timer's + // deadline is the one the scheduler holds, as replay's is. + for i := range results { + if h.timers == nil { + h.timers = map[string]pendingTimer{} } + mirrorScheduled(h.timers, h.sched, results[i].Effects) + forgetSettled(h.settled, results[i].Effects) + } + if len(results) > 0 { + // Drop from the table the timers the tick fired, the ones the scheduler no longer + // holds: one that came due between the tick's reads, and a chained one it armed + // and fired, so a checkpoint after the tick doesn't persist a fired timer. + dropUnscheduled(h.timers, h.sched) } // A tick that read no clock and fired nothing records nothing: there is no // nondeterminism to journal and no step was produced. @@ -863,6 +1125,16 @@ func (h *Handle[S, E, C]) checkpointDue(step int) bool { // dispatch leaves the effect recoverable from the still-present tail rather than // orphaned behind the compaction. func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) error { + ended, unstarted := h.actorSets() + held := len(h.pending) + if held > 0 { + before, err := recordParentFires(h.pending, true) + if err != nil { + return fmt.Errorf("durable: recording step %d for %q: %w", step, h.id, err) + } + // They ran before the step's own work, so they come first. + rec.Entries = append(before, rec.Entries...) + } if h.checkpointDue(step) { snap, err := state.MarshalSnapshot(h.inst.Snapshot()) if err != nil { @@ -871,24 +1143,213 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // Wrap the kernel snapshot with the absolute deadlines of the timers armed at // this checkpoint, so a recovery whose compacted tail no longer carries their // arming ScheduleAfter can re-arm them at their recorded instants. - env, err := marshalCheckpoint(snap, h.timers, rec.followingStep()) + env, err := marshalCheckpoint(checkpointEnvelope{ + Snapshot: snap, + NextStep: rec.followingStep(), + EndedActors: ended, + UnstartedActors: unstarted, + EndedServices: h.endedServices(), + Format: journalFormat, + }, h.timers) if err != nil { return fmt.Errorf("durable: marshaling checkpoint envelope at step %d for %q: %w", step, h.id, err) } rec.Snapshot = env } + rec.Format = journalFormat + if h.ended.changedBy(ended) { + rec.EndedActors = ended + } + if h.unstarted.changedBy(unstarted) { + rec.UnstartedActors = unstarted + } if _, err := h.runner.store.Append(ctx, h.id, *rec, WithFence(h.runner.cfg.fence)); err != nil { return fmt.Errorf("durable: recording step %d for %q: %w", step, h.id, err) } + h.ended.note(ended) + h.unstarted.note(unstarted) + h.pending = h.pending[held:] return nil } +// recordedSet is an actor set the journal records when a step changes it. +type recordedSet struct { + ids []string // the set the journal last recorded + set bool // whether ids holds a recorded set +} + +// changedBy reports whether now differs from the set the journal last recorded, so the +// step records it. A nil now records nothing. +func (r *recordedSet) changedBy(now *ActorSet) bool { + return now != nil && (!r.set || !slices.Equal(now.IDs, r.ids)) +} + +// note remembers now as recorded, once the step that carries it is appended. +func (r *recordedSet) note(now *ActorSet) { + if now != nil { + r.ids, r.set = now.IDs, true + } +} + +// actorSets returns the actors the instance's state declares that ran and have ended, +// and those that aren't running and haven't ended, and remembers them for the next +// step. A declared actor that isn't running has ended when it settled (the actor system +// keeps a settled actor), or when this step asked the system to spawn it and the latest +// of those spawns started it (then something stopped it), or, when this step didn't try +// to spawn it, when it was running or ended at the previous step. A spawn whose onError +// applied, or whose onError was refused for a reason other than a context ending, +// also counts as ended, since the journal holds that onError, or the refusal replay +// meets again. So an actor whose spawn failed with no onError declared, or whose +// onError a context's ending refused, which left the step that drove it recording +// nothing, hasn't ended: it's unstarted, and Recover tries it again. One whose +// respawn of a running actor failed is in neither set, as it was while running, until +// a later spawn of it: the journal holds its start, so Recover respawns it again. Both +// are nil with no actor palette. +func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { + if h.actors == nil { + return nil, nil + } + lc := h.actorFires.takeLifecycle() + running := h.actors.IDs() + // The sets depend on the declared actors, so on the configuration, on which are + // running, and on this step's spawns. A step that changed none of them, as most + // steps that touch no actor don't, gets the last result back. + config := h.inst.Configuration() + if h.sets.valid && lc.empty() && + slices.Equal(config, h.sets.config) && slices.Equal(running, h.sets.running) { + return h.sets.ended, h.sets.unstarted + } + defer func() { + h.sets = actorSetsCache[S]{valid: true, config: config, running: running, ended: ended, unstarted: unstarted} + }() + endedIDs, unstartedIDs := []string{}, []string{} + respawnFailed := map[string]bool{} + for _, id := range declaredActors(h.inst.StartEffects()) { + if slices.Contains(running, id) { + continue + } + _, ran := h.actors.Ref(id) + journaled := false // whether the journal holds its start though it isn't running + switch { + case ran: + case lc.attempted[id]: + ran = lc.spawned[id] || lc.failed[id] + journaled = lc.respawned[id] + default: + ran = h.seen[id] + journaled = h.respawnFailed[id] + } + switch { + case ran: + endedIDs = append(endedIDs, id) + case journaled: + // Its respawn failed, but the journal holds its start: it's in neither set, + // as when it was running, so Recover respawns it again rather than as new. + respawnFailed[id] = true + default: + unstartedIDs = append(unstartedIDs, id) + } + } + h.respawnFailed = respawnFailed + slices.Sort(endedIDs) + endedIDs = slices.Compact(endedIDs) + slices.Sort(unstartedIDs) + unstartedIDs = slices.Compact(unstartedIDs) + h.seen = map[string]bool{} + for _, id := range append(running, endedIDs...) { + h.seen[id] = true + } + return &ActorSet{IDs: endedIDs}, &ActorSet{IDs: unstartedIDs} +} + +// actorSetsCache is the last result actorSets computed, with what it read: the +// configuration and the running actors. +type actorSetsCache[S comparable] struct { + valid bool + config []S + running []string + ended, unstarted *ActorSet +} + +// endedServices returns the invoked services the active states declare that settled +// while the state that declares them stayed active, sorted. A declared service that +// isn't in flight but never settled, such as one a Tick's timer entered, which a Tick +// doesn't start, isn't one: Recover starts it. It is nil with no service registry. +func (h *Handle[S, E, C]) endedServices() []string { + if h.svc == nil || len(h.settled) == 0 { + return nil + } + var ids []string + for _, eff := range h.inst.StartEffects() { + if sv, ok := eff.(state.StartService); ok && h.settled[sv.ID] { + ids = append(ids, sv.ID) + } + } + slices.Sort(ids) + return slices.Compact(ids) +} + +// declaredActors returns the ids of the actors effects spawn. +func declaredActors(effects []state.Effect) []string { + var ids []string + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok { + ids = append(ids, sp.ID) + } + } + return ids +} + +// startsExcept returns effects without the starts of kind T (a SpawnActor or a +// StartService) whose id, as id reads it, ids holds. Recover uses it so it doesn't +// spawn an actor the live run had ended, or start a service that settled while its +// state stayed active. The kind matters: an explicit invoke id can name both an actor +// and a service. With no ids it returns effects unchanged. +func startsExcept[T state.Effect](effects []state.Effect, ids []string, id func(T) string) []state.Effect { + if len(ids) == 0 { + return effects + } + out := make([]state.Effect, 0, len(effects)) + for _, eff := range effects { + if start, ok := eff.(T); ok && slices.Contains(ids, id(start)) { + continue + } + out = append(out, eff) + } + return out +} + +// respawn spawns the actors effects declare. With a recorded unstarted set, an actor it +// leaves out was running, and the journal holds every parent Fire its start drove, so it +// spawns without letting its start reach the parent. An unstarted actor, or any actor +// when the journal recorded no set, spawns as new. The running actors spawn first, in +// order, then the rest: a message a new actor sends the parent can enter a state that +// spawns a running actor, which must already be running, or its start would reach the +// parent a second time. It notes the running ones on fires, so one whose spawn fails +// still counts as having started. +func respawn[S comparable, E comparable, C any](ctx context.Context, actors *state.ActorSystem[S, E, C], fires *parentFires[S], effects []state.Effect, unstarted *ActorSet) { + var running, fresh []state.Effect + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok && unstarted != nil && !slices.Contains(unstarted.IDs, sp.ID) { + running = append(running, eff) + continue + } + fresh = append(fresh, eff) + } + fires.respawning(running) + actors.AbsorbRespawn(ctx, running) + actors.Absorb(ctx, fresh) +} + // Recover reconstructs a durable instance purely from the Store: it loads the // latest checkpoint Snapshot and the journal/effect tail after it, Restores the // snapshot (firing nothing, no IO), and replays the tail's recorded driving // events through the kernel to reach the instance's live state. The returned // Handle continues recording subsequent Fires. Recover reports ErrInstanceNotFound -// for an instance that was never started. +// for an instance that was never started, and the context's error if ctx ends before +// the journal is replayed, or a context's ending refuses a parent Fire an actor it +// spawned drove. A ctx that ends once the actors are spawned, with no Fire refused, +// doesn't fail it, as for Start: their behaviors already ran. func Recover[S comparable, E comparable, C any](ctx context.Context, m *state.Machine[S, E, C], st Store, id InstanceID, opts ...Option[S, E, C]) (*Handle[S, E, C], error) { r := NewRunner(m, st, opts...) return r.recover(ctx, id) @@ -910,10 +1371,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // Unwrap the durable checkpoint envelope: the kernel snapshot bytes, the absolute // deadlines of the timers armed at the checkpoint, and the next step ordinal. A bare // (pre-envelope) checkpoint yields the snapshot with no persisted timers. - kernelSnap, persistedTimers, checkpointNext, err := unmarshalCheckpoint(snapBytes) - if err != nil { - return nil, fmt.Errorf("durable: unmarshaling checkpoint envelope for %q: %w", id, err) - } + env := unmarshalCheckpoint(snapBytes) + kernelSnap, persistedTimers, checkpointNext := env.Snapshot, env.Timers, env.NextStep snap, err := state.UnmarshalSnapshot[S, E, C](kernelSnap) if err != nil { @@ -936,11 +1395,15 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // Install the invoked-service host driver and arm the restored configuration's // services, so a service in flight at the checkpoint (or armed by a replayed - // step) can be re-settled from its recorded outcome without re-running it. + // step) can be re-settled from its recorded outcome without re-running it. A + // service that had settled by the checkpoint while its state stayed active isn't + // armed: it would run again. + restoredStarts := inst.StartEffects() + endedServices := env.EndedServices svcBuf := make([]state.JournalEntry, 0) svc := r.newServiceRunner(inst) if svc != nil { - svc.Absorb(ctx, inst.StartEffects()) + svc.Absorb(ctx, startsExcept(restoredStarts, endedServices, func(sv state.StartService) string { return sv.ID })) } // Build the child-machine actor host driver, but DO NOT spawn the restored @@ -949,8 +1412,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // behavior. Spawning here would re-instantiate an actor the recorded run already // settled. The live actors at the resume point are armed once, after replay, // from the final configuration's StartEffects. - actorBuf := make([]state.JournalEntry, 0) - actors := r.newActorSystem(inst) + actors, actorFires := r.newActorSystem(inst) // armed mirrors the scheduler's pending timers re-established by tail replay, // with their recorded deadlines, so a persisted-but-compacted timer is re-armed @@ -958,106 +1420,72 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // with every still-pending timer's deadline for the next checkpoint. armed := map[string]pendingTimer{} + // mirror tracks, as replay walks the tail, the still-pending timers in armed and the + // services that settled in their state's current activation, starting from the ones + // the checkpoint recorded. + mirror := &armMirror{armed: armed, clock: repClock} + for _, sv := range endedServices { + mirror.settle(sv) + } + + // ended is the latest recorded set of the declared actors the live run had ended: + // the checkpoint's, then each tail Record's that records one. Nil means none was + // recorded, so Recover spawns every actor the configuration declares. + ended := env.EndedActors + // unstarted is the latest recorded set of the declared actors that weren't running + // and hadn't ended, recorded alongside ended. Nil means none was recorded. + unstarted := env.UnstartedActors + for i := range tail { + // A canceled context can stop a replayed settle or tick with no error, leaving + // state short of the journal, so check it before each Record. + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } rec := &tail[i] - switch { - case hasActorEntry(rec): - // Re-fire each recorded parent transition the live delivery drove, in - // recorded (fire) order, carrying the recorded actor done-data / error so - // the kernel re-derives the identical onDone / onError (or message) parent - // transition — running no actor behavior. - for _, entry := range actorEntries(rec) { - if err := replayActor(ctx, inst, r.cfg.eventCodec, entry); err != nil { - return nil, fmt.Errorf("durable: at step %d for %q: %w", rec.Step, id, err) - } - } - case hasServiceEntry(rec): - // Re-settle each recorded invoked-service outcome through the same settle - // seam the live run drove, in recorded (settle) order, so the kernel - // re-fires the identical onDone / onError event with the identical data — - // running no service. The settle absorbs its own follow-on StartService - // effects, so a chained invoke arms its successor for the next entry. - for _, entry := range serviceEntries(rec) { - if err := replayService(ctx, svc, entry); err != nil { - return nil, fmt.Errorf("durable: at step %d for %q: %w", rec.Step, id, err) - } - } - case rec.Tick: - // Re-derive the timers the live tick fired: ticking the replay clock - // returns the recorded readings, so the same deadlines come due and the - // same timers fire, at their recorded instants. Mirror the tick into the - // armed table — drop the timers it fired, arm any a chained transition - // re-scheduled — so the deadline table tracks the still-pending set. - tickRes := sched.Tick(ctx) - if now, ok := tickInstant(rec.Entries); ok { - for id, pt := range armed { - if !pt.due.After(now) { - delete(armed, id) - } - } - for ri := range tickRes { - mirrorArmed(armed, tickRes[ri].Effects, now) - } - } - case len(rec.Event) == 0: - continue // a checkpoint-only Record drives no event - default: - event, err := r.cfg.eventCodec.Decode(rec.Event) - if err != nil { - return nil, fmt.Errorf("durable: decoding recorded event at step %d for %q: %w", rec.Step, id, err) - } - fireOpts, err := replayFireOptions(rec, event, r.cfg.eventDataDecoder) - if err != nil { - return nil, fmt.Errorf("durable: decoding recorded event data at step %d for %q: %w", rec.Step, id, err) - } - res := inst.Fire(ctx, event, fireOpts...) - if res.Err != nil { - return nil, fmt.Errorf("durable: replaying step %d for %q: %w", rec.Step, id, res.Err) - } - // Re-arm/cancel this step's timers exactly as the live Fire did, so the - // scheduler's pending set is reconstructed with the recorded deadlines. - // Mirror the same arming into the armed table, drawing the deadline from - // the recorded clock read the Absorb consumed (captured at the recorded - // step rather than the live wall clock). - if hasTimerEffect(res.Effects) { - sched.Absorb(ctx, res.Effects) - // The step's recorded clock read (the one the live Absorb consumed) is - // the instant to derive each re-armed deadline from, so the mirror uses - // recorded time, not the live wall clock. - if now, ok := tickInstant(rec.Entries); ok { - mirrorArmed(armed, res.Effects, now) - } - } - // Arm this step's services so a service it entered is in flight for the - // recorded settlement that follows, mirroring the live Fire path. - if svc != nil { - svc.Absorb(ctx, res.Effects) - } - // Re-dispatch this step's domain effects, deduped by the Store's - // dispatched set: an effect already marked (it landed before the crash) - // is skipped; one recorded-but-un-marked (the crash fell between append - // and dispatch) is applied now — exactly-once across the crash boundary. - if err := r.dispatchReplayEffects(ctx, id, rec.Step, res.Effects); err != nil { + // The mirror tracks the still-pending timers in armed as replay arms, cancels and + // fires them, with deadlines drawn from the recorded clock reads, not the live + // wall clock. + if err := checkFormat(env.Format, rec); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } + fired, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, mirror, armsActorFires(rec)) + if err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } + if rec.EndedActors != nil { + ended = rec.EndedActors + } + if rec.UnstartedActors != nil { + unstarted = rec.UnstartedActors + } + if fired != nil { + // Re-dispatch this step's domain effects, deduped by the Store's dispatched + // set: an effect already marked (it landed before the crash) is skipped; one + // recorded-but-un-marked (the crash fell between append and dispatch) is + // applied now — exactly-once across the crash boundary. + if err := r.dispatchReplayEffects(ctx, id, rec.Step, fired.Effects); err != nil { return nil, err } } } + // A canceled context can stop the last replayed settle or tick with no error too, so + // check it once more, now that the walk is done, before any actor spawns. + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } + // Drain any clock readings the replay re-recorded after the cursor exhausted // (none in the common case where replay consumes exactly the recorded // readings): they belong to no new step and must not leak into the next Fire. buf = buf[:0] - // Arm the live actors at the resume point from the final configuration's - // StartEffects: this spawns exactly the actors running where replay left the - // parent (for example the next child in a chain, after the prior one settled), - // so a subsequent DeliverToActor finds them — without re-instantiating an actor - // the recorded run already settled, which replay reconstructed by re-firing the - // parent rather than re-running behavior. - if actors != nil { - actors.Absorb(ctx, inst.StartEffects()) - } - + // Re-arming reads the clock past the journal, and so can arming a timer for a parent + // Fire an actor Recover spawns drives, which the next step records: re-arm before the + // spawns, so the re-arm's read can be dropped while theirs are kept, and so one of + // their Fires can cancel a re-armed timer. + // // Re-arm any timer that was pending at the checkpoint but whose arming // ScheduleAfter was compacted out of the tail, so it survives compaction: the // tail replay could not re-arm it (its arm is gone), so re-arm it here at its @@ -1107,21 +1535,77 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S } } } - return &Handle[S, E, C]{ - runner: r, - id: id, - inst: inst, - nextStep: next, - sched: sched, - recClock: recClock, - timers: armed, - svc: svc, - svcBuf: &svcBuf, - actors: actors, - actorBuf: &actorBuf, - lock: make(chan struct{}, 1), - out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, - }, nil + // A parent Fire the actors Recover spawns drive arms its state's timers and services + // on this Handle's drivers. + h := &Handle[S, E, C]{ + runner: r, + id: id, + inst: inst, + nextStep: next, + sched: sched, + recClock: recClock, + timers: armed, + svc: svc, + svcBuf: &svcBuf, + settled: mirror.settled, + actors: actors, + actorFires: actorFires, + lock: make(chan struct{}, 1), + out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, + } + + // Arm the live actors at the resume point from the final configuration's + // StartEffects: this spawns exactly the actors running where replay left the + // parent (for example the next child in a chain, after the prior one settled), + // so a subsequent DeliverToActor finds them — without re-instantiating an actor + // the recorded run already settled, which replay reconstructed by re-firing the + // parent rather than re-running behavior. + // + // An actor that was running sends the parent nothing as it spawns again: the journal + // holds what its start drove. + if actors != nil { + // With no recorded ended set, Recover spawns every declared actor, as it did + // before the set was recorded. + var endedIDs []string + if ended != nil { + endedIDs = ended.IDs + } + spawns := startsExcept(inst.StartEffects(), endedIDs, func(sp state.SpawnActor) string { return sp.ID }) + actorFires.arm = h.absorbParentFire + actorFires.attempt(spawns) + func() { + defer actorFires.driving(ctx)() + respawn(ctx, actors, actorFires, spawns, unstarted) + }() + } + // A parent Fire a newly started actor drove (a message it sent as it started, or a + // failed spawn's onError) applied to the instance past its journal, so the next step + // journals it, ahead of its own work. One a context's ending refused never applied, + // and the Handle would hold state the journal can't reach, so Recover fails. + recoverFires := actorFires.take() + if refused := refusedByContext(parentFireErrs(recoverFires)...); refused != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, refused) + } + // The journal's ended actors stay ended, and seen, so the next step records a set + // only when it changes them. + h.seen = map[string]bool{} + if actors != nil { + for _, id := range actors.IDs() { + h.seen[id] = true + } + h.ended.note(ended) + h.unstarted.note(unstarted) + if ended != nil { + for _, id := range ended.IDs { + h.seen[id] = true + } + } + } + + // A context that ended once the spawns ran fails nothing, as for Start: their + // behaviors already ran, and failing would make a retry run them again. + h.pending = recoverFires + return h, nil } // eventPayload is the recorded form of a WithEventData payload. @@ -1301,3 +1785,275 @@ func (jsonEventCodec[E]) Decode(payload []byte) (E, error) { func isContextErr(err error) bool { return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) } + +// stepCanceled reports why a Tick, RunService or DeliverToActor must record nothing: +// a context ended, so a Fire the step drove may have been refused, and live may not +// have applied what the step would journal. That's the caller's ctx having ended, or +// a Fire refused with a context's error (one middleware derived from ctx included) +// among errs, which hold the errors of the Fires the step drove, the parent Fires its +// actors drove among them. These steps check ctx itself because a service or timer +// they consumed can end on it without any Fire reporting it. A refusal with any other +// cause, such as a failing guard, is deterministic: the step is journaled, and replay +// meets the same refusal. +func stepCanceled(ctx context.Context, errs ...error) error { + if err := ctx.Err(); err != nil { + return err + } + return refusedByContext(errs...) +} + +// consumedCanceled is stepCanceled for a step that consumed something (a timer it +// fired, a delivery that drove the parent), and refusedByContext for one that didn't, +// which has nothing an ended ctx could have cost it. +func consumedCanceled(ctx context.Context, consumed bool, errs ...error) error { + if consumed { + return stepCanceled(ctx, errs...) + } + return refusedByContext(errs...) +} + +// refusedByContext returns the first of errs that is a context's error: a Fire refused +// because the context it ran under ended. +func refusedByContext(errs ...error) error { + for _, err := range errs { + if err != nil && isContextErr(err) { + return err + } + } + return nil +} + +// failOnPanic fails the Handle when host code panicked during a step, since the kernel +// may have applied what the step never recorded, then lets the panic go on. A step +// defers it after release, so it runs first, under the step lock. +func (h *Handle[S, E, C]) failOnPanic() { + if p := recover(); p != nil { + _ = h.fail(fmt.Errorf("durable: a step of %q panicked: %v", h.id, p)) + panic(p) + } +} + +// resultErrs returns each result's error, nil ones included. +func resultErrs[S comparable](results []state.FireResult[S]) []error { + errs := make([]error, len(results)) + for i := range results { + errs[i] = results[i].Err + } + return errs +} + +// replayRecord re-applies one journaled Record to inst the way the live step applied +// it, running no service, actor or effect handler. Recover and StateAt both walk the +// journal with it; Recover adds its deadline table, which mirror tracks, and effect +// re-dispatch on top. A nil mirror tracks no deadlines. +// +// - Parent Fires a Start's or Recover's spawns drove, recorded with the next step, +// re-fire first, before the step's own work. +// - An actor delivery re-fires each parent transition the delivery drove, in fire +// order, with the recorded done-data or error, so the kernel re-derives the same +// onDone / onError (or message) transition. A Fire's or settle's absorb-driven +// parent Fires, such as a spawned actor's onError, re-fire after its own work. Each +// re-arms the timers and services its state declares, as the live Fire did, when +// actorArms says the version that wrote rec armed them. +// - A service settlement re-settles each recorded outcome through the same settle +// seam, in settle order; the settle absorbs its own follow-on StartService +// effects, so a chained invoke arms its successor for the next entry, and its +// timers are re-armed as RunService armed them. +// - A tick barrier ticks the replay clock, which returns the recorded readings, so +// the same deadlines come due and the same timers fire at their recorded instants. +// - A plain event re-fires it with its recorded event data, then re-arms its timers +// and services as the live Fire did. +// - A checkpoint-only Record drives nothing. +func replayRecord[S comparable, E comparable, C any]( + ctx context.Context, + inst *state.Instance[S, E, C], + cfg *runnerConfig[S, E, C], + sched *state.Scheduler[S, E, C], + svc *state.ServiceRunner[S, E, C], + rec *Record, + mirror *armMirror, + actorArms bool, +) (*state.FireResult[S], error) { + var fired *state.FireResult[S] + before, rest, err := splitActorEntries(rec) + if err != nil { + return fired, fmt.Errorf("at step %d: %w", rec.Step, err) + } + // Parent Fires a Start's or Recover's spawns drove ran before the step's own work. + if err := replayActors(ctx, inst, cfg, sched, svc, rec, before, mirror, actorArms); err != nil { + return fired, err + } + switch { + case len(rec.Event) > 0: + event, err := cfg.eventCodec.Decode(rec.Event) + if err != nil { + return fired, fmt.Errorf("decoding recorded event at step %d: %w", rec.Step, err) + } + fireOpts, err := replayFireOptions(rec, event, cfg.eventDataDecoder) + if err != nil { + return fired, fmt.Errorf("decoding recorded event data at step %d: %w", rec.Step, err) + } + res := inst.Fire(ctx, event, fireOpts...) + if res.Err != nil { + return fired, fmt.Errorf("replaying step %d: %w", rec.Step, res.Err) + } + replayArm(ctx, sched, svc, res.Effects, mirror) + fired = &res + case hasServiceEntry(rec): + for _, entry := range serviceEntries(rec) { + effects, err := replayService(ctx, svc, entry) + if err != nil { + return fired, fmt.Errorf("at step %d: %w", rec.Step, err) + } + mirror.settle(entry.CorrelationID) + // The settle armed its own services; arm its timers, as RunService did. + replayArm(ctx, sched, nil, effects, mirror) + } + case rec.Tick: + mirrorTick(mirror, sched, sched.Tick(ctx)) + } + // The rest are a delivery's parent Fires, or the ones a Fire's or settle's absorb + // drove after it, such as a spawned actor's onError. + return fired, replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror, actorArms) +} + +// replayActors re-fires recorded parent transitions, in order. When actorArms, the +// version that wrote rec armed the timers and services an actor-driven Fire declares, +// so each one arms them, as the live run did. An older version armed none, and took no +// clock read for them, so they're left alone, as that run left them. +func replayActors[S comparable, E comparable, C any]( + ctx context.Context, + inst *state.Instance[S, E, C], + cfg *runnerConfig[S, E, C], + sched *state.Scheduler[S, E, C], + svc *state.ServiceRunner[S, E, C], + rec *Record, + entries []decodedActorEntry, + mirror *armMirror, + actorArms bool, +) error { + for _, entry := range entries { + effects, err := replayActor(ctx, inst, cfg.eventCodec, entry) + if err != nil { + return fmt.Errorf("at step %d: %w", rec.Step, err) + } + if actorArms { + replayArm(ctx, sched, svc, effects, mirror) + } else { + mirror.forget(effects) + } + } + return nil +} + +// checkFormat fails when rec's journal Format is lower than the checkpoint's that replay +// started from: a version doesn't write an older format than it did, so the Store lost +// the field, and replaying the Record as an older format's would recover wrong. +func checkFormat(checkpoint int, rec *Record) error { + if rec.Format < checkpoint { + return fmt.Errorf("durable: step %d records journal format %d after a checkpoint of format %d: the Store didn't keep Record.Format", rec.Step, rec.Format, checkpoint) + } + return nil +} + +// armsActorFires reports whether rec was written by a version that arms the timers and +// services an actor-driven parent Fire declares, from the journal Format it records. +func armsActorFires(rec *Record) bool { + return rec.Format >= actorArmsFormat +} + +// journalFormat is the format this version writes in every Record. It is +// actorArmsFormat, the first that arms the timers and services an actor-driven parent +// Fire's state declares. +const ( + actorArmsFormat = 1 + journalFormat = actorArmsFormat +) + +// replayArm arms the timers and services a replayed Fire's effects declare, as the live +// step's absorb did, reading the clock only when they schedule or cancel a timer, as it +// did. svc may be nil. +func replayArm[S comparable, E comparable, C any](ctx context.Context, sched *state.Scheduler[S, E, C], svc *state.ServiceRunner[S, E, C], effects []state.Effect, mirror *armMirror) { + mirror.forget(effects) + if hasTimerEffect(effects) { + sched.Absorb(ctx, effects) + mirror.arm(effects) + } + if svc != nil { + svc.Absorb(ctx, effects) + } +} + +// armMirror tracks the timers a Recover's replay leaves pending, with the deadlines the +// scheduler computed from the recorded clock reads, so the Handle's timer table starts +// with them, and the services that settled in their state's current activation, so the +// Handle's next checkpoint records them. A nil mirror, as a time-travel read uses, +// tracks nothing. +type armMirror struct { + armed map[string]pendingTimer + clock *replayClock + settled map[string]bool +} + +// settle notes that a replayed settle settled the service id. +func (m *armMirror) settle(id string) { + if m == nil { + return + } + if m.settled == nil { + m.settled = map[string]bool{} + } + m.settled[id] = true +} + +// forget drops from the settled services each one a replayed Fire's effects start or +// stop, as the live step did. +func (m *armMirror) forget(effects []state.Effect) { + if m == nil { + return + } + forgetSettled(m.settled, effects) +} + +// arm folds a replayed absorb's timer effects into the table, at the reading the +// scheduler's absorb just took. +func (m *armMirror) arm(effects []state.Effect) { + if m == nil { + return + } + mirrorArmed(m.armed, effects, m.clock.lastRead()) +} + +// mirrorTick arms in m any timer a replayed tick's chained transition scheduled, at the +// deadline the scheduler holds, as the live Tick does, then drops the timers the tick +// fired: the ones sched no longer holds. +func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Scheduler[S, E, C], results []state.FireResult[S]) { + if m == nil { + return + } + for i := range results { + mirrorScheduled(m.armed, sched, results[i].Effects) + m.forget(results[i].Effects) + } + dropUnscheduled(m.armed, sched) +} + +// mirrorScheduled folds a fired timer's ScheduleAfter and CancelScheduled effects into +// table, taking each scheduled timer's deadline from sched (Scheduler.Due), so the table +// holds what the scheduler armed whatever clock reads the tick and its transitions took. +// A timer scheduled and then fired or canceled within the tick isn't pending, and isn't +// kept. +func mirrorScheduled[S comparable, E comparable, C any](table map[string]pendingTimer, sched *state.Scheduler[S, E, C], effects []state.Effect) { + for _, eff := range effects { + switch e := eff.(type) { + case state.ScheduleAfter: + if due, ok := sched.Due(e.ID); ok { + table[e.ID] = pendingTimer{id: e.ID, due: due, event: e.Event} + } else { + delete(table, e.ID) + } + case state.CancelScheduled: + delete(table, e.ID) + } + } +} diff --git a/durable/runner_example_test.go b/durable/runner_example_test.go index 2fd92fa0..a6f2b530 100644 --- a/durable/runner_example_test.go +++ b/durable/runner_example_test.go @@ -159,10 +159,11 @@ func quoteMachine(fn state.ServiceFn[*quoteCtx]) *state.Machine[string, string, } // ExampleHandle_RunService shows the invoked-service record/replay seam: a pricing -// service runs exactly once on the live path (its returned quote recorded), and on +// service runs once on the live path (its returned quote recorded), and on // recovery the recorded quote is replayed back through the same settle seam without // re-invoking the service — so the recovered instance reaches the same state and -// context, and the service's call count never advances past one. +// context, and the service's call count never advances past one. (A turn whose +// context ends partway records nothing, and a recovered Handle runs it again.) func ExampleHandle_RunService() { ctx := context.Background() var calls int @@ -232,10 +233,11 @@ func fulfillmentMachine() *state.Machine[string, string, *fulfillmentCtx] { } // ExampleHandle_DeliverToActor shows the actor record/replay seam: a child shipping -// actor runs exactly once on the live path (its done-data recorded), and on recovery +// actor runs once on the live path (its done-data recorded), and on recovery // the recorded done-data is replayed back through the same parent onDone without // re-running the actor — so the recovered instance reaches the same state and -// context, and the actor's run count never advances past one. +// context, and the actor's run count never advances past one. (A delivery whose +// context ends partway records nothing, and a recovered Handle restarts the actor.) func ExampleHandle_DeliverToActor() { ctx := context.Background() var runs int diff --git a/durable/runner_options.go b/durable/runner_options.go index 614afe83..b653c5e1 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -94,10 +94,10 @@ func WithRunnerClock[S comparable, E comparable, C any](c state.Clock) Option[S, } // WithServiceRegistry binds the invoked-service implementations the Runner runs on -// the live path and resolves on recovery. A durable service runs exactly once — -// live — and its result is recorded; on recovery the recorded result is replayed -// through the same settle seam and the service is never re-invoked, so the registry -// is consulted only to execute a service the first time. Supply it for any machine +// the live path and resolves on recovery. A durable service runs live and its result is +// recorded; on recovery the recorded result is replayed through the same settle seam and +// that service is never re-invoked, so the registry is consulted only to execute a +// service whose result isn't recorded. Supply it for any machine // that declares `invoke` states; a purely event-driven or timer-driven machine // needs none. The registry binds the same ServiceFns the machine declares, by name // (state.NewRegistry().Service(name, fn)). @@ -111,11 +111,11 @@ func WithServiceRegistry[S comparable, E comparable, C any](reg *state.Registry[ // WithActorPalette binds the child-machine actor behaviors the Runner spawns and // runs on the live path and resolves on recovery, keyed by the actor src name (the -// name passed to InvokeActor or the Spawn built-in). A durable actor's behavior -// runs exactly once — live — and its done-data, error, or parent-driving message is -// recorded; on recovery the recorded result is replayed back through the same parent -// transition and the behavior is never re-instantiated, so the palette is consulted -// only to run an actor the first time. Supply it for any machine that spawns child +// name passed to InvokeActor or the Spawn built-in). A durable actor's behavior runs +// live and its done-data, error, or parent-driving message is recorded; on recovery the +// recorded result is replayed back through the same parent transition and that behavior +// is never re-instantiated, so the palette is consulted only to run an actor whose +// result isn't recorded. Supply it for any machine that spawns child // actors; a machine that spawns none needs none. Each behavior is the actor-model // analog of a ServiceFn, registered by the same src name the machine declares. func WithActorPalette[S comparable, E comparable, C any](palette map[string]state.ActorBehavior) Option[S, E, C] { diff --git a/durable/service.go b/durable/service.go index 490f8b46..66dde8cd 100644 --- a/durable/service.go +++ b/durable/service.go @@ -16,14 +16,15 @@ import ( // (configuration, context, event payload, machine definition) and MUST be recorded // to reproduce a run. // -// # Run exactly once, replay the result +// # Run once per recorded result, replay the result // -// A durable service runs exactly once, on the live path, and its result is -// recorded; on recovery the recorded result is replayed back through the same -// settle seam, and the service is NEVER re-invoked. This is the standard -// durable-execution guarantee: the external call (with its side effects and its -// nondeterministic output) happens once, and recovery is a pure replay against the -// kernel rather than a re-execution of the host's services. +// A durable service runs on the live path and its result is recorded; on recovery the +// recorded result is replayed back through the same settle seam, and that service is +// NEVER re-invoked. This is the standard durable-execution guarantee: recovery is a pure +// replay against the kernel rather than a re-execution of the host's services. A result +// that wasn't recorded, after a context canceled during the service, a crash, or a failed +// Append whose write didn't land, has nothing to replay, so it stays in flight, runs again +// when the host calls RunService, and must tolerate a second run. // // The Runner wraps the kernel's reusable host driver, state.ServiceRunner, which // turns StartService / StopService effects into real ServiceFn executions and @@ -75,7 +76,7 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { return out } -// RunService runs the in-flight invoked service identified by id exactly once, +// RunService runs the in-flight invoked service identified by id, // records its outcome, and settles it — firing the invocation's onDone (on // success) or onError (on failure) event through the durable instance and // recording the produced step. The service is resolved and executed against the @@ -84,19 +85,28 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { // re-invoking the service. // // It returns the routed FireResult and true, or the zero result and false when id -// names no in-flight service (already settled, stopped, or never started), or false -// and the error when the Handle had already failed or ctx has ended. If the service -// settled but its outcome couldn't be recorded or appended, it returns the result, -// true and ErrHandleFailed: the Handle has failed. If another goroutine failed the -// Handle while this step was recording, it returns the result, true and ErrHandleFailed -// saying the step was recorded. A failed checkpoint returns the result, true and that -// error, and the Handle carries on. A recovered Handle has an -// unrecorded service in flight again, and RunService runs it a second time. +// names no in-flight service (already settled, stopped, or never started). It returns +// false and an error when no registry is wired, the Handle has failed, or ctx ended +// before the service started. +// +// Once the service has run, it returns true with any error. A result that won't encode, +// a ctx that ended during the service or while its settle's effects were absorbed (even +// after a clean settle), or a Fire the settle drove refused because a context ended (ctx, +// or one middleware derived from it) returns ErrHandleFailed and records nothing: a +// recovered Handle has the service in flight again, and RunService runs it a second time. +// A failed Append also returns ErrHandleFailed, but the write may have landed anyway: +// Recover finds out, and the service runs again only if the result isn't in the +// journal. If another goroutine failed the Handle while this step was recording, it +// returns the result, true and ErrHandleFailed saying the step was recorded. Every +// ErrHandleFailed also matches its cause, so test for ErrHandleFailed first, then +// ErrFenced, as the Handle doc says. A failed Checkpoint returns the plain error, and +// the result is recorded. func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.FireResult[S], bool, error) { if err := h.acquire(ctx); err != nil { return state.FireResult[S]{}, false, err } defer h.release() + defer h.failOnPanic() if err := h.refuse(ctx); err != nil { return state.FireResult[S]{}, false, err } @@ -112,12 +122,25 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire return state.FireResult[S]{}, false, nil } res := results[0] + // The service settled: unless the settle's own Fire leaves or re-enters the state + // that declares it, which the absorb below notes, a checkpoint records it as settled. + h.noteSettled(id) // The settle re-fired the invocation's onDone / onError, which may enter a state // that arms a timer, starts another service, or spawns an actor. Absorb those // effects into every driver so the next seam method finds them armed — the service // seam composes with the timer and actor seams in one instance. - h.absorbDrivers(ctx, res.Effects) + h.absorbDrivers(h.stepContext(ctx), res.Effects) + + // A context that ended during the service or the absorb can stop the settle's Fire, + // or a Fire an actor spawn routes, before it applies, so the instance may not have + // seen this result: journaling it would commit on recovery what live never applied. + // The runner has already dropped the service, so this Handle can't run it again; + // Recover re-arms it. + fires := h.actorFires.take() + if err := stepCanceled(ctx, append([]error{res.Err}, parentFireErrs(fires)...)...); err != nil { + return res, true, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, err)) + } entry, err := recordServiceOutcome(id, h.svc.LastResult, h.svc.LastError()) if err != nil { @@ -127,14 +150,32 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire *h.svcBuf = append(*h.svcBuf, entry) } + // Every parent Fire the absorb drove (a message an actor sent as it spawned, a + // settle, a failed spawn's onError) applied after the settle, so the step journals + // them, and replay re-fires them after it. + driven, err := recordParentFires(fires, false) + if err != nil { + return res, true, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) + } + step := h.nextStep - rec := Record{Step: step, Entries: h.drainServices()} + // Arming a timer the settle's state declares reads the clock, so the step carries + // its reads. + rec := Record{Step: step, Entries: append(append(h.drainClock(), h.drainServices()...), driven...)} if err := h.persistStep(ctx, step, &rec); err != nil { return res, true, err } return res, true, nil } +// noteSettled records that the service id settled in its state's current activation. +func (h *Handle[S, E, C]) noteSettled(id string) { + if h.settled == nil { + h.settled = map[string]bool{} + } + h.settled[id] = true +} + // recordServiceOutcome builds the JournalServiceResult entry for a just-settled // service. It reads the success result through lastResult (valid only during the // settle's synchronous window) and the error through lastErr, encoding whichever @@ -167,32 +208,35 @@ func recordServiceOutcome(id string, lastResult func() (any, bool), lastErr erro // the recorded payload and calls SettleDone (with the recorded result) or // SettleError (with the reconstructed error), so the kernel re-fires the same // onDone / onError event with the same data and re-derives identical context. It -// reports an error only when the recorded entry cannot be decoded or names no -// in-flight service (a corrupt or mis-ordered journal). -func replayService[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], entry state.JournalEntry) error { +// returns the settle's effects, so the caller arms the timers its state declares, as +// the live RunService did. It reports an error only when the recorded entry cannot be +// decoded or names no in-flight service (a corrupt or mis-ordered journal). +func replayService[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], entry state.JournalEntry) ([]state.Effect, error) { if svc == nil { - return errors.New("durable: replaying a service result requires a service registry (supply WithServiceRegistry)") + return nil, errors.New("durable: replaying a service result requires a service registry (supply WithServiceRegistry)") } var sp serviceResultPayload if err := json.Unmarshal(entry.Payload, &sp); err != nil { - return fmt.Errorf("durable: decoding recorded service %q outcome: %w", entry.CorrelationID, err) + return nil, fmt.Errorf("durable: decoding recorded service %q outcome: %w", entry.CorrelationID, err) } if sp.Error != nil { - if _, ok := svc.SettleError(ctx, entry.CorrelationID, errors.New(*sp.Error)); !ok { - return fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) + res, ok := svc.SettleError(ctx, entry.CorrelationID, errors.New(*sp.Error)) + if !ok { + return nil, fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) } - return nil + return res.Effects, nil } var result any if len(sp.Result) > 0 { if err := json.Unmarshal(sp.Result, &result); err != nil { - return fmt.Errorf("durable: decoding recorded service %q result: %w", entry.CorrelationID, err) + return nil, fmt.Errorf("durable: decoding recorded service %q result: %w", entry.CorrelationID, err) } } - if _, ok := svc.SettleDone(ctx, entry.CorrelationID, result); !ok { - return fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) + res, ok := svc.SettleDone(ctx, entry.CorrelationID, result) + if !ok { + return nil, fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) } - return nil + return res.Effects, nil } // serviceEntries returns the recorded service outcomes carried by a single diff --git a/durable/service_test.go b/durable/service_test.go index df1d4db8..4d29a5d8 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -6,6 +6,7 @@ import ( "fmt" "sync/atomic" "testing" + "time" "github.com/stablekernel/crucible/durable" "github.com/stablekernel/crucible/state" @@ -470,3 +471,525 @@ func TestService_Determinism(t *testing.T) { t.Fatalf("two live runs diverged:\n run1=%s\n run2=%s", s1, s2) } } + +// TestService_ResultFromCanceledTurn_NotCommittedOnRecover proves a service result +// whose settle is canceled with the turn's context, and so never reaches the live +// instance, is not committed by recovery either. +func TestService_ResultFromCanceledTurn_NotCommittedOnRecover(t *testing.T) { + ctx := context.Background() + turnCtx, cancel := context.WithCancel(ctx) + defer cancel() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + cancel() // the turn's deadline passes while the call is in flight + return "late", nil + } + m := fetchMachine(fn) + store := durable.NewMemStore() + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + runner := durable.NewRunner(m, store, opts...) + h, err := runner.Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + _, _, _ = h.RunService(turnCtx, state.InvokeID("fetch", "loading", 0)) + + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + // Compare state, not bytes: live keeps the Trace of the refused settle. + if live, got := h.Instance().Current(), recovered.Instance().Current(); got != live || live != "loading" { + t.Fatalf("recovered %q, live %q, want both loading: the canceled turn's result was committed", got, live) + } + if notes := recovered.Instance().Entity().Notes; len(notes) != 0 { + t.Fatalf("recovered notes %v, want none", notes) + } +} + +// TestService_CanceledTurn_RecoverRerunsTheService proves the canceled result isn't +// journaled, the Handle refuses further steps, and a recovered Handle can run the +// service to completion. +func TestService_CanceledTurn_RecoverRerunsTheService(t *testing.T) { + ctx := context.Background() + turnCtx, cancel := context.WithCancel(ctx) + defer cancel() + calls := 0 + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + calls++ + cancel() + return "late", nil + } + m := fetchMachine(fn) + store := durable.NewMemStore() + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + invoke := state.InvokeID("fetch", "loading", 0) + before := tailLen(t, store, id) + if _, _, err = h.RunService(turnCtx, invoke); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("RunService = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want the canceled result unrecorded", before, after) + } + if _, err = h.Fire(ctx, "start"); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("Fire after the cancel = %v, want ErrHandleFailed", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ok, err := recovered.RunService(ctx, invoke); err != nil || !ok { + t.Fatalf("RunService after Recover = (%v, %v)", ok, err) + } + if calls != 2 { + t.Fatalf("service ran %d times, want 2", calls) + } +} + +// TestRecover_CanceledContext_DoesNotLoseARecordedResult proves a canceled Recover +// reports the cancellation rather than a Handle short of the journal. +func TestRecover_CanceledContext_DoesNotLoseARecordedResult(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchMachine(fn) + store := durable.NewMemStore() + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + mustRunService(t, h, state.InvokeID("fetch", "loading", 0)) + canceled, cancel := context.WithCancel(ctx) + cancel() + if _, err = durable.Recover(canceled, m, store, id, opts...); !errors.Is(err, context.Canceled) { + t.Fatalf("Recover = %v, want context.Canceled", err) + } +} + +// TestStateAt_CanceledContext_ReportsIt proves a canceled historical read reports the +// cancellation, not a view short of the journal. +func TestStateAt_CanceledContext_ReportsIt(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchMachine(fn) + store := durable.NewMemStore(durable.WithHistory()) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + mustRunService(t, h, state.InvokeID("fetch", "loading", 0)) + canceled, cancel := context.WithCancel(ctx) + cancel() + if _, err = durable.StateAt(canceled, m, store, id, 0, opts...); !errors.Is(err, context.Canceled) { + t.Fatalf("StateAt = %v, want context.Canceled", err) + } +} + +// TestRecover_CanceledContext_ChainedServices_ReportsIt proves a canceled replay of two +// chained services reports the cancellation, not a journal that looks corrupt. +func TestRecover_CanceledContext_ChainedServices_ReportsIt(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := chainMachine(fn, fn) + store := durable.NewMemStore() + id := durable.InstanceID("chain-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](chainRegistry(fn, fn))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("first")) + if err != nil { + t.Fatalf("Start: %v", err) + } + mustRunService(t, h, state.InvokeID("chain", "first", 0)) + mustRunService(t, h, state.InvokeID("chain", "second", 0)) + canceled, cancel := context.WithCancel(ctx) + cancel() + if _, err = durable.Recover(canceled, m, store, id, opts...); !errors.Is(err, context.Canceled) { + t.Fatalf("Recover = %v, want context.Canceled", err) + } +} + +// TestTick_ContextEndedPartway_RecordsNothing proves a due timer the kernel refused isn't +// journaled: the Handle fails and the journal doesn't grow. +func TestTick_ContextEndedPartway_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := timerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + turn, cancel := context.WithCancel(ctx) + defer cancel() + clk := &cancelingClock{Clock: state.NewFakeClock(epoch)} + opts := []durable.Option[string, string, *timerCtx]{durable.WithRunnerClock[string, string, *timerCtx](clk)} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + _, before, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + clk.Clock.(*state.FakeClock).Advance(6 * time.Second) + clk.onNow = cancel // the turn ends as the Tick reads the clock + if _, err = h.Tick(turn); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("Tick = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + clk.onNow = nil + _, after, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(after) != len(before) { + t.Fatalf("journal grew from %d to %d records", len(before), len(after)) + } +} + +// cancelingClock runs onNow once on the next clock read. +type cancelingClock struct { + state.Clock + onNow func() +} + +func (c *cancelingClock) Now() time.Time { + if c.onNow != nil { + f := c.onNow + c.onNow = nil + f() + } + return c.Clock.Now() +} + +// TestService_ContextEndedDuringAbsorb_RecordsNothing proves a service that settles +// cleanly, and whose context then ends while the settle's actor spawn is absorbed, +// fails the Handle and records nothing: the spawn's onError Fire was refused, so the +// live instance never applied what the journal would otherwise commit. +func TestService_ContextEndedDuringAbsorb_RecordsNothing(t *testing.T) { + ctx := context.Background() + turnCtx, cancel := context.WithCancel(ctx) + defer cancel() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return "ok", nil } + spawn := func(map[string]any) (state.ActorInstance, error) { + cancel() // the turn's deadline passes while the settle's spawn is absorbed + return nil, errors.New("worker unavailable") + } + m := state.ForgeFor[svcCtx]("absorb"). + Service("fetch", fn). + Actor("spawnChild"). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("loading"). + Transition("loading").On("ok").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed"). + Quench() + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store, + durable.WithServiceRegistry[string, string, svcCtx](state.NewRegistry[svcCtx]().Service("fetch", fn)), + durable.WithActorPalette[string, string, svcCtx](map[string]state.ActorBehavior{"spawnChild": spawn})). + Start(ctx, "absorb-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + before := tailLen(t, store, "absorb-1") + _, ran, err := h.RunService(turnCtx, state.InvokeID("absorb", "loading", 0)) + if !ran || !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService = %v, %v; want true, ErrHandleFailed", ran, err) + } + if after := tailLen(t, store, "absorb-1"); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } +} + +// countingClock counts clock reads and runs onRead on each. +type countingClock struct { + state.Clock + n int + onRead func(n int) +} + +func (c *countingClock) Now() time.Time { + c.n++ + if c.onRead != nil { + c.onRead(c.n) + } + return c.Clock.Now() +} + +// TestTick_ContextEndedAfterTheTimersApplied_RecordsNothing proves a Tick whose context +// ends after its due timer's Fire applied still fails the Handle and records nothing, +// as RunService and DeliverToActor do, and Recover fires the timer again. +func TestTick_ContextEndedAfterTheTimersApplied_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := chainedTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("chain-1") + fc := state.NewFakeClock(epoch) + clk := &countingClock{Clock: fc} + opts := []durable.Option[string, string, *timerCtx]{durable.WithRunnerClock[string, string, *timerCtx](clk)} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + before := tailLen(t, store, id) + fc.Advance(4 * time.Second) + turn, cancel := context.WithCancel(ctx) + defer cancel() + base := clk.n + clk.onRead = func(n int) { + if n == base+3 { // the scheduler's last read, after the first timer applied + cancel() + } + } + results, err := h.Tick(turn) + clk.onRead = nil + if turn.Err() == nil { + t.Fatal("the test didn't end the context") + } + if len(results) != 1 || results[0].Err != nil { + t.Fatalf("Tick results %v, want one applied timer", results) + } + if !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("Tick = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "first" { + t.Fatalf("recovered state %q, want first: the unrecorded tick must fire again", got) + } +} + +// TestService_RefusedByADerivedContext_RecordsNothing proves a settle refused because a +// context middleware derived from the caller's ended, while the caller's is still live, +// fails the Handle and records nothing. +func TestService_RefusedByADerivedContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + fn := counterService(new(int64)) + cancelOnOK := func(next state.FireFunc[string, string, svcCtx]) state.FireFunc[string, string, svcCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + if event == "ok" { + derived, cancel := context.WithCancel(ctx) + cancel() + return next(derived, event) + } + return next(ctx, event) + } + } + m := state.ForgeFor[svcCtx]("derived"). + Use(cancelOnOK). + Service("fetch", fn). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("ready").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("loading"). + Transition("loading").On("ok").GoTo("ready"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("derived-1") + h, err := durable.NewRunner(m, store, durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))). + Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + before := tailLen(t, store, id) + if _, _, err = h.RunService(ctx, state.InvokeID("derived", "loading", 0)); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("RunService = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } +} + +// TestRecover_DoesNotRearmASuperstatesSettledService proves a service a compound state +// declares, which settled into one of the compound's children, isn't in flight after +// Recover, so RunService doesn't run it again: not from the journal, and not from a +// checkpoint taken after the settle, where the compound is still active. +func TestRecover_DoesNotRearmASuperstatesSettledService(t *testing.T) { + t.Skip("Start and Recover start only the active leaves' services and actors, not a compound state's; #249") + ctx := context.Background() + // every=-1 runs live with no checkpoint, then checkpoints from each recovered Handle, + // so the checkpoint comes from a replay of the settle. + for _, every := range []int{0, 1, -1} { + t.Run(fmt.Sprintf("every=%d", every), func(t *testing.T) { + var runs int64 + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { + atomic.AddInt64(&runs, 1) + return "ok", nil + } + m := state.ForgeFor[stepCtx]("nestSvc"). + Service("fetch", fetch). + SuperState("outer").Invoke("fetch", state.WithInvokeOnDone("fetched")). + SubState("a"). + SubState("b"). + Initial("a"). + EndSuperState(). + Initial("outer"). + Transition("a").On("fetched").GoTo("b"). + Transition("b").On("poke").GoTo("b"). + Quench() + opts := []stepOption{durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch))} + live := opts + switch { + case every > 0: + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + live = opts + case every < 0: + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](1)) + } + store, id := durable.NewMemStore(), durable.InstanceID("nest-svc") + svcID := state.InvokeID("nestSvc", "outer", 0) + h, err := durable.NewRunner(m, store, live...).Start(ctx, id, stepCtx{}, state.WithInitialState("a")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, ran, err := h.RunService(ctx, svcID); err != nil || !ran { + t.Fatalf("RunService = %v, %v", ran, err) + } + if got := h.Instance().Current(); got != "b" { + t.Fatalf("state = %q, want b after the settle", got) + } + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + if _, ran, runErr := recovered.RunService(ctx, svcID); runErr != nil || ran { + t.Fatalf("RunService after Recover %d = %v, %v, want the settled service not in flight", round, ran, runErr) + } + if n := atomic.LoadInt64(&runs); n != 1 { + t.Fatalf("the service ran %d times, want once", n) + } + // A step on the recovered Handle checkpoints again, from its own view. + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } + }) + } +} + +// TestRecover_StartsAServiceThatNeverSettled proves a checkpoint records as settled only +// a service that settled, not every declared service that isn't in flight, so Recover +// starts the rest: one whose state a Tick's timer entered (a Tick starts no service), +// and one whose state was re-entered after it settled, which is a new service, whether +// a Fire re-entered it, starting it live, or a Tick did. The checkpoint is the live +// run's, or one a recovered Handle takes after replaying the run. +func TestRecover_StartsAServiceThatNeverSettled(t *testing.T) { + ctx := context.Background() + for _, how := range []string{"timer entered", "Fire re-entered", "timer re-entered"} { + for _, where := range []string{"live checkpoint", "replayed checkpoint"} { + t.Run(how+"/"+where, func(t *testing.T) { + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + m := state.ForgeFor[stepCtx]("unsettled"). + Service("fetch", fetch). + State("idle"). + State("waiting"). + State("fetching").Invoke("fetch", state.WithInvokeOnDone("fetched")). + Initial("idle"). + Transition("idle").On("begin").GoTo("waiting"). + Transition("waiting").On("go").GoTo("fetching"). + Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("fetching"). + Transition("fetching").On("fetched").GoTo("fetching"). + Transition("fetching").On("again").GoTo("fetching").Reenter(). + Transition("fetching").After(10 * time.Second).On("redo").GoTo("fetching").Reenter(). + Transition("fetching").On("poke").GoTo("fetching"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch)), + } + checkpointing := append(opts, durable.WithCheckpointEvery[string, string, stepCtx](1)) + live := checkpointing + if where == "replayed checkpoint" { + live = opts + } + store, id := durable.NewMemStore(), durable.InstanceID("unsettled") + svcID := state.InvokeID("unsettled", "fetching", 0) + h, err := durable.NewRunner(m, store, live...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "begin"); err != nil { + t.Fatalf("Fire(begin): %v", err) + } + switch how { + case "timer entered": + clk.Advance(10 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + default: + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + if _, ran, runErr := h.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v", ran, runErr) + } + if how == "Fire re-entered" { + if _, err = h.Fire(ctx, "again"); err != nil { + t.Fatalf("Fire(again): %v", err) + } + } else { + clk.Advance(10 * time.Second) + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v, want the redo timer to fire", len(results), tickErr) + } + } + } + if got := h.Instance().Current(); got != "fetching" { + t.Fatalf("state = %q, want fetching", got) + } + if where == "replayed checkpoint" { + // Replay the journal, then checkpoint from the recovered Handle's view. + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the journal: %v", err) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, checkpointing...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, runErr := recovered.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService after Recover = %v, %v, want the service in flight: it never settled in this activation of fetching", ran, runErr) + } + }) + } + } +} diff --git a/durable/spawn_message_test.go b/durable/spawn_message_test.go new file mode 100644 index 00000000..c54d2313 --- /dev/null +++ b/durable/spawn_message_test.go @@ -0,0 +1,302 @@ +package durable_test + +// The Recover tests for the messages an actor sends its parent as it spawns: every step +// and every Start or Recover journals them, and Recover spawns a running actor again +// without sending them again, so each applies exactly once. + +import ( + "context" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +type greetOption = durable.Option[string, string, actorCtx] + +// greetMachine spawns a greeter in "greeting", entered by "go" from idle, by the +// onDone of the finisher that "working" runs, or by the onDone of the service that +// "loading" invokes. The greeter's hello is noted and, with +// leave, moves to "greeted", which stops the greeter; without it, the greeter keeps +// running. +func greetMachine(leave bool) *state.Machine[string, string, actorCtx] { + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + target := "greeting" + if leave { + target = "greeted" + } + return state.ForgeFor[actorCtx]("greet"). + Service("fetch", fetchOK). + Reducer("noteHello", note("hello")). + Reducer("notePoke", note("poke")). + Actor("greeter"). + Actor("spawnChild"). + State("idle"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("loading").Invoke("fetch", state.WithInvokeOnDone("fetched")). + State("greeting").InvokeActor("greeter"). + State("greeted"). + Initial("idle"). + Transition("idle").On("go").GoTo("greeting"). + Transition("working").On("childDone").GoTo("greeting"). + Transition("loading").On("fetched").GoTo("greeting"). + Transition("greeting").On("hello").GoTo(target).Assign("noteHello"). + Transition("greeting").On("poke").GoTo("greeting").Assign("notePoke"). + Transition("greeted").On("poke").GoTo("greeted").Assign("notePoke"). + Quench() +} + +// fetchOK is a service that succeeds. +func fetchOK(context.Context, state.ServiceCtx[actorCtx]) (any, error) { return "ok", nil } + +// greetPalette binds a greeter, or one that can't start, and the finisher. +func greetPalette(greeterStarts bool) greetOption { + var runs int64 + greeter := func(map[string]any) (state.ActorInstance, error) { return &greeter{}, nil } + if !greeterStarts { + greeter = failingSpawn(nil) + } + return durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "greeter": greeter, + "spawnChild": counterChild(&runs), + }) +} + +// wantHellos fails unless the instance's notes hold hello exactly once. +func wantHellos(t *testing.T, what string, h *durable.Handle[string, string, actorCtx]) { + t.Helper() + hellos := 0 + for _, n := range h.Instance().Entity().Notes { + if n == "hello" { + hellos++ + } + } + if hellos != 1 { + t.Fatalf("%s: notes = %v, want the spawn's hello once", what, h.Instance().Entity().Notes) + } +} + +// TestRecover_AppliesEachSpawnMessageOnce proves the message a greeter sends its parent +// as it spawns, by Start, by a Fire, or by the onDone a delivery or a service settle +// drove, is journaled and applied exactly once across repeated Recovers, whether the +// greeter keeps running (Recover spawns it again without the message) or the message +// ends it (Recover doesn't spawn it, and the journal alone holds the message), with and +// without checkpoints. +func TestRecover_AppliesEachSpawnMessageOnce(t *testing.T) { + ctx := context.Background() + for _, leave := range []bool{false, true} { + for _, every := range []int{0, 1} { + for _, by := range []string{"Start", "Fire", "onDone", "RunService"} { + t.Run(fmt.Sprintf("%s/leave=%v/every=%d", by, leave, every), func(t *testing.T) { + m := greetMachine(leave) + opts := []greetOption{greetPalette(true), durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("fetch", fetchOK))} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, actorCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("greet") + initial := map[string]string{"Start": "greeting", "Fire": "idle", "onDone": "working", "RunService": "loading"}[by] + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + switch by { + case "Fire": + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + case "onDone": + if found, deliverErr := h.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("greet", "working", 0)}, "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActor = %v, %v", found, deliverErr) + } + case "RunService": + if _, ran, runErr := h.RunService(ctx, state.InvokeID("greet", "loading", 0)); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v", ran, runErr) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + wantHellos(t, "live", h) + liveState := h.Instance().Current() + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d", round), recovered) + if got := recovered.Instance().Current(); got != liveState { + t.Fatalf("Recover %d state = %q, want the live %q", round, got, liveState) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } + }) + } + } + } +} + +// TestRecover_AnUnstartedActorsSpawnMessageApplies proves an actor whose spawn failed +// with no onError, so it never ran, sends its spawn message live when Recover retries +// the spawn, and the next step journals it: each Recover before that step applies it +// live once, and one after it replays it once without sending it again. +func TestRecover_AnUnstartedActorsSpawnMessageApplies(t *testing.T) { + ctx := context.Background() + m := greetMachine(false) + store, id := durable.NewMemStore(), durable.InstanceID("unstarted") + h, err := durable.NewRunner(m, store, greetPalette(false)).Start(ctx, id, actorCtx{}, state.WithInitialState("greeting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if notes := h.Instance().Entity().Notes; len(notes) != 1 { + t.Fatalf("live notes = %v, want only the poke, since the greeter never started", notes) + } + var recovered *durable.Handle[string, string, actorCtx] + for round := 1; round <= 2; round++ { + if recovered, err = durable.Recover(ctx, m, store, id, greetPalette(true)); err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d, before a step", round), recovered) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + again, err := durable.Recover(ctx, m, store, id, greetPalette(true)) + if err != nil { + t.Fatalf("Recover after the step: %v", err) + } + wantHellos(t, "Recover after the step", again) +} + +// TestDeliverToActor_JournalsEachFireUnderItsActor proves a delivery journals each +// parent Fire it drove under the actor that drove it: the finisher's onDone under the +// finisher, and the hello of the greeter that onDone spawned under the greeter. +func TestDeliverToActor_JournalsEachFireUnderItsActor(t *testing.T) { + ctx := context.Background() + store, id := durable.NewMemStore(), durable.InstanceID("correlate") + h, err := durable.NewRunner(greetMachine(false), store, greetPalette(true)).Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + finisher := state.ActorID("greet", "working", 0) + if found, deliverErr := h.DeliverToActor(ctx, state.ActorRef{ID: finisher}, "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActor = %v, %v", found, deliverErr) + } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + var got []string + for _, rec := range tail { + for _, e := range rec.Entries { + if e.Kind == state.JournalActorMessage { + got = append(got, e.CorrelationID) + } + } + } + want := fmt.Sprint([]string{finisher, state.ActorID("greet", "greeting", 0)}) + if fmt.Sprint(got) != want { + t.Fatalf("journaled actor entries under %v, want %s", got, want) + } +} + +// sender is an actor that sends its parent ev from its initial entry, then keeps +// running. +type sender struct { + ev string + sent bool +} + +func (s *sender) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (s *sender) ChildEffects() []state.Effect { + if s.sent { + return nil + } + s.sent = true + return []state.Effect{state.SendParent{Event: s.ev}} +} +func (s *sender) Output() any { return nil } + +// TestRecover_ARetriedSpawnsMessageDoesNotRestartARunningActor proves Recover spawns the +// actors that were running before it retries an unstarted one. The parallel state +// declares the hopper, which can't start live, ahead of the greeter that one region +// declares as "v". When Recover's retry starts the hopper, its hop enters the other +// region's state, which declares "v" too. The greeter must already be running there, +// so that spawn is a no-op and its journaled hello applies once, across two Recovers. +func TestRecover_ARetriedSpawnsMessageDoesNotRestartARunningActor(t *testing.T) { + t.Skip("Start and Recover start only the active leaves' services and actors, not a compound state's; #249") + ctx := context.Background() + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + m := state.ForgeFor[actorCtx]("cascade"). + Reducer("noteHello", note("hello")). + Reducer("notePoke", note("poke")). + Actor("hopper"). + Actor("greeter"). + State("off"). + SuperState("par").InvokeActor("hopper"). + Region("left"). + Initial("p1"). + SubState("p1").InvokeActor("greeter", state.WithInvokeID("v")). + EndRegion(). + Region("right"). + Initial("q1"). + SubState("q1"). + SubState("q2").InvokeActor("greeter", state.WithInvokeID("v")). + EndRegion(). + EndSuperState(). + Initial("off"). + Transition("off").On("go").GoTo("par"). + Transition("p1").On("hello").GoTo("p1").Assign("noteHello"). + Transition("p1").On("poke").GoTo("p1").Assign("notePoke"). + Transition("q1").On("hop").GoTo("q2"). + Quench() + palette := func(hopperStarts bool) greetOption { + hopper := failingSpawn(nil) + if hopperStarts { + hopper = func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "hop"}, nil } + } + return durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "hopper": hopper, + "greeter": func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "hello"}, nil }, + }) + } + store, id := durable.NewMemStore(), durable.InstanceID("cascade") + h, err := durable.NewRunner(m, store, palette(false)).Start(ctx, id, actorCtx{}, state.WithInitialState("off")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + wantHellos(t, "live", h) + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, palette(true)) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d", round), recovered) + if got := fmt.Sprint(recovered.Instance().Configuration()); got != "[p1 q2]" { + t.Fatalf("Recover %d configuration = %s, want [p1 q2] after the hopper's hop", round, got) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } +} diff --git a/durable/spawn_onerror_rule_test.go b/durable/spawn_onerror_rule_test.go new file mode 100644 index 00000000..8e73d765 --- /dev/null +++ b/durable/spawn_onerror_rule_test.go @@ -0,0 +1,190 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// The rule for a spawn that failed to start: Recover retries it only when nothing was +// declared to catch the failure. A spawn whose declared onError the parent refused, +// for any reason but a context ending, is done, since the journal holds the refusal. +// A context-refused onError retries (TestRecover_RetriesAGuardedSpawnOnlyWhenAContext- +// RefusedItsOnError). + +// denyAs is a middleware that refuses event with err, as a policy layer might. +func denyAs(event string, err error) state.Middleware[string, string, stepCtx] { + return func(next state.FireFunc[string, string, stepCtx]) state.FireFunc[string, string, stepCtx] { + return func(ctx context.Context, ev string) state.FireResult[string] { + if ev == event { + return state.FireResult[string]{Err: err} + } + return next(ctx, ev) + } + } +} + +// spawnRuleMachine is idle -start-> spawning, which invokes child with opts. spawning +// handles spawnFailed only when handles, and poke always. +func spawnRuleMachine(handles bool, mw state.Middleware[string, string, stepCtx], opts ...state.InvokeOption) stepMachine { + b := state.ForgeFor[stepCtx]("spawnRule").Actor("child") + if mw != nil { + b = b.Use(mw) + } + b = b.State("idle"). + State("spawning").InvokeActor("child", opts...). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("poke").GoTo("spawning") + if handles { + b = b.Transition("spawning").On("spawnFailed").GoTo("failed") + } + return b.Quench() +} + +// spawnRuleCalls runs start live with a child behavior that fails its first spawn and +// starts after, then Recovers once, and returns how many times the behavior ran. +func spawnRuleCalls(t *testing.T, m stepMachine) int { + t.Helper() + ctx := context.Background() + store, id := durable.NewMemStore(), durable.InstanceID("spawn-rule") + var calls int + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": func(in map[string]any) (state.ActorInstance, error) { + calls++ + if calls == 1 { + return nil, errors.New("the child can't start yet") + } + return finishingChild()(in) + }, + })} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if calls != 1 { + t.Fatalf("live ran the behavior %d times, want once", calls) + } + if _, err = durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + return calls +} + +func TestSpawnRule_NoOnErrorRetries(t *testing.T) { + if got := spawnRuleCalls(t, spawnRuleMachine(false, nil)); got != 2 { + t.Fatalf("behavior ran %d times, want Recover to retry it once", got) + } +} + +func TestSpawnRule_GuardRefusedOnErrorIsDone(t *testing.T) { + m := state.ForgeFor[stepCtx]("spawnRuleGuard"). + Guard("never", func(state.GuardCtx[stepCtx]) bool { return false }). + Actor("child"). + State("idle"). + State("spawning").InvokeActor("child", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed").When("never"). + Transition("spawning").On("poke").GoTo("spawning"). + Quench() + if got := spawnRuleCalls(t, m); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) + } +} + +func TestSpawnRule_DeclaredOnErrorWithNoTransitionIsDone(t *testing.T) { + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by a no-transition refusal; #250") + if got := spawnRuleCalls(t, spawnRuleMachine(false, nil, state.WithInvokeOnError("spawnFailed"))); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) + } +} + +func TestSpawnRule_DenialWordedLikeNoTransitionIsDone(t *testing.T) { + denial := &state.InvalidTransitionError{Event: "spawnFailed", Reason: "no transition declared for this state and event"} + m := spawnRuleMachine(true, denyAs("spawnFailed", denial), state.WithInvokeOnError("spawnFailed")) + if got := spawnRuleCalls(t, m); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) + } +} + +// TestSpawnRule_ActorThatFailsWithNoOnErrorStaysEnded pins that an invoked actor that +// ran and then failed with no onError declared is recorded as ended, so no Recover +// spawns it again. +func TestSpawnRule_ActorThatFailsWithNoOnErrorStaysEnded(t *testing.T) { + ctx := context.Background() + for _, every := range []int{0, 1} { + m := state.ForgeFor[stepCtx]("failsLater"). + Actor("child"). + State("idle"). + State("working").InvokeActor("child", state.WithInvokeID("kid")). + Initial("idle"). + Transition("idle").On("start").GoTo("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + store, id := durable.NewMemStore(), durable.InstanceID("fails-later") + var runs int64 + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"child": failChild(&runs)})} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if ok, err := h.DeliverToActorByID(ctx, "kid", "finish"); !ok || err != nil { + t.Fatalf("DeliverToActorByID = %v, %v, want the actor found", ok, err) + } + for round := 1; round <= 2; round++ { + if _, err := durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("every %d, Recover %d: %v", every, round, err) + } + // A respawn would run the behavior again. + if runs != 1 { + t.Fatalf("every %d, Recover %d: behavior ran %d times, want the live run only", every, round, runs) + } + } + } +} + +// spawnActionMachine is idle -start-> spawning, whose start transition spawns child +// with opts; spawning handles spawnFailed only when handles. +func spawnActionMachine(handles bool, opts ...state.SpawnOption) stepMachine { + b := state.ForgeFor[stepCtx]("spawnAction"). + Actor("child"). + State("idle"). + State("spawning"). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning").Spawn("child", "kid", opts...). + Transition("spawning").On("poke").GoTo("spawning") + if handles { + b = b.Transition("spawning").On("spawnFailed").GoTo("failed") + } + return b.Quench() +} + +// An actor a transition spawns, rather than one a state invokes, doesn't return on +// Recover, so its failed spawn isn't retried either, declared onError or not. +func TestSpawnRule_SpawnActionNoOnErrorIsNotRetried(t *testing.T) { + if got := spawnRuleCalls(t, spawnActionMachine(false)); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave a spawned actor alone", got) + } +} + +func TestSpawnRule_SpawnActionDeclaredOnErrorWithNoTransitionIsDone(t *testing.T) { + if got := spawnRuleCalls(t, spawnActionMachine(false, state.WithSpawnOnError("spawnFailed"))); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) + } +} diff --git a/durable/spawn_zero_event_test.go b/durable/spawn_zero_event_test.go new file mode 100644 index 00000000..1bb89513 --- /dev/null +++ b/durable/spawn_zero_event_test.go @@ -0,0 +1,87 @@ +package durable_test + +import ( + "context" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestRecover_RetriesANoOnErrorSpawnEvenWhenTheZeroEventHasATransition pins that a +// failed spawn with no onError declared escalates rather than firing the zero event, so +// a transition the parent declares on that event never runs, live or after Recover, +// and Recover retries the spawn: nothing declared for the failure caught it. +func TestRecover_RetriesANoOnErrorSpawnEvenWhenTheZeroEventHasATransition(t *testing.T) { + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by a no-transition refusal; #250") + ctx := context.Background() + m := state.ForgeFor[stepCtx]("zeroOnError"). + Reducer("note", func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "caught") + return c + }). + Actor("child"). + State("idle"). + SuperState("spawning").InvokeActor("child"). + SubState("waiting"). + SubState("caught"). + Initial("waiting"). + EndSuperState(). + Initial("idle"). + Transition("idle").On("start").GoTo("waiting"). + // The zero event moves between children, so spawning, and its actor, stay. + Transition("waiting").On("").GoTo("caught").Assign("note"). + Transition("caught").On("poke").GoTo("caught"). + Quench() + store, id := durable.NewMemStore(), durable.InstanceID("zero-onerror") + var calls int + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": failingSpawn(func() { calls++ }), + })} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + live := fmt.Sprint(h.Instance().Entity().Notes) + if live != "[]" { + t.Fatalf("live notes = %s, want none: the failure escalates, firing no zero event", live) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != live || calls != 2 { + t.Fatalf("recovered notes = %s after %d behavior runs, want the live %s and the retry's second run", got, calls, live) + } +} + +// TestRecover_RetriesANoOnErrorSpawnAWildcardSwallowed pins that a spawn with no onError +// declared is retried at Recover when the parent's state swallows its zero event with a +// catch-all or a forbid: nothing declared for the failure caught it. +func TestRecover_RetriesANoOnErrorSpawnAWildcardSwallowed(t *testing.T) { + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by a no-transition refusal; #250") + for _, how := range []string{"forbid any", "on any"} { + t.Run(how, func(t *testing.T) { + b := state.ForgeFor[stepCtx]("wildcard"). + Actor("child"). + State("idle"). + State("spawning").InvokeActor("child"). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning") + if how == "forbid any" { + b = b.State("spawning").ForbidAny() + } else { + b = b.Transition("spawning").OnAny().GoTo("spawning") + } + m := b.Quench() + if got := spawnRuleCalls(t, m); got != 2 { + t.Fatalf("behavior ran %d times, want Recover to retry it once", got) + } + }) + } +} diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go new file mode 100644 index 00000000..59734651 --- /dev/null +++ b/durable/step_rule_test.go @@ -0,0 +1,1087 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// stepCtx is the JSON-marshalable context for the step-rule fixtures. +type stepCtx struct { + Notes []string `json:"notes"` +} + +type stepMachine = *state.Machine[string, string, stepCtx] + +type stepOption = durable.Option[string, string, stepCtx] + +// cancelOn is a context middleware that fires event under a context derived from the +// caller's and already ended, while the caller's stays live. +func cancelOn(event string) state.Middleware[string, string, stepCtx] { + return func(next state.FireFunc[string, string, stepCtx]) state.FireFunc[string, string, stepCtx] { + return func(ctx context.Context, ev string) state.FireResult[string] { + if ev == event { + derived, cancel := context.WithCancel(ctx) + cancel() + return next(derived, ev) + } + return next(ctx, ev) + } + } +} + +// failingSpawn is an actor behavior that never starts: it runs hook, if any, then +// fails, so the parent's onError routes. +func failingSpawn(hook func()) state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + if hook != nil { + hook() + } + return nil, errors.New("the child can't start") + } +} + +// finishingChild is an actor that completes when delivered "finish". +func finishingChild() state.ActorBehavior { + var runs int64 + return counterChild(&runs) +} + +func wantFailedWithCancel(t *testing.T, what string, err error) { + t.Helper() + if !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("%s = %v, want ErrHandleFailed wrapping context.Canceled", what, err) + } +} + +func wantTail(t *testing.T, store durable.Store, id durable.InstanceID, want int) { + t.Helper() + if got := tailLen(t, store, id); got != want { + t.Fatalf("journal has %d records, want %d", got, want) + } +} + +// spawnOnStartMachine is idle -start-> spawning, a state whose actor can't start, so +// the absorb of Fire's own effects routes spawnFailed through the parent. +func spawnOnStartMachine(mw state.Middleware[string, string, stepCtx]) stepMachine { + b := state.ForgeFor[stepCtx]("spawner"). + Actor("spawnFail"). + State("idle"). + State("spawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle") + if mw != nil { + b = b.Use(mw) + } + return b.Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed"). + Quench() +} + +// TestFire_SpawnRefusedByAnEndedContext_RecordsNothing proves Fire follows the one +// rule: when the onError of an actor its absorb spawned is refused because a context +// ended, whether the caller's or one derived from it, Fire fails the Handle and +// records nothing, so Recover can't apply the onError live never applied. +func TestFire_SpawnRefusedByAnEndedContext_RecordsNothing(t *testing.T) { + for _, tc := range []struct { + name string + derived bool + }{{"the caller's context", false}, {"a derived context", true}} { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + turn, cancel := context.WithCancel(ctx) + defer cancel() + var mw state.Middleware[string, string, stepCtx] + hook := cancel + if tc.derived { + mw, hook = cancelOn("spawnFailed"), nil + } + m := spawnOnStartMachine(mw) + store := durable.NewMemStore() + id := durable.InstanceID("spawn-on-start") + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(hook)})} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + before := tailLen(t, store, id) + _, err = h.Fire(turn, "start") + wantFailedWithCancel(t, "Fire", err) + wantTail(t, store, id, before) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "idle" { + t.Fatalf("recovered state = %q, want idle, since nothing was recorded", got) + } + }) + } +} + +// messengerUsing is messengerMachine with mw installed. +func messengerUsing(mw state.Middleware[string, string, stepCtx]) stepMachine { + return state.ForgeFor[stepCtx]("messenger"). + Actor("spawnPinger"). + State("listening").InvokeActor("spawnPinger", state.WithInvokeOnDone("pingerDone")). + State("heard"). + Initial("listening"). + Use(mw). + Transition("listening").On("pong").GoTo("heard"). + Transition("heard").On("pingerDone").GoTo("heard"). + Quench() +} + +// TestDeliverToActor_MessageRefusedByADerivedContext_RecordsNothing proves a delivery +// whose child's message to the parent (SendParent) is refused by a context derived +// from the caller's, while the caller's is live, fails the Handle and records nothing. +func TestDeliverToActor_MessageRefusedByADerivedContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := messengerUsing(cancelOn("pong")) + store := durable.NewMemStore() + id := durable.InstanceID("msg-derived") + var msgs int64 + palette := map[string]state.ActorBehavior{"spawnPinger": pingerChild(&msgs)} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, stepCtx](palette)). + Start(ctx, id, stepCtx{}, state.WithInitialState("listening")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("messenger", "listening", 0)) + if !ok { + t.Fatal("no actor ref for the pinger") + } + before := tailLen(t, store, id) + _, err = h.DeliverToActor(ctx, ref, "ping") + wantFailedWithCancel(t, "DeliverToActor", err) + wantTail(t, store, id, before) +} + +// TestDeliverToActor_SpawnRefusedByADerivedContext_RecordsNothing proves a delivery +// whose parent transition enters a state with an actor that can't start, and whose +// onError a derived context refuses, fails the Handle and records nothing. +func TestDeliverToActor_SpawnRefusedByADerivedContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("relay"). + Actor("spawnChild"). + Actor("spawnFail"). + State("supervising").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("respawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("supervising"). + Use(cancelOn("spawnFailed")). + Transition("supervising").On("childDone").GoTo("respawning"). + Transition("respawning").On("spawnFailed").GoTo("failed"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("respawn-derived") + palette := map[string]state.ActorBehavior{"spawnChild": finishingChild(), "spawnFail": failingSpawn(nil)} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, stepCtx](palette)). + Start(ctx, id, stepCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("relay", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for the child") + } + before := tailLen(t, store, id) + _, err = h.DeliverToActor(ctx, ref, "finish") + wantFailedWithCancel(t, "DeliverToActor", err) + wantTail(t, store, id, before) +} + +// expiringMachine is idle -arm-> waiting -(after 1s: expire)-> next, with mw +// installed and next's declarations added by decl. +func expiringMachine(mw state.Middleware[string, string, stepCtx], decl func(*state.Builder[string, string, stepCtx]) *state.Builder[string, string, stepCtx]) stepMachine { + b := state.ForgeFor[stepCtx]("expiring"). + State("idle"). + State("waiting") + b = decl(b) + b = b.Initial("idle") + if mw != nil { + b = b.Use(mw) + } + return b.Transition("idle").On("arm").GoTo("waiting"). + Transition("waiting").After(time.Second).On("expire").GoTo("next"). + Quench() +} + +func doneNext(b *state.Builder[string, string, stepCtx]) *state.Builder[string, string, stepCtx] { + return b.State("next").Final() +} + +// startArmed starts m with opts, a fake clock, and fires arm, so a 1s timer is armed. +func startArmed(t *testing.T, m stepMachine, store durable.Store, id durable.InstanceID, opts ...stepOption) (*durable.Handle[string, string, stepCtx], *state.FakeClock, []stepOption) { + t.Helper() + fc := state.NewFakeClock(epoch) + opts = append(opts, durable.WithRunnerClock[string, string, stepCtx](fc)) + h, err := durable.NewRunner(m, store, opts...).Start(context.Background(), id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(context.Background(), "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + return h, fc, opts +} + +// TestTick_RefusedByADerivedContext_RecordsNothing proves a Tick whose timer's Fire a +// derived context refuses, while the caller's is live, fails the Handle and records +// nothing. +func TestTick_RefusedByADerivedContext_RecordsNothing(t *testing.T) { + m := expiringMachine(cancelOn("expire"), doneNext) + store := durable.NewMemStore() + id := durable.InstanceID("tick-derived") + h, fc, _ := startArmed(t, m, store, id) + before := tailLen(t, store, id) + fc.Advance(time.Second) + _, err := h.Tick(context.Background()) + wantFailedWithCancel(t, "Tick", err) + wantTail(t, store, id, before) +} + +// spawnAtStartMachine starts in spawning, whose actor can't start and whose onError a +// derived context refuses, so Start's and Recover's own spawn drive a refused parent +// Fire that belongs to no step. +func spawnAtStartMachine() stepMachine { + return state.ForgeFor[stepCtx]("spawn-at-start"). + Actor("spawnFail"). + State("spawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("poked"). + State("failed").Final(). + Initial("spawning"). + Use(cancelOn("spawnFailed")). + Transition("spawning").On("spawnFailed").GoTo("failed"). + Transition("spawning").On("poke").GoTo("poked"). + Quench() +} + +// TestStartAndRecover_SpawnRefusal_Fails proves a parent Fire a context refused while +// Start or Recover spawned the resume point's actors fails the call: it never applied, +// so the Handle would hold state the journal can't reach. +func TestStartAndRecover_SpawnRefusal_Fails(t *testing.T) { + ctx := context.Background() + m := spawnAtStartMachine() + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(nil)})} + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store, opts...).Start(ctx, "refused", stepCtx{}, state.WithInitialState("spawning")) + if h != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Start = Handle %v, %v, want no Handle and context.Canceled", h != nil, err) + } + h, err = durable.Recover(ctx, m, store, "refused", opts...) + if h != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Recover = Handle %v, %v, want no Handle and context.Canceled", h != nil, err) + } +} + +// TestFire_ContextEndedAfterACleanApply_Records proves a Fire that drove nothing +// refused applied whole, so it records and returns no error even when its context +// ended after the kernel applied the event, here while the step armed its timer. +func TestFire_ContextEndedAfterACleanApply_Records(t *testing.T) { + ctx := context.Background() + turn, cancel := context.WithCancel(ctx) + defer cancel() + m := expiringMachine(nil, doneNext) + store := durable.NewMemStore() + id := durable.InstanceID("clean-apply") + clk := &countingClock{Clock: state.NewFakeClock(epoch)} + h, err := durable.NewRunner(m, store, durable.WithRunnerClock[string, string, stepCtx](clk)). + Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + before := tailLen(t, store, id) + clk.onRead = func(int) { cancel() } // arming the timer, after the kernel returned + _, err = h.Fire(turn, "arm") + clk.onRead = nil + if turn.Err() == nil { + t.Fatal("the test didn't end the context") + } + if err != nil { + t.Fatalf("Fire = %v, want the clean step recorded", err) + } + wantTail(t, store, id, before+1) + if got := h.Instance().Current(); got != "waiting" { + t.Fatalf("state = %q, want waiting", got) + } +} + +// noteMachine records each event its transitions take, with the data a settle +// carried, so a recovered context shows which Fire got the actor's output. +func noteMachine() stepMachine { + note := func(prefix string) func(state.AssignCtx[stepCtx]) stepCtx { + return func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, fmt.Sprintf("%s:%v", prefix, in.Event)) + return c + } + } + return state.ForgeFor[stepCtx]("noter"). + Reducer("noteDone", note("done")). + Reducer("noteFail", note("fail")). + Actor("spawnChild"). + Actor("spawnFail"). + State("supervising").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("respawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("supervising"). + Transition("supervising").On("childDone").GoTo("respawning").Assign("noteDone"). + Transition("respawning").On("spawnFailed").GoTo("failed").Assign("noteFail"). + Quench() +} + +// TestDeliverToActor_OutcomeGoesToTheSettlingFire proves that when one delivery drives +// several parent Fires, the actor's output is recorded with the Fire that settled it, +// not the last one, so Recover reaches the live context. +func TestDeliverToActor_OutcomeGoesToTheSettlingFire(t *testing.T) { + ctx := context.Background() + m := noteMachine() + store := durable.NewMemStore() + id := durable.InstanceID("outcome") + var runs int64 + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "spawnChild": counterChild(&runs), + "spawnFail": failingSpawn(nil), + })} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("noter", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for the child") + } + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + live := h.Instance().Entity().Notes + if len(live) != 2 || live[0] != "done:out-1" || live[1] != "fail:spawnFailed" { + t.Fatalf("live notes = %v, want the output on childDone, then the plain spawnFailed", live) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Entity().Notes; fmt.Sprint(got) != fmt.Sprint(live) { + t.Fatalf("recovered notes = %v, want the live %v", got, live) + } +} + +// TestFire_PanicInHostCode_FailsTheHandle proves a panic in host code during a step, +// here an actor behavior the step's absorb spawned after the kernel applied the event, +// fails the Handle, since the instance is ahead of the journal, and a later step can't +// record on top of it. +func TestFire_PanicInHostCode_FailsTheHandle(t *testing.T) { + ctx := context.Background() + m := spawnOnStartMachine(nil) + store := durable.NewMemStore() + id := durable.InstanceID("panics") + panicking := func(map[string]any) (state.ActorInstance, error) { panic("the child exploded") } + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": panicking})). + Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + before := tailLen(t, store, id) + func() { + defer func() { + if recover() == nil { + t.Fatal("Fire didn't panic") + } + }() + _, _ = h.Fire(ctx, "start") + }() + wantTail(t, store, id, before) + if _, err = h.Fire(ctx, "spawnFailed"); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("Fire after the panic = %v, want ErrHandleFailed", err) + } + wantTail(t, store, id, before) +} + +// watcherMachine invokes the counter child on supervising; childDone and the other +// events stay in supervising, so the parent keeps declaring the child after it settles. +// how decides what childDone does: "refuse" (a guard fails), "stay" (applies without +// leaving), or "stop" (applies and stops the child explicitly). svcDone, from a service +// the state also invokes, re-enters supervising. +func watcherMachine(how string, withService bool) (*state.Machine[string, string, actorCtx], []durable.Option[string, string, actorCtx]) { + var runs int64 + svc := func(context.Context, state.ServiceCtx[actorCtx]) (any, error) { return "ok", nil } + b := state.ForgeFor[actorCtx]("watcher"). + Guard("never", func(state.GuardCtx[actorCtx]) bool { return false }). + Service("svc", svc). + Actor("spawnChild"). + State("supervising").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")) + if withService { + b = b.Invoke("svc", state.WithInvokeOnDone("svcDone")) + } + b = b.State("complete").Final().Initial("supervising") + switch how { + case "refuse": + b = b.Transition("supervising").On("childDone").GoTo("complete").When("never") + case "stay": + b = b.Transition("supervising").On("childDone").GoTo("supervising") + case "stop": + b = b.Transition("supervising").On("childDone").GoTo("supervising").StopActor(state.ActorID("watcher", "supervising", 0)) + } + m := b.Transition("supervising").On("svcDone").GoTo("supervising").Reenter(). + Transition("supervising").On("poke").GoTo("supervising"). + Quench() + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + if withService { + opts = append(opts, durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("svc", svc))) + } + return m, opts +} + +// TestRecover_SpawnsTheActorsLiveHadRunning proves Recover spawns only the declared +// actors the live run still had running, as the journal records them: an actor that +// settled while its parent stayed in the declaring state, whether its onDone was +// refused, applied without leaving, or stopped it, isn't spawned again, with or +// without a checkpoint compacting the step; one a later step spawned again is. +func TestRecover_SpawnsTheActorsLiveHadRunning(t *testing.T) { + ctx := context.Background() + childID := state.ActorID("watcher", "supervising", 0) + for _, how := range []string{"refuse", "stay", "stop"} { + for _, every := range []int{0, 1, 2} { + t.Run(fmt.Sprintf("%s/checkpoint every %d", how, every), func(t *testing.T) { + m, opts := watcherMachine(how, false) + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, actorCtx](every)) + } + store := durable.NewMemStore() + id := durable.InstanceID("watch") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(childID) + if !ok { + t.Fatal("no actor ref for the child") + } + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if found, _ := recovered.DeliverToActor(ctx, ref, "finish"); found { + t.Fatal("recovered: the actor that settled live is running again") + } + // A step on the recovered Handle, then a second Recover, keeps it ended. + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + again, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if found, _ := again.DeliverToActor(ctx, ref, "finish"); found { + t.Fatal("second Recover: the actor that settled live is running again") + } + }) + } + } + t.Run("a service re-entering spawns it again", func(t *testing.T) { + m, opts := watcherMachine("refuse", true) + store := durable.NewMemStore() + id := durable.InstanceID("watch-svc") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, _ := h.ActorRef(childID) + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + mustRunService(t, h, state.InvokeID("watcher", "supervising", 1)) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if found, _ := recovered.DeliverToActor(ctx, ref, "finish"); !found { + t.Fatal("recovered: the actor the service's re-entry spawned again isn't running") + } + }) +} + +// TestDeliverToActor_MiddlewareDeniedParentFire_Recovers proves a parent Fire that +// middleware denied before the kernel saw it is journaled as refused, and Recover +// meets the same refusal instead of failing on the event it has none of. +func TestDeliverToActor_MiddlewareDeniedParentFire_Recovers(t *testing.T) { + ctx := context.Background() + deny := func(next state.FireFunc[string, string, actorCtx]) state.FireFunc[string, string, actorCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + if event == "childDone" { + return state.FireResult[string]{Err: errors.New("denied by policy")} + } + return next(ctx, event) + } + } + m := supervisorUsing(deny, false) + store := durable.NewMemStore() + id := durable.InstanceID("denied") + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for the child") + } + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != h.Instance().Current() { + t.Fatalf("recovered state = %q, want the live %q", got, h.Instance().Current()) + } +} + +// TestTick_FiresNothing_ContextEnded_StaysHealthy proves a Tick that fired no timer +// keeps the Handle healthy even when its context ends during the call, since it +// consumed nothing an ended context could have cost it. +func TestTick_FiresNothing_ContextEnded_StaysHealthy(t *testing.T) { + ctx := context.Background() + m := expiringMachine(nil, doneNext) + store := durable.NewMemStore() + id := durable.InstanceID("idle-tick") + clk := &countingClock{Clock: state.NewFakeClock(epoch)} + h, err := durable.NewRunner(m, store, durable.WithRunnerClock[string, string, stepCtx](clk)). + Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + turn, cancel := context.WithCancel(ctx) + defer cancel() + clk.onRead = func(int) { cancel() } // the timer isn't due yet + results, err := h.Tick(turn) + clk.onRead = nil + if turn.Err() == nil { + t.Fatal("the test didn't end the context") + } + if err != nil || len(results) != 0 { + t.Fatalf("Tick = %d results, %v; want none and no error", len(results), err) + } + if _, err = h.Fire(ctx, "arm"); errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("the Handle failed: %v", err) + } +} + +// TestRecover_RetriesAFailedSpawn proves an actor whose spawn failed live, which never +// ran, isn't counted as ended: Recover spawns it again, as it did before the journal +// recorded ended actors. +func TestRecover_RetriesAFailedSpawn(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[actorCtx]("retry"). + Actor("spawnChild"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("done").Final(). + Initial("working"). + Transition("working").On("next").GoTo("working"). + Transition("working").On("childDone").GoTo("done"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("retry") + failing := map[string]state.ActorBehavior{"spawnChild": failingSpawn(nil)} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, actorCtx](failing)). + Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "next"); err != nil { + t.Fatalf("Fire: %v", err) + } + var runs int64 + recovered, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ok := recovered.ActorRef(state.ActorID("retry", "working", 0)); !ok { + t.Fatal("Recover didn't spawn the actor whose live spawn failed") + } +} + +// failNoteMachine has a state whose actor can't start; its onError applies, staying in +// the state (stay) or leaving it (leave), and notes the failure, so a recovered +// context shows how many times it applied. +func failNoteMachine(initial string, leave bool) stepMachine { + fail := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "fail") + return c + } + target := "spawning" + if leave { + target = "failed" + } + poke := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "poke") + return c + } + return state.ForgeFor[stepCtx]("noting"). + Reducer("noteFail", fail). + Reducer("notePoke", poke). + Actor("spawnChild"). + State("idle"). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + State("failed"). + Initial(initial). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo(target).Assign("noteFail"). + Transition("spawning").On("poke").GoTo("spawning").Assign("notePoke"). + Transition("failed").On("poke").GoTo("failed").Assign("notePoke"). + Quench() +} + +// TestRecover_ReplaysASpawnsOnErrorOnce proves a failed spawn's onError that applied is +// journaled with the step that drove it, or with the step after Start or Recover drove +// it, so Recover reaches the live state and context, applying it once, and doesn't +// retry the spawn. +func TestRecover_ReplaysASpawnsOnErrorOnce(t *testing.T) { + ctx := context.Background() + failing := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnChild": failingSpawn(nil)})} + check := func(t *testing.T, h *durable.Handle[string, string, stepCtx], m stepMachine, store durable.Store, id durable.InstanceID, opts []stepOption) { + t.Helper() + liveState, liveNotes := h.Instance().Current(), fmt.Sprint(h.Instance().Entity().Notes) + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + if got, notes := recovered.Instance().Current(), fmt.Sprint(recovered.Instance().Entity().Notes); got != liveState || notes != liveNotes { + t.Fatalf("Recover %d = %s %s, want the live %s %s", round, got, notes, liveState, liveNotes) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + // The next Recover rebuilds the Handle that just continued. + liveState, liveNotes = recovered.Instance().Current(), fmt.Sprint(recovered.Instance().Entity().Notes) + } + } + for _, leave := range []bool{false, true} { + for _, every := range []int{0, 1} { + opts := append([]stepOption{}, failing...) + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + t.Run(fmt.Sprintf("Fire/leave=%v/every=%d", leave, every), func(t *testing.T) { + m, store, id := failNoteMachine("idle", leave), durable.NewMemStore(), durable.InstanceID("fire") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + check(t, h, m, store, id, opts) + }) + t.Run(fmt.Sprintf("Start/leave=%v/every=%d", leave, every), func(t *testing.T) { + m, store, id := failNoteMachine("spawning", leave), durable.NewMemStore(), durable.InstanceID("start") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("spawning")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + check(t, h, m, store, id, opts) + }) + } + } + t.Run("RunService", func(t *testing.T) { + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + fail := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "fail") + return c + } + m := state.ForgeFor[stepCtx]("noting"). + Service("fetch", fetch). + Reducer("noteFail", fail). + Actor("spawnChild"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + Initial("loading"). + Transition("loading").On("ok").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("spawning").Assign("noteFail"). + Transition("spawning").On("poke").GoTo("spawning"). + Quench() + opts := append([]stepOption{durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch))}, failing...) + store, id := durable.NewMemStore(), durable.InstanceID("settle") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, ran, err := h.RunService(ctx, state.InvokeID("noting", "loading", 0)); err != nil || !ran { + t.Fatalf("RunService = %v, %v", ran, err) + } + check(t, h, m, store, id, opts) + }) + t.Run("a spawn that fails during Recover", func(t *testing.T) { + m, store, id := failNoteMachine("spawning", false), durable.NewMemStore(), durable.InstanceID("at-recover") + good := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnChild": finishingChild()})} + h, err := durable.NewRunner(m, store, good...).Start(ctx, id, stepCtx{}, state.WithInitialState("spawning")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + // Recover while the actor can't start: its onError applies on this Handle. + r1, err := durable.Recover(ctx, m, store, id, failing...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = r1.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + // A later Recover, with the actor able to start, reaches what r1 had. + r2, err := durable.Recover(ctx, m, store, id, good...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if got, want := fmt.Sprint(r2.Instance().Entity().Notes), fmt.Sprint(r1.Instance().Entity().Notes); got != want { + t.Fatalf("second Recover notes = %s, want r1's %s", got, want) + } + if found, _ := r2.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("noting", "spawning", 0)}, "finish"); found { + t.Fatal("second Recover spawned the actor r1 had handled as failed") + } + }) +} + +// TestRecover_HandlesASpawnWhoseLatestOnErrorWasRefused proves the latest spawn attempt +// decides, and a refused onError that isn't a context's ending counts as handled: a +// failed spawn's onError applies and re-enters the state, the spawn there fails too, +// and the parent refuses that onError for its guard — so the journal holds the +// refusal, Recover doesn't retry the spawn, and the behavior never runs again. +func TestRecover_HandlesASpawnWhoseLatestOnErrorWasRefused(t *testing.T) { + ctx := context.Background() + fail := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "fail") + return c + } + m := state.ForgeFor[stepCtx]("again"). + Guard("firstFailure", func(in state.GuardCtx[stepCtx]) bool { return len(in.Entity.Notes) == 0 }). + Reducer("noteFail", fail). + Actor("spawnChild"). + State("idle"). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("spawning").Reenter().When("firstFailure").Assign("noteFail"). + Quench() + store, id := durable.NewMemStore(), durable.InstanceID("again") + var calls int + palette := durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "spawnChild": func(map[string]any) (state.ActorInstance, error) { + calls++ + return nil, errors.New("the child can't start") + }, + }) + h, err := durable.NewRunner(m, store, palette).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if calls != 2 { + t.Fatalf("live ran the behavior %d times, want the two failed spawns of one step", calls) + } + liveState, liveNotes := h.Instance().Current(), fmt.Sprint(h.Instance().Entity().Notes) + recovered, err := durable.Recover(ctx, m, store, id, palette) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if calls != 2 { + t.Fatalf("Recover ran the behavior again: %d calls, want the two live ones", calls) + } + if got, notes := recovered.Instance().Current(), fmt.Sprint(recovered.Instance().Entity().Notes); got != liveState || notes != liveNotes { + t.Fatalf("recovered %s %s, want the live %s %s", got, notes, liveState, liveNotes) + } + if _, ok := recovered.ActorRef(state.ActorID("again", "spawning", 0)); ok { + t.Fatal("Recover retried the spawn whose latest onError the parent refused") + } +} + +// TestStart_FailsWhenItsContextEndsDuringASpawn proves Start returns no Handle when its +// context ends while an initial actor's spawn fails, so the parent refuses its onError: +// live never applied it. Recover starts from the baseline, retries the spawn, and with +// a live context the onError applies. +func TestStart_FailsWhenItsContextEndsDuringASpawn(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("held"). + Actor("spawnFail"). + State("spawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("failed"). + Initial("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed"). + Transition("spawning").On("poke").GoTo("spawning"). + Quench() + turn, cancel := context.WithCancel(ctx) + defer cancel() + // The spawn ends Start's own context, so the parent refuses its onError. + ending := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(cancel)})} + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(nil)})} + store, id := durable.NewMemStore(), durable.InstanceID("held") + h, err := durable.NewRunner(m, store, ending...).Start(turn, id, stepCtx{}, state.WithInitialState("spawning")) + if h != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Start = Handle %v, %v, want no Handle and context.Canceled", h != nil, err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + // Recover retried the spawn, and with a live context its onError applied. + if got := recovered.Instance().Current(); got != "failed" { + t.Fatalf("recovered state = %q, want failed", got) + } +} + +// TestRecover_SucceedsWhenItsContextEndsAfterReplay proves Recover, like Start, returns +// its Handle when its context ends after the journal is replayed, here while it spawns +// the resume point's actor, and no parent Fire was refused: the actor's behavior ran, +// and failing would make a retry run it again. +func TestRecover_SucceedsWhenItsContextEndsAfterReplay(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("late"). + Actor("quiet"). + State("working").InvokeActor("quiet"). + Initial("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + quiet := func(hook func()) []stepOption { + return []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "quiet": func(map[string]any) (state.ActorInstance, error) { + if hook != nil { + hook() + } + return &sender{sent: true}, nil + }, + })} + } + store, id := durable.NewMemStore(), durable.InstanceID("late") + h, err := durable.NewRunner(m, store, quiet(nil)...).Start(ctx, id, stepCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + turn, cancel := context.WithCancel(ctx) + defer cancel() + recovered, err := durable.Recover(turn, m, store, id, quiet(cancel)...) + if recovered == nil || err != nil { + t.Fatalf("Recover = Handle %v, %v, want the Handle and no error", recovered != nil, err) + } +} + +// cancelingStore ends a context once Start's baseline checkpoint is written. +type cancelingStore struct { + durable.Store + cancel context.CancelFunc +} + +func (s cancelingStore) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { + err := s.Store.Checkpoint(ctx, id, snapshot, throughStep, opts...) + s.cancel() + return err +} + +// TestStart_SucceedsWhenItsContextEndsWithNoRefusal proves Start fails only on a parent +// Fire a context's ending refused, not whenever its context ends after the baseline: +// with no actors, or with an actor that started and drove nothing, Start returns a +// Handle whose steps record, and Recover rebuilds the same state. +func TestStart_SucceedsWhenItsContextEndsWithNoRefusal(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("lateStart"). + Actor("quiet"). + State("idle"). + State("working").InvokeActor("quiet"). + Initial("idle"). + Transition("idle").On("go").GoTo("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + for _, initial := range []string{"idle", "working"} { + t.Run(initial, func(t *testing.T) { + turn, cancel := context.WithCancel(ctx) + defer cancel() + mem := durable.NewMemStore() + var store durable.Store = mem + hook := func() {} + if initial == "idle" { + store = cancelingStore{Store: mem, cancel: cancel} + } else { + hook = cancel + } + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "quiet": func(map[string]any) (state.ActorInstance, error) { + hook() + return &sender{sent: true}, nil + }, + })} + id := durable.InstanceID("late-" + initial) + h, err := durable.NewRunner(m, store, opts...).Start(turn, id, stepCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + if turn.Err() == nil { + t.Fatal("Start's context didn't end") + } + hook = func() {} + if _, err = h.Fire(ctx, map[string]string{"idle": "go", "working": "poke"}[initial]); err != nil { + t.Fatalf("Fire after Start: %v", err) + } + recovered, err := durable.Recover(ctx, m, mem, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "working" { + t.Fatalf("recovered state = %q, want working", got) + } + }) + } +} + +// guardedSpawnMachine is idle -start-> spawning, whose actor can't start: its +// onError is guarded false, so the parent refuses it deterministically and the +// spawn stays where it is. +func guardedSpawnMachine() stepMachine { + return state.ForgeFor[stepCtx]("guarded"). + Guard("never", func(state.GuardCtx[stepCtx]) bool { return false }). + Actor("spawnChild"). + State("idle"). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed").When("never"). + Transition("spawning").On("poke").GoTo("spawning"). + Quench() +} + +// TestRecover_RunsAGuardedSpawnOnce proves a spawn whose onError was refused for a +// reason other than a context ending, here a guard, is handled: the journal holds +// the refusal and replay meets it again, so the behavior runs once live and no +// Recover runs it again, with or without a checkpoint compacting the step. +func TestRecover_RunsAGuardedSpawnOnce(t *testing.T) { + ctx := context.Background() + for _, every := range []int{0, 1} { + t.Run(fmt.Sprintf("checkpoint every %d", every), func(t *testing.T) { + m := guardedSpawnMachine() + store, id := durable.NewMemStore(), durable.InstanceID("guarded") + var calls int + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "spawnChild": failingSpawn(func() { calls++ }), + })} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if calls != 1 { + t.Fatalf("live ran the behavior %d times, want once", calls) + } + liveState, liveNotes := h.Instance().Current(), fmt.Sprint(h.Instance().Entity().Notes) + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + if calls != 1 { + t.Fatalf("Recover %d ran the behavior again: %d calls, want the one live call", round, calls) + } + if got, notes := recovered.Instance().Current(), fmt.Sprint(recovered.Instance().Entity().Notes); got != liveState || notes != liveNotes { + t.Fatalf("Recover %d = %s %s, want the live %s %s", round, got, notes, liveState, liveNotes) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } + }) + } +} + +// TestRecover_RetriesAGuardedSpawnOnlyWhenAContextRefusedItsOnError proves the +// context case keeps its retry: a spawn whose onError a context's ending refused +// was recorded nowhere, so Recover runs the behavior again, and once a live +// context refuses the onError for the guard's reason instead, the next step +// journals it and later Recovers leave the behavior alone. +func TestRecover_RetriesAGuardedSpawnOnlyWhenAContextRefusedItsOnError(t *testing.T) { + ctx := context.Background() + m := guardedSpawnMachine() + store, id := durable.NewMemStore(), durable.InstanceID("guarded-ctx") + var calls int + // countingSpawn counts each run and runs hook, if any, before failing. + countingSpawn := func(hook func()) state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + calls++ + if hook != nil { + hook() + } + return nil, errors.New("the child can't start") + } + } + palette := func(hook func()) stepOption { + return durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "spawnChild": countingSpawn(hook), + }) + } + turn, cancel := context.WithCancel(ctx) + defer cancel() + h, err := durable.NewRunner(m, store, palette(cancel)).Start(turn, id, stepCtx{}, state.WithInitialState("spawning")) + if h != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Start = Handle %v, %v, want no Handle and context.Canceled", h != nil, err) + } + if calls != 1 { + t.Fatalf("Start ran the behavior %d times, want once", calls) + } + // Nothing was recorded, so Recover retries the spawn; with a live context the + // parent refuses its onError for the guard's reason, which the next step + // journals. + recovered, err := durable.Recover(ctx, m, store, id, palette(nil)) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if calls != 2 { + t.Fatalf("Recover ran the behavior %d times, want the retry to make two", calls) + } + if got := recovered.Instance().Current(); got != "spawning" { + t.Fatalf("recovered state = %q, want spawning", got) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + again, err := durable.Recover(ctx, m, store, id, palette(nil)) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if calls != 2 { + t.Fatalf("second Recover ran the behavior again: %d calls, want two", calls) + } + if got := again.Instance().Current(); got != recovered.Instance().Current() { + t.Fatalf("second Recover state = %q, want %q", got, recovered.Instance().Current()) + } +} diff --git a/durable/store.go b/durable/store.go index afaf4fd7..0ba8ca0d 100644 --- a/durable/store.go +++ b/durable/store.go @@ -83,6 +83,47 @@ type Record struct { // (zero for a tick that found nothing due). It lets replay advance its step // accounting across a re-derived tick without a recorded Event per timer. TickSteps int + + // EndedActors, when set, holds the child-machine actors the instance's state + // declared once this step ended that ran and have ended, settled or stopped, or + // whose spawn failed and whose onError applied, or was refused for a reason + // other than a context ending (the journal holds that onError, or the refusal + // replay meets again), so Recover doesn't spawn them again. An actor whose spawn + // failed with no onError declared isn't one, and + // neither is one whose onError a context's ending refused, since the step that + // drove it records nothing: Recover tries both again. The first step after Start records the + // set, and later steps record it when they change it. It is nil otherwise, for a + // machine with no actor palette, and on a Record from before this field. An empty + // set is not nil: a Store must keep it, though it treats other empty fields as nil. + EndedActors *ActorSet `json:",omitempty"` + + // UnstartedActors, when set, holds the child-machine actors the instance's state + // declared once this step ended that aren't running and haven't ended: their latest + // spawn failed with no onError declared, or its onError was refused because a + // context ended, which + // left the step that drove it recording nothing. Recover + // spawns them as new, so the messages they send the parent as they start apply and + // are journaled. A declared actor in neither set was running, or a Recover's respawn + // of it failed, and the journal holds every parent Fire its start drove, so Recover + // spawns it again without letting those reach the parent. It's + // recorded as EndedActors is: with the first step after Start, then when a step + // changes it, and an empty set is not nil. When the journal holds none, as on a + // Record from before this field, Recover lets every spawn reach the parent. + UnstartedActors *ActorSet `json:",omitempty"` + + // Format is the journal format of the durable version that wrote the Record: zero on a + // Record from before this field, and 1 from the version that arms the timers and + // services an actor-driven parent Fire's state declares. Replay arms them only for a + // Record of format 1 or later, since an older run took no clock read for them. A + // Store keeps it as it keeps Step. + Format int `json:",omitempty"` +} + +// ActorSet is a set of child-machine actor ids at a point in a durable instance's +// journal. +type ActorSet struct { + // IDs are the actors' ids, sorted. + IDs []string `json:"ids"` } // followingStep returns the step ordinal after r. A tick barrier consumes one @@ -118,7 +159,9 @@ func (r *Record) followingStep() int { // already-checkpointed Step is still recognized rather than rejected as out of // order, and a different Record there is still a conflict. Two Records are the // same when every field matches, with a nil and an empty field counting as equal, -// except EventDataError, where nil means no error and an empty message is an error. +// except EventDataError, where nil means no error and an empty message is an error, +// and EndedActors and UnstartedActors, where nil means none recorded and an empty set +// means none. // An Append carrying WithIdempotencyKey (a backend reads it with // AppendIdempotencyKey) dedups on that key alone, so the caller vouches for the // Record: no comparison is made. Keys starting "step:" are reserved for the Store's diff --git a/durable/store_format_test.go b/durable/store_format_test.go new file mode 100644 index 00000000..d4de30be --- /dev/null +++ b/durable/store_format_test.go @@ -0,0 +1,47 @@ +package durable_test + +import ( + "context" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// formatDroppingStore is a Store that keeps every Record field but Format, as a +// custom backend with a schema from before that field would. +type formatDroppingStore struct{ *durable.MemStore } + +func (s formatDroppingStore) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { + rec.Format = 0 + return s.MemStore.Append(ctx, id, rec, opts...) +} + +// TestRecover_FromAStoreThatDropsFormat pins that Recover fails when a Store loses +// Record.Format, rather than replay the Records as an older format's and silently +// skip the timer an actor-driven Fire armed live. +func TestRecover_FromAStoreThatDropsFormat(t *testing.T) { + ctx := context.Background() + m := armedMachine() + clk := state.NewFakeClock(epoch) + opts := armedOptions(clk, true) + store, id := formatDroppingStore{durable.NewMemStore()}, durable.InstanceID("armed") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if found, deliverErr := h.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("armed", "working", 0)}, "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActor = %v, %v", found, deliverErr) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + clk.Advance(10 * time.Second) + if _, err := durable.Recover(ctx, m, store, id, opts...); err == nil { + t.Fatal("Recover from a Store that dropped Format succeeded; want it to fail rather than recover without the timer the live run armed") + } +} diff --git a/durable/tick_drivers_test.go b/durable/tick_drivers_test.go new file mode 100644 index 00000000..4c8cd73b --- /dev/null +++ b/durable/tick_drivers_test.go @@ -0,0 +1,108 @@ +package durable_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestTick_ATimerThatLeavesAServiceStateStopsTheService pins that a timer-driven +// transition out of a state stops the service that state invokes, as a host Fire's +// exit does: after the Tick, RunService reports no service in flight. +func TestTick_ATimerThatLeavesAServiceStateStopsTheService(t *testing.T) { + t.Skip("Tick hands a timer transition's effects only to the scheduler, not the service and actor drivers; #236 fixes it") + ctx := context.Background() + var runs int + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { runs++; return "ok", nil } + m := state.ForgeFor[stepCtx]("tickExit"). + Service("fetch", fetch). + State("idle"). + State("fetching").Invoke("fetch", state.WithInvokeOnDone("fetched")). + State("timedOut"). + Initial("idle"). + Transition("idle").On("begin").GoTo("fetching"). + Transition("fetching").On("fetched").GoTo("fetching"). + Transition("fetching").After(5 * time.Second).On("timeout").GoTo("timedOut"). + Quench() + clk := state.NewFakeClock(epoch) + h, err := durable.NewRunner(m, durable.NewMemStore(), + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch)), + ).Start(ctx, "tick-exit", stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "begin"); err != nil { + t.Fatalf("Fire(begin): %v", err) + } + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := h.Instance().Current(); got != "timedOut" { + t.Fatalf("state = %q, want timedOut", got) + } + if _, ran, err := h.RunService(ctx, state.InvokeID("tickExit", "fetching", 0)); ran || err != nil { + t.Fatalf("RunService after the timer left fetching = ran %v, %v (runs %d), want no service in flight", ran, err, runs) + } +} + +// TestRecover_ATickEnteredStatesActorMatchesLive pins that Recover leaves a state a +// timer entered with the actors the live run had: live, a Tick that enters greeting +// spawns its greeter, whose hello applies once; Recover then applies it no more and no +// less than live. +func TestRecover_ATickEnteredStatesActorMatchesLive(t *testing.T) { + t.Skip("Tick hands a timer transition's effects only to the scheduler, not the service and actor drivers; #236 fixes it") + ctx := context.Background() + note := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "hello") + return c + } + m := state.ForgeFor[stepCtx]("tickEnter"). + Reducer("note", note). + Actor("greeter"). + State("idle"). + State("waiting"). + State("greeting").InvokeActor("greeter"). + Initial("idle"). + Transition("idle").On("go").GoTo("waiting"). + Transition("waiting").After(5 * time.Second).On("due").GoTo("greeting"). + Transition("greeting").On("hello").GoTo("greeting").Assign("note"). + Transition("greeting").On("poke").GoTo("greeting"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { return &reentryGreeter{}, nil }, + }), + } + store, id := durable.NewMemStore(), durable.InstanceID("tick-enter") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + live := fmt.Sprint(h.Instance().Entity().Notes) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != live || live != "[hello]" { + t.Fatalf("live notes %s, recovered %s; want [hello] for both: the Tick's state spawns its greeter once", live, got) + } +} diff --git a/durable/timer_checkpoint_test.go b/durable/timer_checkpoint_test.go index 3834a216..9d3ac771 100644 --- a/durable/timer_checkpoint_test.go +++ b/durable/timer_checkpoint_test.go @@ -2,6 +2,7 @@ package durable_test import ( "context" + "sync" "testing" "time" @@ -381,3 +382,113 @@ func TestTimerCheckpoint_RecoveryDeterministic(t *testing.T) { t.Fatalf("recovery across checkpoint nondeterministic\n first: %s\n second: %s", first, second) } } + +// steppingClock is a Clock that moves step past each reading it returns, as a wall +// clock moves between the reads of one Tick. +type steppingClock struct { + mu sync.Mutex + now time.Time + step time.Duration +} + +func (c *steppingClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + t := c.now + c.now = c.now.Add(c.step) + return t +} + +func (c *steppingClock) After(d time.Duration) <-chan time.Time { + ch := make(chan time.Time, 1) + ch <- c.Now().Add(d) + return ch +} + +func (c *steppingClock) Advance(d time.Duration) { + c.mu.Lock() + c.now = c.now.Add(d) + c.mu.Unlock() +} + +// TestTick_DropsEachTimerItFired proves the timer table a checkpoint persists after a +// Tick holds none of the timers the Tick fired, so a Recover from it doesn't fire one +// again: not a chained zero-delay timer the Tick armed and fired in the same pass, and +// not a timer that came due between the Tick's first clock read and a later one, as +// a wall clock moves on. Each fired transition stays in its state, so no cancel drops +// the timer. The checkpoint is the live run's, or one a recovered Handle takes after +// replaying the Tick. +func TestTick_DropsEachTimerItFired(t *testing.T) { + ctx := context.Background() + for _, how := range []string{"chained zero delay", "due between reads"} { + for _, where := range []string{"live checkpoint", "replayed checkpoint"} { + t.Run(how+"/"+where, func(t *testing.T) { + b := state.ForgeFor[stepCtx]("fired"). + State("idle"). + State("first"). + State("second"). + Initial("idle"). + Transition("idle").On("arm").GoTo("first"). + Transition("second").On("poke").GoTo("second"). + Transition("first").On("poke").GoTo("first") + var clk interface { + state.Clock + Advance(time.Duration) + } + wantFired := 2 + if how == "chained zero delay" { + // first's timer enters second, whose zero-delay timer is due at once. + b = b.Transition("first").After(10 * time.Second).On("toSecond").GoTo("second"). + Transition("second").After(0).On("zero").GoTo("second") + clk = state.NewFakeClock(epoch) + } else { + // Two timers 1ms apart; each read moves the clock 1ms, so the second + // comes due at the Tick's third read. + b = b.Transition("first").After(10 * time.Second).On("a").GoTo("first"). + Transition("first").After(10*time.Second + time.Millisecond).On("b").GoTo("first") + clk = &steppingClock{now: epoch, step: time.Millisecond} + } + m := b.Quench() + opts := []stepOption{durable.WithRunnerClock[string, string, stepCtx](clk)} + checkpointing := append(opts[:len(opts):len(opts)], durable.WithCheckpointEvery[string, string, stepCtx](1)) + live := checkpointing + if where == "replayed checkpoint" { + live = opts + } + store, id := durable.NewMemStore(), durable.InstanceID("fired") + h, err := durable.NewRunner(m, store, live...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + // The arming read moved a stepping clock 1ms: land the Tick's first read at + // the first timer's deadline. + if how == "due between reads" { + clk.Advance(10*time.Second - time.Millisecond) + } else { + clk.Advance(10 * time.Second) + } + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != wantFired { + t.Fatalf("Tick = %d results, %v, want %d", len(results), tickErr, wantFired) + } + if where == "replayed checkpoint" { + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the journal: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + } + recovered, err := durable.Recover(ctx, m, store, id, checkpointing...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if results, tickErr := recovered.Tick(ctx); tickErr != nil || len(results) != 0 { + t.Fatalf("Tick after Recover = %d results, %v, want none: the Tick before it fired every due timer", len(results), tickErr) + } + }) + } + } +} diff --git a/durable/timetravel.go b/durable/timetravel.go index ed19ff79..82518afc 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -101,7 +101,8 @@ func (v *TimeTravelView[S, E, C]) Step() int { return v.step } // historical read applies no side effect. // // step must be in [BaselineStep, lastRecordedStep]; a step outside that range -// reports ErrStepOutOfRange, and an unknown instance reports ErrInstanceNotFound. +// reports ErrStepOutOfRange, an unknown instance reports ErrInstanceNotFound, and an +// ended ctx reports its error. func StateAt[S comparable, E comparable, C any]( ctx context.Context, m *state.Machine[S, E, C], @@ -137,7 +138,7 @@ func StateAt[S comparable, E comparable, C any]( return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } - if err := replayThrough(ctx, inst, &cfg, bounded); err != nil { + if err := replayThrough(ctx, inst, &cfg, bounded, unmarshalCheckpoint(baseline).Format); err != nil { return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } return &TimeTravelView[S, E, C]{inst: inst, step: step}, nil @@ -202,11 +203,7 @@ func restoreBaseline[S comparable, E comparable, C any]( baseline []byte, repClock state.Clock, ) (*state.Instance[S, E, C], error) { - kernelSnap, _, _, err := unmarshalCheckpoint(baseline) - if err != nil { - return nil, fmt.Errorf("unmarshaling baseline envelope: %w", err) - } - snap, err := state.UnmarshalSnapshot[S, E, C](kernelSnap) + snap, err := state.UnmarshalSnapshot[S, E, C](unmarshalCheckpoint(baseline).Snapshot) if err != nil { return nil, fmt.Errorf("unmarshaling baseline snapshot: %w", err) } @@ -232,6 +229,7 @@ func replayThrough[S comparable, E comparable, C any]( inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], bounded []Record, + format int, ) error { sched := state.NewScheduler(inst) @@ -241,48 +239,23 @@ func replayThrough[S comparable, E comparable, C any]( } for i := range bounded { - rec := &bounded[i] - switch { - case hasActorEntry(rec): - for _, entry := range actorEntries(rec) { - if err := replayActor(ctx, inst, cfg.eventCodec, entry); err != nil { - return fmt.Errorf("at step %d: %w", rec.Step, err) - } - } - case hasServiceEntry(rec): - for _, entry := range serviceEntries(rec) { - if err := replayService(ctx, svc, entry); err != nil { - return fmt.Errorf("at step %d: %w", rec.Step, err) - } - } - case rec.Tick: - sched.Tick(ctx) - case len(rec.Event) == 0: - continue // a checkpoint-only Record drives no event - default: - event, err := cfg.eventCodec.Decode(rec.Event) - if err != nil { - return fmt.Errorf("decoding recorded event at step %d: %w", rec.Step, err) - } - fireOpts, err := replayFireOptions(rec, event, cfg.eventDataDecoder) - if err != nil { - return fmt.Errorf("decoding recorded event data at step %d: %w", rec.Step, err) - } - res := inst.Fire(ctx, event, fireOpts...) - if res.Err != nil { - return fmt.Errorf("replaying step %d: %w", rec.Step, res.Err) - } - if hasTimerEffect(res.Effects) { - sched.Absorb(ctx, res.Effects) - } - if svc != nil { - svc.Absorb(ctx, res.Effects) - } - // A domain effect is intentionally NOT dispatched here: a time-travel read - // applies no side effect. + // A canceled context can stop a replayed settle or tick with no error, leaving + // state short of the journal, so check it before each Record. + if err := ctx.Err(); err != nil { + return err + } + // A domain effect is never dispatched here: a time-travel read applies no + // side effect. + if err := checkFormat(format, &bounded[i]); err != nil { + return err + } + if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, armsActorFires(&bounded[i])); err != nil { + return err } } - return nil + // A canceled context can stop a replayed settle or tick without an error reaching + // here, which would hand back a view short of the journal. + return ctx.Err() } // boundRecords returns the prefix of records whose first ordinal falls at or below diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 1d55a005..6617e6a6 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -13,6 +13,29 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Added +- **`ErrNoTransition`** matches, with `errors.Is`, the `*InvalidTransitionError` a `Fire` + returns when the active configuration declares no transition for the event, and no + host-built error with the same `Reason`. It's additive, within v1.1.0. +- **`ActorSystem.WithParentFireObserver`** calls a function with each parent Fire the + system drives (a `ParentFire`: its result, refused ones included, the actor it came + from, whether it settled that actor, with its output or error, and whether it routed + the onError of a spawn that couldn't start), so a host that records a delivery or spawn + can tell a parent transition refused because its context ended from one that applied, + and which Fire carried the actor's output. It's additive, within v1.1.0. +- **`Scheduler.Due`** reports when a pending timer is due, so a host that keeps its own + record of armed timers' deadlines, as `durable` does for a checkpoint, reads the one + the scheduler holds rather than working it out from a clock read of its own. It's + additive, within v1.1.0. +- **`ActorSystem.AbsorbRespawn`** is `Absorb` for actors a host spawns again after + rebuilding the parent from a record that already holds every parent Fire their + earlier start drove: an actor it spawns starts as under `Absorb`, but its start + doesn't reach the parent, neither a message sent to the parent nor the onDone or + onError of a nested actor it spawns. The onError of a respawn that can't start, and + the onDone or onError of a respawned actor that settles as the others start, still + fire the parent, since that actor was running. A nested actor's failure with no + onError doesn't escalate again, since its start already escalated it; a respawned + actor's own failure with no onError does. The durable runner's `Recover` uses it for + the actors that were running. It's additive, within v1.1.0. - **`FireEventData`** reports the payload a `WithEventData` option carries, so a host that records a Fire can persist it. It's additive, so the next release is v1.1.0. - **Callbacks get the step's context.** `GuardCtx`, `ActionCtx` and `AssignCtx` have a new @@ -43,6 +66,13 @@ counts as an additive (minor) versus breaking (major) change. Use the transitions' guards ran now fails, whether or not one was chosen, where it could succeed before. +### Fixed + +- **`AbsorbRespawn` quiets only the actors it spawns.** Its quiet was one flag for the + whole system, so a message another goroutine's delivery sent the parent while it ran + was dropped. The quiet now rides the call chain that spawns each actor, and ends when + `AbsorbRespawn` returns. + ## [1.0.0] — 2026-06-13 The first stable release. It freezes the data model, the serialized IR, the diff --git a/state/actor_parent_fire_observer_test.go b/state/actor_parent_fire_observer_test.go new file mode 100644 index 00000000..2cd99ce9 --- /dev/null +++ b/state/actor_parent_fire_observer_test.go @@ -0,0 +1,51 @@ +package state_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestActorSystem_WithParentFireObserver_SeesEachParentFire proves the observer gets +// every parent Fire the system drives, in fire order, a refused one included with its +// error, and marks the Fire that settled the actor: here a child's message to the +// parent, then its onDone, which a guard refuses. +func TestActorSystem_WithParentFireObserver_SeesEachParentFire(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("watcher"). + Guard("never", func(state.GuardCtx[*trec]) bool { return false }). + Actor("relay"). + State("watching").InvokeActor("relay", state.WithInvokeOnDone("relayDone")). + State("finished").Final(). + Initial("watching"). + Transition("watching").On("pong").GoTo("watching"). + Transition("watching").On("relayDone").GoTo("finished").When("never"). + Quench() + parent := m.Cast(&trec{}, state.WithInitialState("watching")) + var seen []state.ParentFire[string] + sys := state.NewActorSystem(parent). + Register("relay", relayBehavior()). + WithParentFireObserver(func(pf state.ParentFire[string]) { seen = append(seen, pf) }) + sys.Absorb(ctx, parent.StartEffects()) + ref, ok := sys.Ref(state.ActorID("watcher", "watching", 0)) + if !ok { + t.Fatal("the relay child didn't spawn") + } + + sys.Deliver(ctx, ref, "ping") // the child sends the parent "pong" + sys.Deliver(ctx, ref, "finish") + + if len(seen) != 2 { + t.Fatalf("observed %d parent Fires, want 2 (the message, then the onDone)", len(seen)) + } + if r := seen[0].Result; r.Err != nil || r.Trace.Event != "pong" || seen[0].Settle { + t.Fatalf("first = %q, err %v, settle %v, want the applied pong message", r.Trace.Event, r.Err, seen[0].Settle) + } + if seen[1].Result.Err == nil || !seen[1].Settle { + t.Fatalf("second = err %v, settle %v, want the guard-refused onDone, settling", seen[1].Result.Err, seen[1].Settle) + } + if got := parent.Current(); got != "watching" { + t.Fatalf("parent = %q, want watching after the refused onDone", got) + } +} diff --git a/state/actor_respawn_lift_test.go b/state/actor_respawn_lift_test.go new file mode 100644 index 00000000..9880f043 --- /dev/null +++ b/state/actor_respawn_lift_test.go @@ -0,0 +1,40 @@ +package state_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestActorSystem_AbsorbRespawn_DoesNotMuteAnotherActorsDelivery pins that the quiet of +// an AbsorbRespawn covers only the actors it spawns: a delivery to another actor that +// was already running, made while AbsorbRespawn is under way (as another goroutine +// can), reaches the parent with the message it drives. +func TestActorSystem_AbsorbRespawn_DoesNotMuteAnotherActorsDelivery(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("mute"). + Actor("pinger"). + Actor("late"). + State("waiting").InvokeActor("pinger").InvokeActor("late"). + State("hellod"). + Initial("waiting"). + Transition("waiting").On("hello").GoTo("hellod"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("waiting")) + sys := state.NewActorSystem(inst) + sys.Register("pinger", func(map[string]any) (state.ActorInstance, error) { return &pinger{}, nil }) + pingerID := state.ActorID("mute", "waiting", 0) + sys.Register("late", func(map[string]any) (state.ActorInstance, error) { + // Another goroutine's delivery, landing while AbsorbRespawn runs. + sys.DeliverByID(ctx, pingerID, "ping") + return &startGreeter{sent: true}, nil + }) + effects := inst.StartEffects() + // The pinger was already running, started as usual. + sys.Absorb(ctx, effects[:1]) + sys.AbsorbRespawn(ctx, effects[1:]) + if got := inst.Current(); got != "hellod" { + t.Fatalf("the pinger's hello, delivered during AbsorbRespawn, left the parent in %q, want hellod", got) + } +} diff --git a/state/actor_respawn_test.go b/state/actor_respawn_test.go new file mode 100644 index 00000000..13d52f72 --- /dev/null +++ b/state/actor_respawn_test.go @@ -0,0 +1,333 @@ +package state_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// startGreeter is an actor that sends its parent "hello" from its initial entry, then +// keeps running. +type startGreeter struct{ sent bool } + +func (g *startGreeter) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (g *startGreeter) ChildEffects() []state.Effect { + if g.sent { + return nil + } + g.sent = true + return []state.Effect{state.SendParent{Event: "hello"}} +} +func (g *startGreeter) Output() any { return nil } + +// TestActorSystem_AbsorbRespawn_DropsStartMessages proves an actor AbsorbRespawn spawns +// runs, but the message it sends the parent as it starts doesn't reach the parent, as it +// does under Absorb, while a spawn that can't start still routes its onError. +func TestActorSystem_AbsorbRespawn_DropsStartMessages(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("respawn"). + Actor("greeter"). + Actor("broken"). + State("greeting").InvokeActor("greeter").InvokeActor("broken", state.WithInvokeOnError("brokenFailed")). + State("hellod"). + State("failed"). + Initial("greeting"). + Transition("greeting").On("hello").GoTo("hellod"). + Transition("greeting").On("brokenFailed").GoTo("failed"). + Quench() + behaviors := func(sys *state.ActorSystem[string, string, *trec], broken bool) { + sys.Register("greeter", func(map[string]any) (state.ActorInstance, error) { return &startGreeter{}, nil }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { + if broken { + return nil, errors.New("can't start") + } + return &startGreeter{sent: true}, nil + }) + } + + live := m.Cast(&trec{}, state.WithInitialState("greeting")) + liveSys := state.NewActorSystem(live) + behaviors(liveSys, false) + liveSys.Absorb(ctx, live.StartEffects()) + if got := live.Current(); got != "hellod" { + t.Fatalf("Absorb left the parent in %q, want hellod from the greeter's start", got) + } + + resumed := m.Cast(&trec{}, state.WithInitialState("greeting")) + var seen []state.ParentFire[string] + sys := state.NewActorSystem(resumed). + WithParentFireObserver(func(pf state.ParentFire[string]) { seen = append(seen, pf) }) + behaviors(sys, false) + sys.AbsorbRespawn(ctx, resumed.StartEffects()) + if got := resumed.Current(); got != "greeting" { + t.Fatalf("AbsorbRespawn left the parent in %q, want greeting: the start message should be dropped", got) + } + if len(seen) != 0 { + t.Fatalf("observed %d parent Fires, want none", len(seen)) + } + if !sys.IsRunning(state.ActorID("respawn", "greeting", 0)) { + t.Fatal("AbsorbRespawn didn't spawn the greeter") + } + + failing := m.Cast(&trec{}, state.WithInitialState("greeting")) + failSys := state.NewActorSystem(failing) + behaviors(failSys, true) + failSys.AbsorbRespawn(ctx, []state.Effect{failing.StartEffects()[1]}) + if got := failing.Current(); got != "failed" { + t.Fatalf("AbsorbRespawn of a spawn that can't start left the parent in %q, want failed by its onError", got) + } +} + +// starter is an actor that sends its first effects from its initial entry, then keeps +// running; finish ends it with no output. +type starter struct{ start []state.Effect } + +func (a *starter) DeliverFire(_ context.Context, ev any) (bool, any) { return ev == "finish", nil } +func (a *starter) ChildEffects() []state.Effect { + out := a.start + a.start = nil + return out +} +func (a *starter) Output() any { return nil } + +// TestActorSystem_AbsorbRespawn_ParentFiresItDrivesAreAudible proves the quiet of an +// AbsorbRespawn spawn covers only the spawned actor's own start: the onError of a spawn +// that can't start, and the onDone of an actor a respawned one ends as it starts, are +// parent Fires the earlier start didn't send, so the greeter their state spawns reaches +// the parent with its hello, as under Absorb. +func TestActorSystem_AbsorbRespawn_ParentFiresItDrivesAreAudible(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("audible"). + Actor("greeter"). + Actor("broken"). + Actor("finisher"). + Actor("poker"). + State("failing").InvokeActor("broken", state.WithInvokeOnError("brokenFailed")). + State("pair").InvokeActor("finisher", state.WithInvokeOnDone("finished")).InvokeActor("poker"). + State("greeting").InvokeActor("greeter"). + State("hellod"). + Initial("failing"). + Transition("failing").On("brokenFailed").GoTo("greeting"). + Transition("pair").On("finished").GoTo("greeting"). + Transition("greeting").On("hello").GoTo("hellod"). + Quench() + finisher := state.ActorID("audible", "pair", 0) + for _, from := range []string{"failing", "pair"} { + t.Run(from, func(t *testing.T) { + inst := m.Cast(&trec{}, state.WithInitialState(from)) + sys := state.NewActorSystem(inst) + sys.Register("greeter", func(map[string]any) (state.ActorInstance, error) { return &startGreeter{}, nil }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("can't start") }) + sys.Register("finisher", func(map[string]any) (state.ActorInstance, error) { return &starter{}, nil }) + sys.Register("poker", func(map[string]any) (state.ActorInstance, error) { + return &starter{start: []state.Effect{state.SendTo{TargetID: finisher, Event: "finish"}}}, nil + }) + sys.AbsorbRespawn(ctx, inst.StartEffects()) + if got := inst.Current(); got != "hellod" { + t.Fatalf("AbsorbRespawn from %s left the parent in %q, want hellod: the greeter its onError or onDone spawned should reach the parent", from, got) + } + }) + } +} + +// TestActorSystem_AbsorbRespawn_NestedStartFiresStayQuiet proves the quiet of an +// AbsorbRespawn spawn covers a nested actor the respawned one spawns as it starts: the +// onError of a nested spawn that can't start, and the onDone of a nested actor the +// respawned one ends as it starts, are parent Fires its earlier start drove, so neither +// fires the parent again, though each does under Absorb. +func TestActorSystem_AbsorbRespawn_NestedStartFiresStayQuiet(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("nested"). + Actor("host"). + State("hosting").InvokeActor("host"). + State("heard"). + Initial("hosting"). + Transition("hosting").On("nestedFailed").GoTo("heard"). + Transition("hosting").On("nestedDone").GoTo("heard"). + Quench() + starts := map[string][]state.Effect{ + "fails": {state.SpawnActor{ID: "child", Src: state.Ref{Name: "broken"}, OnError: "nestedFailed"}}, + "settles": { + state.SpawnActor{ID: "child", Src: state.Ref{Name: "finisher"}, OnDone: "nestedDone"}, + state.SendTo{TargetID: "child", Event: "finish"}, + }, + } + for _, how := range []string{"fails", "settles"} { + t.Run(how, func(t *testing.T) { + build := func() (*state.Instance[string, string, *trec], *state.ActorSystem[string, string, *trec]) { + inst := m.Cast(&trec{}, state.WithInitialState("hosting")) + sys := state.NewActorSystem(inst) + sys.Register("host", func(map[string]any) (state.ActorInstance, error) { return &starter{start: starts[how]}, nil }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("can't start") }) + sys.Register("finisher", func(map[string]any) (state.ActorInstance, error) { return &starter{}, nil }) + return inst, sys + } + live, liveSys := build() + liveSys.Absorb(ctx, live.StartEffects()) + if got := live.Current(); got != "heard" { + t.Fatalf("Absorb left the parent in %q, want heard: the nested child's Fire should reach it", got) + } + resumed, sys := build() + var seen []state.ParentFire[string] + sys.WithParentFireObserver(func(pf state.ParentFire[string]) { seen = append(seen, pf) }) + sys.AbsorbRespawn(ctx, resumed.StartEffects()) + if got := resumed.Current(); got != "hosting" { + t.Fatalf("AbsorbRespawn left the parent in %q, want hosting: the nested child's Fire is part of the host's start", got) + } + if len(seen) != 0 { + t.Fatalf("observed %d parent Fires, want none", len(seen)) + } + }) + } +} + +// TestActorSystem_AbsorbRespawn_QuietResumesAfterANewFire proves a parent Fire +// AbsorbRespawn lets through, the onDone of a respawned actor another one's start ends, +// hears the parent only while it and its effects run: the hello the second actor's start +// sends next is still part of that start, and is dropped. +func TestActorSystem_AbsorbRespawn_QuietResumesAfterANewFire(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("resume"). + Actor("finisher"). + Actor("poker"). + State("pair").InvokeActor("finisher", state.WithInvokeOnDone("finished")).InvokeActor("poker"). + State("finishedState"). + State("hellod"). + Initial("pair"). + Transition("pair").On("finished").GoTo("finishedState"). + Transition("finishedState").On("hello").GoTo("hellod"). + Quench() + finisher := state.ActorID("resume", "pair", 0) + inst := m.Cast(&trec{}, state.WithInitialState("pair")) + sys := state.NewActorSystem(inst) + sys.Register("finisher", func(map[string]any) (state.ActorInstance, error) { return &starter{}, nil }) + sys.Register("poker", func(map[string]any) (state.ActorInstance, error) { + return &starter{start: []state.Effect{ + state.SendTo{TargetID: finisher, Event: "finish"}, + state.SendParent{Event: "hello"}, + }}, nil + }) + sys.AbsorbRespawn(ctx, inst.StartEffects()) + if got := inst.Current(); got != "finishedState" { + t.Fatalf("AbsorbRespawn left the parent in %q, want finishedState: the finisher's onDone is new, but the poker's hello is part of its start", got) + } +} + +// pinger is an actor that sends its parent "hello" each time it's delivered "ping". +type pinger struct{ out []state.Effect } + +func (p *pinger) DeliverFire(_ context.Context, ev any) (bool, any) { + if ev == "ping" { + p.out = []state.Effect{state.SendParent{Event: "hello"}} + } + return false, nil +} + +func (p *pinger) ChildEffects() []state.Effect { + out := p.out + p.out = nil + return out +} + +func (p *pinger) Output() any { return nil } + +// TestActorSystem_AbsorbRespawn_QuietEndsWithIt proves the quiet of an AbsorbRespawn +// spawn ends when it returns, even for the context the actor's behavior got: a delivery +// made later with that context reaches the parent with the message it drives. +func TestActorSystem_AbsorbRespawn_QuietEndsWithIt(t *testing.T) { + m := state.ForgeFor[*trec]("after"). + Actor("pinger"). + State("waiting").InvokeActor("pinger"). + State("hellod"). + Initial("waiting"). + Transition("waiting").On("hello").GoTo("hellod"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("waiting")) + sys := state.NewActorSystem(inst) + var captured context.Context + sys.RegisterContext("pinger", func(ctx context.Context, _ map[string]any) (state.ActorInstance, error) { + captured = ctx + return &pinger{}, nil + }) + sys.AbsorbRespawn(context.Background(), inst.StartEffects()) + if !sys.DeliverByID(captured, state.ActorID("after", "waiting", 0), "ping") { + t.Fatal("the pinger isn't running") + } + if got := inst.Current(); got != "hellod" { + t.Fatalf("a delivery after AbsorbRespawn left the parent in %q, want hellod: its hello should reach the parent", got) + } +} + +// crasher is an actor that panics when it's delivered "crash". +type crasher struct{} + +func (crasher) DeliverFire(_ context.Context, ev any) (bool, any) { + if ev == "crash" { + panic("crash") + } + return false, nil +} +func (crasher) ChildEffects() []state.Effect { return nil } +func (crasher) Output() any { return nil } + +// TestActorSystem_AbsorbRespawn_DoesNotEscalateANestedStartFailureAgain proves a nested +// actor's failure with no onError, one whose spawn can't start or one that crashes as +// the respawned actor starts, escalates under Absorb but not again under AbsorbRespawn: +// it's part of the respawned actor's start, which escalated it when it first happened. +// A respawned actor whose own spawn fails now, with no onError, still escalates. +func TestActorSystem_AbsorbRespawn_DoesNotEscalateANestedStartFailureAgain(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("escalate"). + Actor("host"). + State("hosting").InvokeActor("host"). + Initial("hosting"). + Quench() + starts := map[string][]state.Effect{ + "fails": {state.SpawnActor{ID: "child", Src: state.Ref{Name: "broken"}}}, + "crashes": { + state.SpawnActor{ID: "child", Src: state.Ref{Name: "crasher"}}, + state.SendTo{TargetID: "child", Event: "crash"}, + }, + } + build := func(how string, hostStarts bool, escalations *int) (*state.Instance[string, string, *trec], *state.ActorSystem[string, string, *trec]) { + inst := m.Cast(&trec{}, state.WithInitialState("hosting")) + sys := state.NewActorSystem(inst). + WithEscalationHandler(func(context.Context, *state.ActorEscalation) { *escalations++ }) + sys.Register("host", func(map[string]any) (state.ActorInstance, error) { + if !hostStarts { + return nil, errors.New("can't start") + } + return &starter{start: starts[how]}, nil + }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("can't start") }) + sys.Register("crasher", func(map[string]any) (state.ActorInstance, error) { return crasher{}, nil }) + return inst, sys + } + for _, how := range []string{"fails", "crashes"} { + t.Run(how, func(t *testing.T) { + var live int + inst, sys := build(how, true, &live) + sys.Absorb(ctx, inst.StartEffects()) + if live != 1 { + t.Fatalf("Absorb escalated %d times, want once", live) + } + var respawned int + inst, sys = build(how, true, &respawned) + sys.AbsorbRespawn(ctx, inst.StartEffects()) + if respawned != 0 { + t.Fatalf("AbsorbRespawn escalated %d times, want none: the nested failure is part of the host's start", respawned) + } + }) + } + t.Run("respawned actor fails", func(t *testing.T) { + var n int + _, sys := build("fails", false, &n) + // A spawn with no onError, as an actor's own spawns are. + sys.AbsorbRespawn(ctx, []state.Effect{state.SpawnActor{ID: "host", Src: state.Ref{Name: "host"}}}) + if n != 1 { + t.Fatalf("AbsorbRespawn escalated %d times, want once: the respawned actor's own failure is new", n) + } + }) +} diff --git a/state/actor_restore_pending_test.go b/state/actor_restore_pending_test.go new file mode 100644 index 00000000..31544c32 --- /dev/null +++ b/state/actor_restore_pending_test.go @@ -0,0 +1,71 @@ +package state_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestRestoreActors_DoesNotRespawnANestedActorThatSettled pins that an actor restored +// from a snapshot doesn't spawn a nested actor its earlier start spawned, once that +// nested actor settled and moved the actor on: the restored actor resumes, so the +// spawn its fresh Cast buffered is stale. +func TestRestoreActors_DoesNotRespawnANestedActorThatSettled(t *testing.T) { + for _, compound := range []bool{false} { + ctx := context.Background() + nestedRuns := 0 + cb := state.ForgeFor[*childEntity]("child").Actor("nested") + if compound { + cb = cb.SuperState("p").InvokeActor("nested", state.WithInvokeOnDone("nestedDone"), state.WithInvokeID("nested")). + SubState("a"). + SubState("b"). + Initial("a"). + EndSuperState(). + Initial("p") + } else { + cb = cb.State("a").InvokeActor("nested", state.WithInvokeOnDone("nestedDone"), state.WithInvokeID("nested")). + State("b"). + Initial("a") + } + child := cb.Transition("a").On("nestedDone").GoTo("b"). + Transition("b").On("poke").GoTo("b"). + Quench() + parent := state.ForgeFor[*trec]("parent"). + Actor("child"). + State("supervising").InvokeActor("child", state.WithInvokeID("child")). + Initial("supervising"). + Quench() + register := func(sys *state.ActorSystem[string, string, *trec]) { + sys.Register("child", func(map[string]any) (state.ActorInstance, error) { + return state.NewActor(child.Cast(&childEntity{}, state.WithInitialState("a")), nil), nil + }) + sys.Register("nested", func(in map[string]any) (state.ActorInstance, error) { + nestedRuns++ + return childBehavior()(in) + }) + } + inst := parent.Cast(&trec{}, state.WithInitialState("supervising")) + sys := state.NewActorSystem(inst) + register(sys) + sys.Absorb(ctx, inst.StartEffects()) + if nestedRuns != 1 { + t.Fatalf("compound=%v: nested ran %d times starting, want once", compound, nestedRuns) + } + sys.DeliverByID(ctx, "nested", "finish") + snaps, err := sys.SnapshotActors() + if err != nil { + t.Fatalf("SnapshotActors: %v", err) + } + inst2 := parent.Cast(&trec{}, state.WithInitialState("supervising")) + sys2 := state.NewActorSystem(inst2) + register(sys2) + if err = sys2.RestoreActors(ctx, snaps); err != nil { + t.Fatalf("RestoreActors: %v", err) + } + sys2.DeliverByID(ctx, "child", "poke") + if nestedRuns != 1 { + t.Fatalf("compound=%v: nested ran %d times, want once: the restored child spawned it again", compound, nestedRuns) + } + } +} diff --git a/state/actor_system.go b/state/actor_system.go index 10c7a84b..ed44394b 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -4,6 +4,7 @@ import ( "context" "sort" "sync" + "sync/atomic" ) // This file ships the reusable host-driver harness for the actor model. The @@ -155,6 +156,10 @@ type ActorSystem[S comparable, E comparable, C any] struct { // never silently swallowed. Read through LastEscalation. lastEscalation *ActorEscalation + // parentFireObserver, when set, is called with each parent Fire the system + // drives. Set with WithParentFireObserver; guarded by mu. + parentFireObserver func(ParentFire[S]) + // escalationHandler is the optional host policy invoked for each escalation. It // is nil by default — the default escalation behavior (record + inspect) needs no // handler — and wired with WithEscalationHandler. @@ -290,6 +295,94 @@ func (s *ActorSystem[S, E, C]) AbsorbFor(ctx context.Context, event any, effects s.absorb(ctx, effects, event) } +// AbsorbRespawn is Absorb for actors a host spawns again after rebuilding the parent +// from a record that already holds every parent Fire their earlier start drove, as the +// durable runner's Recover does for the actors that were running. Each actor it spawns +// starts as under Absorb, but its start doesn't reach the parent again: no message it, +// or an actor it sends to or spawns, sends the parent while it starts, and no onDone or +// onError of a nested actor its start spawns, fires the parent. Such a Fire is dropped, +// so WithParentFireObserver doesn't see it. What the earlier start can't have driven +// still fires the parent, since each actor in effects was running: the onError of one +// whose spawn fails now, and the onDone or onError of one that settles as the others +// start. A nested actor's failure with no onError doesn't escalate again either, while +// one in effects that fails now does. The effects such a Fire drives absorb as under +// Absorb: an actor its state spawns, or one it sends to, reaches the parent. Its other +// effects absorb as under Absorb. The quiet rides the call chain that spawns each actor, +// so a delivery another goroutine makes while AbsorbRespawn runs reaches the parent as +// usual, and it ends when AbsorbRespawn returns. +func (s *ActorSystem[S, E, C]) AbsorbRespawn(ctx context.Context, effects []Effect) { + respawned := map[string]bool{} + for _, eff := range effects { + if e, ok := eff.(SpawnActor); ok { + respawned[e.ID] = true + } + } + q := &respawnQuiet{respawned: respawned} + // The quiet ends with AbsorbRespawn, even for a context an actor's behavior kept. + defer q.ended.Store(true) + for _, eff := range effects { + if e, ok := eff.(SpawnActor); ok { + s.respawnOne(ctx, q, e) + continue + } + s.absorb(ctx, []Effect{eff}, nil) + } +} + +// respawnQuiet is the quiet of one AbsorbRespawn: it rides the context of the call +// chain that spawns each actor, so only that chain's messages to the parent are dropped, +// and a delivery another goroutine makes meanwhile is heard. +type respawnQuiet struct { + // respawned holds the ids of the actors AbsorbRespawn was given, whose failed spawn + // or settle fires the parent even while it's quiet. + respawned map[string]bool + // ended is set when AbsorbRespawn returns, ending the quiet. + ended atomic.Bool +} + +// quietKey is the context key a respawnQuiet rides under. +type quietKey struct{} + +// quietOf returns the quiet ctx carries, or nil when ctx carries none or AbsorbRespawn +// has returned. +func quietOf(ctx context.Context) *respawnQuiet { + q, _ := ctx.Value(quietKey{}).(*respawnQuiet) + if q == nil || q.ended.Load() { + return nil + } + return q +} + +// heard returns ctx with the quiet lifted, for a parent Fire that's new and so is all +// it drives. +func heard(ctx context.Context) context.Context { + if quietOf(ctx) == nil { + return ctx + } + return context.WithValue(ctx, quietKey{}, (*respawnQuiet)(nil)) +} + +// respawnOne spawns e with the parent quiet on its call chain, so its start doesn't +// reach the parent. +func (s *ActorSystem[S, E, C]) respawnOne(ctx context.Context, q *respawnQuiet, e SpawnActor) { + s.spawn(context.WithValue(ctx, quietKey{}, q), e) +} + +// hearing reports how a parent Fire for actor id's failed spawn or settle goes on ctx's +// call chain: dropped, when it's part of the start AbsorbRespawn is repeating, or fired +// with the parent heard again, when id is an actor AbsorbRespawn was given, which was +// running, so the Fire is new and so is all it drives. +func hearing(ctx context.Context, id string) (drop, lift bool) { + q := quietOf(ctx) + if q == nil { + return false, false + } + if q.respawned[id] { + return false, true + } + return true, false +} + // absorb scans effects emitted by the parent instance while handling curEvent, // spawning/stopping actors and routing the parent's outbound messages (the parent // is the sender). curEvent is nil for the plain Absorb path (a parent ForwardEvent @@ -381,12 +474,22 @@ func (s *ActorSystem[S, E, C]) spawn(ctx context.Context, e SpawnActor) { // failure escalates to the parent as a typed ActorEscalation rather than being // silently swallowed (the G3 default), so a spawn that cannot start is never lost. func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err error) { + drop, lift := hearing(ctx, e.ID) + // A failure the start AbsorbRespawn is repeating was routed or escalated when it + // first happened. + if drop { + return + } ev, ok := e.OnError.(E) if !ok { s.escalate(ctx, &runningActor[E]{ref: ActorRef{ID: e.ID, SystemID: e.SystemID, Src: e.Src.Name}}, "", err) return } + if lift { + ctx = heard(ctx) + } res := s.parent.Fire(ctx, ev) + s.noteParentFire(ParentFire[S]{Result: res, ActorID: e.ID, SpawnFailed: true}) s.Absorb(ctx, res.Effects) } @@ -642,6 +745,9 @@ func (s *ActorSystem[S, E, C]) resolveTarget(targetID, systemID string) (string, // drains it. This is the single path every routed message flows through, so parent // and child delivery share their sender bookkeeping. func (s *ActorSystem[S, E, C]) dispatch(ctx context.Context, targetID string, event any, senderID string) { + if targetID == parentActorID && quietOf(ctx) != nil { + return + } s.inspectMessage(senderID, targetID, MessageSent, event) if targetID == parentActorID { s.fireParentFrom(ctx, event, senderID) @@ -668,6 +774,7 @@ func (s *ActorSystem[S, E, C]) fireParentFrom(ctx context.Context, event any, se s.mu.Unlock() res := s.parent.Fire(ctx, ev) + s.noteParentFire(ParentFire[S]{Result: res, ActorID: senderID}) s.Absorb(ctx, res.Effects) s.mu.Lock() @@ -703,6 +810,7 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any } s.lastOutcome = actorOutcome{output: output, err: err, set: true} s.mu.Unlock() + drop, lift := hearing(ctx, id) // A completed actor's children are torn down with it. for _, c := range children { @@ -712,12 +820,19 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any // G3 default: an unhandled child FAILURE (no onError wired) escalates to the // parent as a typed, observable ActorEscalation rather than being silently // swallowed. A clean completion with no onDone is still a fire-and-forget - // no-op — only a failure escalates. - if err != nil { + // no-op — only a failure escalates. A failure the start AbsorbRespawn is + // repeating escalated when it first happened. + if err != nil && !drop { s.escalate(ctx, ra, parentID, err) } return FireResult[S]{}, false } + if drop { + return FireResult[S]{}, false + } + if lift { + ctx = heard(ctx) + } // Deliver the child's output/error to the parent's onDone/onError transition's // Assign through the done-event payload (AssignCtx.Event), not a side channel: // the reducer reads it from AssignCtx.Event. LastOutput/LastError remain for @@ -729,6 +844,7 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any payload = output } res := s.parent.Fire(ctx, ev, WithEventData(payload)) + s.noteParentFire(ParentFire[S]{Result: res, ActorID: id, Settle: true, Output: output, Err: err}) s.Absorb(ctx, res.Effects) return res, true } @@ -788,3 +904,53 @@ func (s *ActorSystem[S, E, C]) LastError() error { defer s.mu.Unlock() return s.lastOutcome.err } + +// ParentFire is one parent Fire an ActorSystem drove, as WithParentFireObserver +// reports it. +type ParentFire[S comparable] struct { + // Result is the parent Fire's result. A refused Fire carries its error. + Result FireResult[S] + // ActorID is the actor the Fire came from: the one that settled, sent the message, + // or couldn't start. + ActorID string + // SpawnFailed reports that the Fire routed the onError of a spawn that couldn't + // start (an unbound Src, or a behavior that returned an error). + SpawnFailed bool + // Settle reports that the Fire routed a settled actor's onDone or onError, which + // carried the actor's outcome as its event data (WithEventData): Err for an onError, + // Output for an onDone. A message the actor sent the parent, or the onError of a + // spawn that couldn't start, carries none. + Settle bool + // Output is the settled actor's output, when Settle is set and Err is nil. + Output any + // Err is the settled actor's failure, when Settle is set and it failed. + Err error +} + +// WithParentFireObserver calls observe with each parent Fire the system drives (an +// actor's onDone or onError, a message it sends the parent, a failed spawn's +// onError), in fire order, refused ones included, after the Fire returns and before +// its effects are absorbed. A host that records what a delivery or spawn drove uses +// it: a parent Fire refused because the context it ran under ended reports that +// context's error, so the host can tell a refusal it can't replay from one it can, +// and Settle, Output and Err say which Fire carried an actor's outcome, and what it +// was. observe runs on the goroutine that drove the Fire, with no lock of the system's +// held, so it may read the system but must not drive it. Calls from Fires driven on +// different goroutines can overlap, so observe must be safe for concurrent use. +// Setting it returns the system for chaining. +func (s *ActorSystem[S, E, C]) WithParentFireObserver(observe func(ParentFire[S])) *ActorSystem[S, E, C] { + s.mu.Lock() + s.parentFireObserver = observe + s.mu.Unlock() + return s +} + +// noteParentFire hands a parent Fire to the observer, if one is set. +func (s *ActorSystem[S, E, C]) noteParentFire(pf ParentFire[S]) { + s.mu.Lock() + observe := s.parentFireObserver + s.mu.Unlock() + if observe != nil { + observe(pf) + } +} diff --git a/state/driver.go b/state/driver.go index 52c7eebc..a4179eb5 100644 --- a/state/driver.go +++ b/state/driver.go @@ -105,6 +105,17 @@ func (s *Scheduler[S, E, C]) HasPending(id string) bool { return ok } +// Due reports when the pending timer id is due, and false when no timer is pending +// under id. A host that keeps its own record of armed timers' deadlines, as a durable +// runtime does for a checkpoint, reads it after Absorb or Tick, rather than working the +// deadline out from a clock reading of its own. +func (s *Scheduler[S, E, C]) Due(id string) (time.Time, bool) { + s.mu.Lock() + defer s.mu.Unlock() + p, ok := s.pending[id] + return p.due, ok +} + // Tick fires every timer whose due time is at or before the Scheduler clock's // current time, in due-time order (ties broken by id for determinism). Each due // timer is removed, then its delayed event is fired through the instance and the diff --git a/state/errors.go b/state/errors.go index 1ac786c6..0e8c9f2d 100644 --- a/state/errors.go +++ b/state/errors.go @@ -1,6 +1,7 @@ package state import ( + "errors" "fmt" "strings" "time" @@ -18,6 +19,30 @@ type InvalidTransitionError struct { To string Event string Reason string + + // noTransition marks the kernel's own refusal of an event the active + // configuration declares no transition for, which ErrNoTransition matches. + noTransition bool +} + +// ErrNoTransition matches, with errors.Is, the *InvalidTransitionError a Fire +// returns when the active configuration declares no transition for the event. It +// matches only the kernel's own refusal, not one a host builds with the same Reason. +var ErrNoTransition = errors.New("crucible/state: no transition declared for this state and event") + +// noTransitionReason is the Reason of the kernel's no-transition refusal. +const noTransitionReason = "no transition declared for this state and event" + +// newNoTransitionError returns the kernel's refusal of event in from, which has no +// transition declared for it. +func newNoTransitionError(from, event string) *InvalidTransitionError { + return &InvalidTransitionError{From: from, Event: event, Reason: noTransitionReason, noTransition: true} +} + +// Is reports whether target is ErrNoTransition and e is the kernel's no-transition +// refusal. +func (e *InvalidTransitionError) Is(target error) bool { + return target == ErrNoTransition && e.noTransition } func (e *InvalidTransitionError) Error() string { diff --git a/state/fire.go b/state/fire.go index ae3706bf..3168cc4f 100644 --- a/state/fire.go +++ b/state/fire.go @@ -604,13 +604,7 @@ func microstepOverflow[S comparable](res FireResult[S], state S) FireResult[S] { // isNoTransition reports whether err is the "no transition declared" outcome — // the benign result of a raised event the current configuration does not handle. -func isNoTransition(err error) bool { - var it *InvalidTransitionError - if as(err, &it) { - return it.Reason == "no transition declared for this state and event" - } - return false -} +func isNoTransition(err error) bool { return errors.Is(err, ErrNoTransition) } // fireOnce is the pure single-event transition step. It resolves the event // against the active configuration child-first, bubbling up through ancestors, @@ -750,11 +744,7 @@ func (i *Instance[S, E, C]) fireSpine(ctx context.Context, event E, tr Trace) Fi return FireResult[S]{NewState: from, Trace: tr, Err: lastGuardErr} } - err := &InvalidTransitionError{ - From: fmtState(from), - Event: fmt.Sprint(event), - Reason: "no transition declared for this state and event", - } + err := newNoTransitionError(fmtState(from), fmt.Sprint(event)) return FireResult[S]{NewState: from, Trace: tr, Err: err} } diff --git a/state/no_transition_test.go b/state/no_transition_test.go new file mode 100644 index 00000000..b108e74e --- /dev/null +++ b/state/no_transition_test.go @@ -0,0 +1,73 @@ +package state_test + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestErrNoTransition_MatchesOnlyTheKernelsOwnRefusal pins that errors.Is(err, +// ErrNoTransition) is true for the refusal a Fire returns when the active +// configuration declares no transition for the event, flat or parallel, wrapped or +// not, and false for any other error, including a host-built InvalidTransitionError +// worded the same way. +func TestErrNoTransition_MatchesOnlyTheKernelsOwnRefusal(t *testing.T) { + ctx := context.Background() + flat := state.ForgeFor[acct]("flat"). + State("a"). + State("b").Final(). + Initial("a"). + Transition("a").On("go").GoTo("b"). + Quench() + parallel := state.ForgeFor[acct]("par"). + SuperState("live"). + Region("r1"). + Initial("r1a"). + SubState("r1a").On("tick").GoTo("r1b"). + SubState("r1b"). + EndRegion(). + Region("r2"). + Initial("r2a"). + SubState("r2a"). + EndRegion(). + EndSuperState(). + Initial("live"). + Quench() + flatErr := flat.Cast(acct{}, state.WithInitialState[string]("a")).Fire(ctx, "nope").Err + parErr := parallel.Cast(acct{}, state.WithInitialState[string]("live")).Fire(ctx, "nope").Err + final := flat.Cast(acct{}, state.WithInitialState[string]("a")) + if res := final.Fire(ctx, "go"); res.Err != nil { + t.Fatalf("Fire(go): %v", res.Err) + } + finalErr := final.Fire(ctx, "go").Err + + cases := []struct { + name string + err error + want bool + }{ + {"flat no transition", flatErr, true}, + {"parallel no transition", parErr, true}, + {"wrapped", fmt.Errorf("host: %w", flatErr), true}, + {"other refusal", finalErr, false}, + {"lookalike", &state.InvalidTransitionError{Event: "nope", Reason: "no transition declared for this state and event"}, false}, + {"nil", nil, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if tc.want && tc.err == nil { + t.Fatal("the Fire returned no error") + } + if got := errors.Is(tc.err, state.ErrNoTransition); got != tc.want { + t.Fatalf("errors.Is(%v, ErrNoTransition) = %v, want %v", tc.err, got, tc.want) + } + }) + } + var it *state.InvalidTransitionError + if !errors.As(flatErr, &it) || it.Reason == "" { + t.Fatalf("the refusal %v is no longer an *InvalidTransitionError with a Reason", flatErr) + } +} diff --git a/state/parallel.go b/state/parallel.go index 99e10928..a8f17b15 100644 --- a/state/parallel.go +++ b/state/parallel.go @@ -644,10 +644,6 @@ func (i *Instance[S, E, C]) fireFromState(ctx context.Context, start S, event E, } } - err := &InvalidTransitionError{ - From: fmtState(from), - Event: fmt.Sprint(event), - Reason: "no transition declared for this state and event", - } + err := newNoTransitionError(fmtState(from), fmt.Sprint(event)) return FireResult[S]{NewState: from, Trace: tr, Err: err} } diff --git a/state/resume_compound_test.go b/state/resume_compound_test.go new file mode 100644 index 00000000..76e7ed59 --- /dev/null +++ b/state/resume_compound_test.go @@ -0,0 +1,46 @@ +package state_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestResumeEffects_DoesNotRestartACompoundServiceThatSettledIntoAChild pins that a host +// that restores a snapshot and absorbs ResumeEffects doesn't start a compound state's +// service again when, before the snapshot, it settled and moved the instance into one of +// the state's children. +func TestResumeEffects_DoesNotRestartACompoundServiceThatSettledIntoAChild(t *testing.T) { + m := state.ForgeFor[*trec]("resumeCompound"). + Service("authorize", func(context.Context, state.ServiceCtx[*trec]) (any, error) { return nil, nil }). + SuperState("ordering").Invoke("authorize", state.WithInvokeOnDone("authorized")). + SubState("pending"). + SubState("paid"). + Initial("pending"). + EndSuperState(). + Initial("ordering"). + Transition("pending").On("authorized").GoTo("paid"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("pending")) + if res := inst.Fire(context.Background(), "authorized"); res.Err != nil { + t.Fatalf("Fire(authorized): %v", res.Err) + } + snap, err := state.MarshalSnapshot(inst.Snapshot()) + if err != nil { + t.Fatalf("MarshalSnapshot: %v", err) + } + restoredSnap, err := state.UnmarshalSnapshot[string, string, *trec](snap) + if err != nil { + t.Fatalf("UnmarshalSnapshot: %v", err) + } + restored, err := m.Restore(restoredSnap) + if err != nil { + t.Fatalf("Restore: %v", err) + } + for _, eff := range restored.ResumeEffects() { + if sv, ok := eff.(state.StartService); ok { + t.Fatalf("ResumeEffects after the service settled into paid starts %s again", sv.ID) + } + } +} diff --git a/state/scheduler_test.go b/state/scheduler_test.go index 2cc8c615..1892e1bd 100644 --- a/state/scheduler_test.go +++ b/state/scheduler_test.go @@ -249,3 +249,34 @@ func assertCancelEffect(t *testing.T, effects []state.Effect, id string) { } t.Fatalf("no CancelScheduled effect for id %q in %v", id, effects) } + +// TestScheduler_Due_ReportsAPendingTimersDeadline pins Due: the deadline Absorb armed a +// timer at, and false once it fired or for an unknown id. +func TestScheduler_Due_ReportsAPendingTimersDeadline(t *testing.T) { + m := state.ForgeFor[*trec]("due"). + State("idle"). + State("a"). + State("b"). + Initial("idle"). + Transition("idle").On("go").GoTo("a"). + Transition("a").After(5 * time.Second).On("toB").GoTo("b"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := state.NewFakeClock(base) + inst := m.Cast(&trec{}, state.WithInitialState("idle"), state.WithClock[string](clk)) + sch := state.NewScheduler(inst) + sch.Absorb(context.Background(), inst.Fire(context.Background(), "go").Effects) + id := state.ScheduleID("due", "a", 0) + due, ok := sch.Due(id) + if !ok || !due.Equal(base.Add(5*time.Second)) { + t.Fatalf("Due(%q) = %v, %v; want %v", id, due, ok, base.Add(5*time.Second)) + } + if _, ok := sch.Due("nope"); ok { + t.Fatal("Due of an unknown id reports a timer") + } + clk.Advance(5 * time.Second) + sch.Tick(context.Background()) + if _, ok := sch.Due(id); ok { + t.Fatal("Due still reports the timer after it fired") + } +} diff --git a/state/start_effects_superstate_test.go b/state/start_effects_superstate_test.go new file mode 100644 index 00000000..a449e887 --- /dev/null +++ b/state/start_effects_superstate_test.go @@ -0,0 +1,47 @@ +package state_test + +import ( + "context" + "testing" + "time" + + "github.com/stablekernel/crucible/state" +) + +// TestResumeEffects_DoesNotRearmASuperstatesTimer proves ResumeEffects re-arms an +// active leaf's `after` timer but not a compound state's: here the compound's timer +// already fired into one of its children, so re-arming it after Restore would fire it +// a second time. +func TestResumeEffects_DoesNotRearmASuperstatesTimer(t *testing.T) { + m := state.ForgeFor[*trec]("nestTimer"). + SuperState("outer"). + SubState("a"). + SubState("b"). + Initial("a"). + EndSuperState(). + State("done"). + Initial("outer"). + Transition("outer").After(time.Second).On("elapsed").GoTo("b"). + Transition("b").After(time.Minute).On("stale").GoTo("done"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("a")) + if res := inst.Fire(context.Background(), "elapsed"); res.Err != nil { + t.Fatalf("Fire(elapsed): %v", res.Err) + } + if got := inst.Current(); got != "b" { + t.Fatalf("state = %q, want b", got) + } + restored, err := m.Restore(inst.Snapshot()) + if err != nil { + t.Fatalf("Restore: %v", err) + } + var timers []any + for _, eff := range restored.ResumeEffects() { + if e, ok := eff.(state.ScheduleAfter); ok { + timers = append(timers, e.Event) + } + } + if len(timers) != 1 || timers[0] != "stale" { + t.Fatalf("ResumeEffects timers = %v, want only b's [stale]", timers) + } +}