diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index 8a0c6af0..fcc87119 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -30,10 +30,16 @@ implement the `Store` interface out of tree. - **Deterministic replay.** A recovered instance is byte-identical to one that never crashed, because recovery replays the recorded driving events and nondeterministic results rather than re-executing their sources. -- **Exactly-once effects.** A domain effect is applied exactly once over the +- **Exactly-once effects.** A domain effect from a step (not an initial entry, which is at-least-once, or a parent transition an actor drives, which is not dispatched) is applied exactly once over the instance's lifetime (the live run plus any number of recoveries), even though - the replay loop is at-least-once. Each effect carries a deterministic - `EffectID` and is deduplicated through the `Store`'s dispatch set. + the replay loop is at-least-once. The exception is a crash or failed mark after the + handler returned, or a handoff between owners, where it can apply twice, so keep + handlers idempotent on `EffectInstance` plus the `EffectID`. Each effect carries a + deterministic `EffectID` and is deduplicated through the `Store`'s dispatch set. + The handler needs a `Store` that implements `DispatchStore`, as `MemStore` and + `FileStore` do: with any other `Store`, `Start`, `Recover` and the stateless + `Runner.Fire` refuse the configuration with `ErrNoDispatchStore`, a permanent + configuration error that doesn't match `ErrEffectDispatch`, so retrying doesn't help. - **Durability across restart.** Every `Fire` step is write-ahead appended to the `Store` before it is acknowledged, so a crash after a successful `Fire` never loses the step. Periodic checkpoints bound the tail that recovery replays. @@ -74,7 +80,7 @@ the first time, and replayed verbatim on recovery: | **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`; 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 | +| **Domain effects** | `WithEffectHandler` | dispatch set, a step's effects applied exactly once via deterministic `EffectID` dedup, with the exceptions under Exactly-once effects | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written: a shorter interval bounds recovery replay, a longer one cuts checkpoint cost. @@ -153,15 +159,20 @@ failed the Handle returns `ErrHandleFailed` saying it was recorded; `Recover` se 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. +owner holds the instance, so stop. `Recover` retries an unapplied effect, and returns +`ErrEffectDispatch` while the handler still fails. ## A note on serialized payloads Events, service done-data, actor done-data, and actor messages are recorded as their JSON form. A parent reducer that type-asserts a non-JSON Go type from `AssignCtx.Event` -observes the JSON-decoded shape on a replayed `onDone`. A `WithEventData` payload is -decoded from its JSON form live as well as on replay, so a reducer gets the same value -both ways. `WithEventDataDecoder` decodes it as the type the caller passed, chosen per +observes the JSON-decoded shape of actor done-data on a replayed `onDone`. A service's +result is JSON-decoded live as well as on replay, so a reducer gets the same value both +ways: a struct is a map and an integer a `float64`, which loses precision above 2^53, and +an error an error with the same message, which `errors.Is` and `errors.As` no longer +match. A +`WithEventData` payload is decoded from its JSON form live as well as on replay, so a +reducer gets the same value both ways. `WithEventDataDecoder` decodes it as the type the caller passed, chosen per event, for example `durable.DecodeAs[Order]`. Without one, a payload decodes as JSON's own form, so `Handle.Fire` refuses a struct or an integer rather than hand the reducer a map or a `float64`. An error stays an error with the same message, with any invalid UTF-8 diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 60405754..ca59d135 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -17,14 +17,18 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. 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. + which is 2 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. `Recover` sends a + tick's and a service settle's effects, and replay hands a tick's timer transitions' + effects to the service runner, only for a Record of format 2 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. +- **`EffectInstance`** reads the instance from the ctx an `EffectHandler` receives, because + effect ids repeat across instances. - **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. @@ -64,6 +68,19 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Changed +- **An effect handler needs a `DispatchStore`.** This is a behavior change. On main, a + Runner with `WithEffectHandler` and a Store that doesn't implement `DispatchStore` + silently skipped every effect: `Fire`'s, and `Recover`'s re-send, never reached the + handler. Now `Start`, `Recover` and the stateless `Runner.Fire` refuse that + configuration with the new `ErrNoDispatchStore`, before they read or write the Store + or call the handler. A stateless `Runner.Fire` on a custom Store without + `DispatchStore` used to succeed with its effects skipped; it now returns + `ErrNoDispatchStore`. It is a permanent configuration error and doesn't match + `ErrEffectDispatch`, so a caller that retries `Recover` on a dispatch failure doesn't + loop on it. A Store with no handler wired is unaffected, and + `MemStore` and `FileStore` implement `DispatchStore`. A Store author whose backend + doesn't track dispatched effects either implements `Dispatched` and + `MarkDispatched` or drops the handler. - **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 @@ -98,7 +115,37 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **A failed effect dispatch fails the Handle**, and so does an effect handler that panics, which now returns `ErrEffectDispatch` instead of panicking out of `Fire`. The effect stays unmarked in the journal, so no later checkpoint compacts it away, and - `Recover` dispatches it again. + `Recover` dispatches it again, failing with `ErrEffectDispatch` while the handler still + does. A handler that panics in `Start` or `Recover` returns `ErrEffectDispatch` too, and + so does a `DispatchStore` whose `Dispatched` or `MarkDispatched` panics or returns an + error, in a step, `Recover` or the stateless `Runner.Fire`, with the Store's error in + the chain. A failed `MarkDispatched` fails the Handle too, and `Recover` applies that + effect again. The handler's error now matches through `errors.Is`. +- **A `KindedEffect` that can't marshal no longer fails a step.** A step records it by + its id and kind with no payload, as it records an effect that isn't a `KindedEffect`, + and its `EffectEnvelope.Meta` holds the marshal error's message under + `crucible.marshalError`; a `MarshalJSON` that panics is recorded the same way, with the + panic's message there. Replay re-derives the effect's value, so it dispatches as any + effect does: once live with a handler wired, once on the `Recover` that retries a + failed dispatch, and once on a `Recover` whose handler was wired only then. This + relaxes `Fire`, and the stateless `Runner.Fire`, which failed with the marshal error + before; `Tick` and `RunService` now record such an effect too. +- **A service result reaches `Assign` decoded, live as well as on replay,** so a retried + effect can't differ from the first attempt: a struct arrives as a map, an integer as a + `float64`, which loses precision above 2^53, and an error as an error with the same + message, any invalid UTF-8 replaced, which `errors.Is` and `errors.As` no longer match. + So onError's `Assign` and the `ServiceRunner`'s `LastError` see a plain error even for + an unbound service's `*state.UnboundRefError`. An `Error` method that panics settles + with a message saying the service error panicked, its invalid UTF-8 replaced too. The journal records this decoded value. A result whose JSON + form won't decode, such as a number beyond `float64`, fails `RunService` with + `ErrHandleFailed` and records nothing, as a result that won't encode does, so + `Recover` doesn't fail on it. Either is refused only after its settle applied: the + onDone `Assign` runs once on an internal stand-in for the result (for one with no + JSON form, the raw result), and the state onDone enters starts its actors and + services, before `RunService` fails; after `Recover` the service runs again, and its + `Assign` with it. So keep a service's result JSON round-trippable, and have an onDone + `Assign` check the payload's type rather than assume it. This may change, to refuse + such a result before any `Assign` runs. - **A step that may not have been recorded fails the Handle.** That call and every later one return `ErrHandleFailed`, wrapping the cause. A step that was recorded while another goroutine failed the Handle also returns `ErrHandleFailed`, saying the step was @@ -142,6 +189,34 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Fixed +- **A timer transition starts and stops services and actors.** `Tick` handed a fired + timer transition's effects only to the scheduler, so a timer that left a state left + its service in flight and its actor running, and one that entered a state started no + service and spawned no actor. A service left in flight could then settle after a + checkpoint that no longer held it, journaling a settle replay couldn't apply, so every + `Recover` failed with "no in-flight service to settle". Now `Tick` hands every fired + transition's effects to the service runner, in fire order, and then to the actor + system, as a `Fire` that produced them all does, live and on replay, so a parent Fire + an actor spawned for one timer drives sees the services every timer of the tick + started, and stops one it leaves rather than leave it in flight: a timer that leaves a + state stops its service and its actor, and one that enters a state starts its service + and spawns its actor. The tick's Record journals the parent Fires an actor it spawned + drove, replayed after its timers, and a parent Fire a context's ending refused fails + the Handle and records nothing, as for `Fire`. Only such a parent Fire fails it once + its timers have fired: a message to an actor that the actor refused because the + tick's `ctx` ended is lost, as actor deliveries are across `Recover`, and the tick + records. Replay does this for a tick of journal + format 2 or later; an older version's tick replays as it ran, with its services left + in flight. This is the Tick-driver fix #236 tracked. The services and actors a timer + starts run under the tick's step context, as a `Fire`'s do, so an actor's behavior or + a parent Fire's middleware that calls back into the same Handle gets + `ErrReentrantStep` at once rather than deadlock on the step lock the `Tick` holds. +- **A checkpoint without `WithServiceRegistry` keeps the settled services.** A Handle + recovered without a service registry restored them from its checkpoint but wrote its + next checkpoint without them, so a later `Recover` with the registry found the service + not settled, and `RunService` ran its `ServiceFn` again. A checkpoint now keeps them + with or without a registry. `Recover` without a registry still refuses a journal tail + that holds a service's settle. - **`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 @@ -168,6 +243,18 @@ 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. +- **Effects reach the handler from `Start`, `Tick` and `RunService`.** They were only + dispatched from `Fire`. `Start` applies the initial entry's effects after encoding the + baseline and before writing it, and only if the entry succeeded. Those effects are + at-least-once: a handler failure, a failed baseline write or overlapping `Start` calls + re-apply them, so key any dedupe on `EffectInstance` plus the effect id. Effects from a + parent transition an actor drives, including during `Fire`, are still not dispatched. + `Recover` re-dispatches what replaying a step produces, as it did for a `Fire`: for a + `Tick` or service step, only in a Record of format 2 or later, so it doesn't send + effects from an older version's `Tick` and service steps, which never dispatched + them. It goes by the Record's format, not its `Effects` envelopes, so a Store that + doesn't keep `Record.Effects` loses no effect a crash left unsent. As for a `Fire`'s, + it loads the Store's dispatched set once for each Record with effects to send. - **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` @@ -192,8 +279,34 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. 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. + recovered Handle. Only a parent Fire a context refused fails it: a Fire that drove none + still records, even when its context ends once the kernel has applied the event. A + message to an actor, or an actor's start, that the actor refused because the context + ended is lost, as actor deliveries are across `Recover`: failing the step would have + the retry run the actors' behaviors, and their side effects, again. +- **A parent's `forwardTo` forwards its event.** A `forwardTo` on a transition a `Fire` + or a `Tick`'s timer drove forwarded nothing, as the actor system was handed the + effects without the event; this was already so on main for `Fire`. Now `Fire` + forwards its event, and `Tick` each timer's event, rebuilt with the Runner's event + codec. As for any actor delivery, the forwarded event isn't replayed: `Recover` + starts the actor fresh. A `forwardTo` on a service settle's transition forwards + nothing. One on a transition an actor's message to the parent drove still hands the + child a nil event: the actor system absorbs that Fire's effects without its event + (#260). `Tick` decodes a + timer's event only for a `forwardTo` an actor system can carry. When the codec can't + decode it, `Tick` forwards nothing and returns the codec's error with the timers' + results. The tick is still recorded and its effects dispatched, and the Handle carries + on, as when an actor can't take a message: failing it would only have `Recover` fire + the timers again and meet the same error. +- **A step spawns no actor for a state it has already left.** When an actor a step + spawned sent the parent a message that left another state the step had entered, such + as a parallel region's, that state's actor still spawned after, and ran for a state + that wasn't active, where `Recover` never spawned it. Now the step skips that spawn, + for one `Fire` and for timers that fire in one `Tick`. `Start` and `Recover` skip it + too, for an actor that starts when they do and sends such a message. When `Recover` + respawns the actors that were running and one fails with an onError that leaves + another of their states, it stops that state's actor. A `Tick` also skips the spawn + of a state that a later timer of the same tick leaves. - **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 diff --git a/durable/README.md b/durable/README.md index 643d40cc..0099ade1 100644 --- a/durable/README.md +++ b/durable/README.md @@ -31,10 +31,16 @@ backends implement the `Store` interface out of tree. - **Deterministic replay**: a recovered instance is byte-identical to one that never crashed, because recovery replays the recorded driving events and nondeterministic results rather than re-executing their sources. -- **Exactly-once effects**: a domain effect is applied exactly once over the +- **Exactly-once effects**: a domain effect from a step (not an initial entry, which is at-least-once, or a parent transition an actor drives, which is not dispatched) is applied exactly once over the instance's lifetime (the live run plus any number of recoveries), even though - the replay loop is at-least-once. Each effect carries a deterministic - `EffectID` and is deduplicated through the `Store`'s dispatch set. + the replay loop is at-least-once. The exception is a crash or failed mark after the + handler returned, or a handoff between owners, where it can apply twice, so keep + handlers idempotent on `EffectInstance` plus the `EffectID`. Each effect carries a + deterministic `EffectID` and is deduplicated through the `Store`'s dispatch set. + The handler needs a `Store` that implements `DispatchStore`, as `MemStore` and + `FileStore` do: with any other `Store`, `Start`, `Recover` and the stateless + `Runner.Fire` refuse the configuration with `ErrNoDispatchStore`, a permanent + configuration error that doesn't match `ErrEffectDispatch`, so retrying doesn't help. - **Durability across restart**: every `Fire` step is write-ahead appended to the `Store` before it is acknowledged, so a crash after a successful `Fire` never loses the step. Periodic checkpoints bound the tail recovery replays. @@ -84,7 +90,7 @@ the first time, and replayed verbatim on recovery: | **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`; 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 | +| **Domain effects** | `WithEffectHandler` | dispatch set, a step's effects applied exactly once via deterministic `EffectID` dedup, with the exceptions under Exactly-once effects | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written (a shorter interval bounds recovery replay; a longer one cuts checkpoint cost). @@ -152,9 +158,12 @@ 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 a -`Tick`, `RunService` or `DeliverToActor` whose context ended during the step, and any of +`RunService` or `DeliverToActor` whose context ended during the step, a `Tick` whose +context ended while its timers fired, 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 +or one middleware derived from it. A message to an actor that the actor refused because +the step's context ended doesn't fail a `Fire` or `Tick`: the message is lost, as actor +deliveries are across `Recover`. 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 @@ -164,15 +173,20 @@ failed the Handle returns `ErrHandleFailed` saying it was recorded; `Recover` se 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. +owner holds the instance, so stop. `Recover` retries an unapplied effect, and returns +`ErrEffectDispatch` while the handler still fails. ## Caveat: serialized payloads Events, service done-data, actor done-data, and actor messages are recorded as their JSON form. A parent reducer that type-asserts a non-JSON Go type from `AssignCtx.Event` -observes the JSON-decoded shape on a replayed `onDone`. A `WithEventData` payload is -decoded from its JSON form live as well as on replay, so a reducer gets the same value -both ways. `WithEventDataDecoder` decodes it as the type the caller passed, chosen per +observes the JSON-decoded shape of actor done-data on a replayed `onDone`. A service's +result is JSON-decoded live as well as on replay, so a reducer gets the same value both +ways: a struct is a map and an integer a `float64`, which loses precision above 2^53, and +an error an error with the same message, which `errors.Is` and `errors.As` no longer +match. A +`WithEventData` payload is decoded from its JSON form live as well as on replay, so a +reducer gets the same value both ways. `WithEventDataDecoder` decodes it as the type the caller passed, chosen per event, for example `durable.DecodeAs[Order]`. Without one, a payload decodes as JSON's own form, so `Handle.Fire` refuses a struct or an integer rather than hand the reducer a map or a `float64`. An error stays an error with the same message, with any invalid UTF-8 diff --git a/durable/actor.go b/durable/actor.go index 03ffcc87..b95cf43c 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -158,13 +158,14 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef return true, h.fail(fmt.Errorf("durable: recording actor %q result for %q: %w", ref.ID, h.id, err)) } - step := h.nextStep - // 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 { + // A parent Fire the delivery drove can arm a timer, which reads the clock. Its effects + // aren't dispatched, so the step names none, and finishStep only offers its + // checkpoint. + rec := &Record{Step: h.nextStep, Entries: append(h.drainClock(), entries...)} + if _, err := h.recordStep(ctx, rec, nil); err != nil { return true, err } - return true, nil + return true, h.finishStep(ctx, rec, nil) } // DeliverToActorByID is DeliverToActor keyed by raw actor id, for a host that diff --git a/durable/actor_absorb_test.go b/durable/actor_absorb_test.go new file mode 100644 index 00000000..c8ead735 --- /dev/null +++ b/durable/actor_absorb_test.go @@ -0,0 +1,211 @@ +package durable_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// recordingActor is an actor that notes every event delivered to it. +type recordingActor struct{ got []any } + +func (r *recordingActor) DeliverFire(_ context.Context, ev any) (bool, any) { + r.got = append(r.got, ev) + return false, nil +} +func (*recordingActor) ChildEffects() []state.Effect { return nil } +func (*recordingActor) Output() any { return nil } + +// TestStep_AParentForwardToForwardsTheStepsEvent pins that a parent transition's +// forwardTo forwards the event that drove it, for a host Fire and for a timer a Tick +// fires, whose event is the timer's delayed event. Pair runs child; poke, and the timer +// due, each stay in pair and forward their event to child. Actor deliveries aren't +// replayed: a recovered Handle starts child fresh, from its initial state, so it holds +// nothing the live run forwarded, as for a SendTo. +func TestStep_AParentForwardToForwardsTheStepsEvent(t *testing.T) { + for _, step := range []string{"Fire", "Tick"} { + t.Run(step, func(t *testing.T) { + ctx := context.Background() + machine := "forward" + step + childID := state.ActorID(machine, "pair", 0) + b := state.ForgeFor[stepCtx](machine). + Actor("child"). + State("idle"). + State("pair").InvokeActor("child"). + Initial("idle"). + Transition("idle").On("go").GoTo("pair") + want := "poke" + if step == "Fire" { + b = b.Transition("pair").On("poke").GoTo("pair").ForwardTo(childID) + } else { + want = "due" + b = b.Transition("pair").After(5 * time.Second).On("due").GoTo("pair").ForwardTo(childID) + } + m := b.Quench() + clk := state.NewFakeClock(epoch) + var children []*recordingActor + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": func(map[string]any) (state.ActorInstance, error) { + children = append(children, &recordingActor{}) + return children[len(children)-1], nil + }, + }), + } + store, id := durable.NewMemStore(), durable.InstanceID("forward") + 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 step == "Fire" { + _, err = h.Fire(ctx, "poke") + } else { + clk.Advance(6 * time.Second) + _, err = h.Tick(ctx) + } + if err != nil { + t.Fatalf("%s: %v", step, err) + } + if len(children) != 1 || fmt.Sprint(children[0].got) != fmt.Sprint([]any{want}) { + t.Fatalf("live child got %v, want [%s]: forwardTo forwards the event that drove the transition", children[0].got, want) + } + if _, err = durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + if len(children) != 2 || len(children[1].got) != 0 { + t.Fatalf("recovered: %d children, the new one got %v; want child respawned fresh, with nothing replayed to it", len(children), children[len(children)-1].got) + } + }) + } +} + +// leaver is an actor that sends its parent leaveB as it starts, then backB when back. +type leaver struct{ sent, back bool } + +func (*leaver) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (l *leaver) ChildEffects() []state.Effect { + if l.sent { + return nil + } + l.sent = true + if l.back { + return []state.Effect{state.SendParent{Event: "leaveB"}, state.SendParent{Event: "backB"}} + } + return []state.Effect{state.SendParent{Event: "leaveB"}} +} +func (*leaver) Output() any { return nil } + +// TestStep_AnActorWhoseStateAnEarlierActorLeft_DoesNotSpawn pins that a step spawns no +// actor for a state a parent Fire its absorb drove has already left. Two regions enter +// A, which runs a1, and B, which runs a2, by one Fire, or by two timers due in one +// Tick, A's first. a1 sends the parent leaveB as it starts, which exits B before a2's +// spawn is absorbed. Recover spawns the actors of the configuration it ends in, so it +// never runs a2, from the journal or from a checkpoint; the live Handle mustn't either. +// When a1 then sends backB, which enters B again, that Fire spawns a2 for B's new +// activation, once, and a2 runs live and recovered. +func TestStep_AnActorWhoseStateAnEarlierActorLeft_DoesNotSpawn(t *testing.T) { + for _, step := range []string{"Fire", "Tick"} { + for _, every := range []int{0, 1} { + for _, back := range []bool{false, true} { + t.Run(fmt.Sprintf("%s checkpoint every %d back %v", step, every, back), func(t *testing.T) { + ctx := context.Background() + machine := "orphan" + step + a1, a2 := state.ActorID(machine, "A", 0), state.ActorID(machine, "B", 0) + b := state.ForgeFor[stepCtx](machine). + Actor("a1"). + Actor("a2"). + State("idle"). + SuperState("both"). + Region("left") + if step == "Fire" { + b = b.Initial("A") + } else { + b = b.Initial("wA").SubState("wA") + } + b = b.SubState("A").InvokeActor("a1"). + EndRegion(). + Region("right") + if step == "Fire" { + b = b.Initial("B") + } else { + b = b.Initial("wB").SubState("wB") + } + b = b.SubState("B").InvokeActor("a2"). + SubState("C"). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("both"). + Transition("B").On("leaveB").GoTo("C"). + Transition("C").On("backB").GoTo("B") + if step == "Tick" { + b = b.Transition("wA").After(4 * time.Second).On("toA").GoTo("A"). + Transition("wB").After(5 * time.Second).On("toB").GoTo("B") + } + m := b.Quench() + clk := state.NewFakeClock(epoch) + spawned := map[string]int{} + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "a1": func(map[string]any) (state.ActorInstance, error) { spawned["a1"]++; return &leaver{back: back}, nil }, + "a2": func(map[string]any) (state.ActorInstance, error) { spawned["a2"]++; return ¬eTarget{}, nil }, + }), + } + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("orphan") + 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 step == "Tick" { + clk.Advance(6 * time.Second) + fired, tickErr := h.Tick(ctx) + if tickErr != nil || len(fired) != 2 { + t.Fatalf("Tick fired %d timers, err %v; want both", len(fired), tickErr) + } + } + if spawned["a2"] != map[bool]int{false: 0, true: 1}[back] { + t.Fatalf("live spawned a2 %d times, want it spawned only for an active B", spawned["a2"]) + } + if every > 0 && tailLen(t, store, id) != 0 { + t.Fatalf("setup: %d records past the checkpoint, want none", tailLen(t, store, id)) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + for _, hh := range []struct { + name string + h *durable.Handle[string, string, stepCtx] + }{{"live", h}, {"recovered", recovered}} { + name, h := hh.name, hh.h + want := map[bool]string{false: "[A C]", true: "[A B]"}[back] + if cfg := fmt.Sprint(h.Instance().Configuration()); cfg != want { + t.Fatalf("%s configuration %s, want %s", name, cfg, want) + } + if _, ok := h.ActorRef(a1); !ok { + t.Fatalf("%s: a1 isn't running, want it running in A", name) + } + if _, ok := h.ActorRef(a2); ok != back { + t.Fatalf("%s: a2 running %v, want %v, as B is active (a2 spawned %d times)", name, ok, back, spawned["a2"]) + } + } + }) + } + } + } +} diff --git a/durable/actor_fire_effects_test.go b/durable/actor_fire_effects_test.go index d9e4612b..db20cfd0 100644 --- a/durable/actor_fire_effects_test.go +++ b/durable/actor_fire_effects_test.go @@ -12,7 +12,7 @@ import ( // 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") + t.Skip("a parent Fire an actor drove has its timers and services armed, but its domain effects aren't dispatched; see #257") ctx := context.Background() type cx struct{} m := state.ForgeFor[cx]("actorEffects"). diff --git a/durable/actor_spawn_left_test.go b/durable/actor_spawn_left_test.go new file mode 100644 index 00000000..fd8d00ca --- /dev/null +++ b/durable/actor_spawn_left_test.go @@ -0,0 +1,299 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// leftAtStartMachine is a machine that starts in both, two regions running a1 in A and +// a2 in B, and a third holding D, whose poke changes nothing. B's leaveB goes to C, and +// C's backB back to B. +func leftAtStartMachine(name string) stepMachine { + return state.ForgeFor[stepCtx](name). + Actor("a1"). + Actor("a2"). + SuperState("both"). + Region("left").Initial("A"). + SubState("A").InvokeActor("a1"). + EndRegion(). + Region("right").Initial("B"). + SubState("B").InvokeActor("a2"). + SubState("C"). + EndRegion(). + Region("third").Initial("D"). + SubState("D"). + EndRegion(). + EndSuperState(). + Initial("both"). + Transition("B").On("leaveB").GoTo("C"). + Transition("C").On("backB").GoTo("B"). + Transition("D").On("poke").GoTo("D"). + Quench() +} + +// TestStartAndRecover_AnActorWhoseStateAnEarlierActorLeft_DoesNotSpawn pins that Start +// and Recover, which spawn the configuration's actors, spawn none for a state a parent +// Fire an earlier spawn drove has already left. a1, spawned first, sends the parent +// leaveB as it starts, which exits B before a2's spawn. A Recover from the journal or a +// checkpoint replays that Fire and ends in C, so it never runs a2; Start mustn't, and +// nor must a Recover from the baseline, where a1 starts afresh and sends leaveB again. +// When a1 then sends backB, that Fire spawns a2 for B's new activation, once. +func TestStartAndRecover_AnActorWhoseStateAnEarlierActorLeft_DoesNotSpawn(t *testing.T) { + for _, every := range []int{0, 1} { + for _, back := range []bool{false, true} { + t.Run(fmt.Sprintf("checkpoint every %d back %v", every, back), func(t *testing.T) { + ctx := context.Background() + machine := "startLeft" + m := leftAtStartMachine(machine) + a1, a2 := state.ActorID(machine, "A", 0), state.ActorID(machine, "B", 0) + spawned := map[string]int{} + opts := []stepOption{ + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "a1": func(map[string]any) (state.ActorInstance, error) { spawned["a1"]++; return &leaver{back: back}, nil }, + "a2": func(map[string]any) (state.ActorInstance, error) { spawned["a2"]++; return ¬eTarget{}, nil }, + }), + } + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + wantA2 := map[bool]int{false: 0, true: 1}[back] + wantCfg := map[bool]string{false: "[A C D]", true: "[A B D]"}[back] + check := func(name string, h *durable.Handle[string, string, stepCtx]) { + t.Helper() + if cfg := fmt.Sprint(h.Instance().Configuration()); cfg != wantCfg { + t.Fatalf("%s configuration %s, want %s", name, cfg, wantCfg) + } + if _, ok := h.ActorRef(a1); !ok { + t.Fatalf("%s: a1 isn't running, want it running in A", name) + } + if _, ok := h.ActorRef(a2); ok != back { + t.Fatalf("%s: a2 running %v, want %v, as B is active (a2 spawned %d times)", name, ok, back, spawned["a2"]) + } + } + store, id := durable.NewMemStore(), durable.InstanceID("start-left") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("both")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if spawned["a2"] != wantA2 { + t.Fatalf("Start spawned a2 %d times, want %d: only for an active B", spawned["a2"], wantA2) + } + check("started", h) + + // From the baseline: the start's parent Fires aren't journaled yet, so a1 + // starts afresh and sends leaveB again. + spawned["a2"] = 0 + fromBase, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover from the baseline: %v", err) + } + if spawned["a2"] != wantA2 { + t.Fatalf("Recover from the baseline spawned a2 %d times, want %d", spawned["a2"], wantA2) + } + check("recovered from the baseline", fromBase) + + // A step journals the start's parent Fires; a Recover replays them. + if _, err = fromBase.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if every > 0 && tailLen(t, store, id) != 0 { + t.Fatalf("setup: %d records past the checkpoint, want none", tailLen(t, store, id)) + } + check("live", fromBase) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + check("recovered", recovered) + }) + } + } +} + +// failingOnRespawn is an actor behavior that starts once, then fails every later +// spawn, as when a respawn at Recover finds a dependency gone. +func failingOnRespawn(n *int) state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + *n++ + if *n > 1 { + return nil, errors.New("gone") + } + return ¬eTarget{}, nil + } +} + +// TestRecover_ARunningActorWhoseStateARespawnsOnErrorLeft_DoesNotRun pins that a Recover +// whose respawn of a running actor fails, routing an onError that leaves another +// region's state, leaves that state's running actor stopped. a1 and a2 were running; +// a1's respawn, first, fails, and its onError leaveB exits B before a2 respawns. The +// next step journals that onError, and a Recover replays it and ends in C, so it never +// runs a2; the Handle that drove it mustn't keep a2 running either. When C goes back to +// B at once, the onError's Fire spawns a2 for B's new activation, and a2 keeps running. +func TestRecover_ARunningActorWhoseStateARespawnsOnErrorLeft_DoesNotRun(t *testing.T) { + for _, every := range []int{0, 1} { + for _, back := range []bool{false, true} { + t.Run(fmt.Sprintf("checkpoint every %d back %v", every, back), func(t *testing.T) { + ctx := context.Background() + machine := "respawnLeft" + b := state.ForgeFor[stepCtx](machine). + Actor("a1"). + Actor("a2"). + SuperState("both"). + Region("left").Initial("A"). + SubState("A").InvokeActor("a1", state.WithInvokeOnError("leaveB")). + EndRegion(). + Region("right").Initial("B"). + SubState("B").InvokeActor("a2"). + SubState("C") + if back { + b = b.Always().GoTo("B") + } + m := b.EndRegion(). + Region("third").Initial("D"). + SubState("D"). + EndRegion(). + EndSuperState(). + Initial("both"). + Transition("B").On("leaveB").GoTo("C"). + Transition("D").On("poke").GoTo("D"). + Quench() + a2 := state.ActorID(machine, "B", 0) + wantCfg := map[bool]string{false: "[A C D]", true: "[A B D]"}[back] + var a1Spawns, a2Spawns int + opts := []stepOption{ + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "a1": failingOnRespawn(&a1Spawns), + "a2": func(map[string]any) (state.ActorInstance, error) { a2Spawns++; return ¬eTarget{}, nil }, + }), + } + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("respawn-left") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("both")) + if err != nil { + t.Fatalf("Start: %v", err) + } + // A step records both actors running. + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if _, ok := h.ActorRef(a2); !ok || a1Spawns != 1 { + t.Fatalf("setup: a2 running %v, a1 spawned %d times; want a2 running, a1 spawned once", ok, a1Spawns) + } + live, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if a1Spawns != 2 { + t.Fatalf("setup: a1 spawned %d times, want its respawn tried", a1Spawns) + } + if _, err = live.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + if every > 0 && tailLen(t, store, id) != 0 { + t.Fatalf("setup: %d records past the checkpoint, want none", tailLen(t, store, id)) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover again: %v", err) + } + for _, hh := range []struct { + name string + h *durable.Handle[string, string, stepCtx] + }{{"live", live}, {"recovered", recovered}} { + if cfg := fmt.Sprint(hh.h.Instance().Configuration()); cfg != wantCfg { + t.Fatalf("%s configuration %s, want %s", hh.name, cfg, wantCfg) + } + if _, ok := hh.h.ActorRef(a2); ok != back { + t.Fatalf("%s: a2 running %v, want %v: it runs only while B is active", hh.name, ok, back) + } + } + }) + } + } +} + +// TestTick_AnActorWhoseStateALaterTimerLeaves_DoesNotSpawn pins that a Tick spawns no +// actor for a state a later timer of the same tick leaves. P arms leave on entry; +// inside it, w's toS enters S, which runs x. Both are due at one Tick, toS first, so the +// kernel has left S by the time the tick hands toS's effects to the actor system. +// Recover replays the timers and ends in out, so it never runs x; the live tick +// mustn't either, even for a moment before leave's effects stop it. +func TestTick_AnActorWhoseStateALaterTimerLeaves_DoesNotSpawn(t *testing.T) { + for _, every := range []int{0, 1} { + t.Run(fmt.Sprintf("checkpoint every %d", every), func(t *testing.T) { + ctx := context.Background() + machine := "tickLeft" + x := state.ActorID(machine, "S", 0) + m := state.ForgeFor[stepCtx](machine). + Actor("x"). + State("idle"). + SuperState("P"). + SubState("w"). + SubState("S").InvokeActor("x"). + Initial("w"). + EndSuperState(). + State("out"). + Initial("idle"). + Transition("idle").On("go").GoTo("P"). + Transition("w").After(4 * time.Second).On("toS").GoTo("S"). + Transition("P").After(5 * time.Second).On("leave").GoTo("out"). + Quench() + clk := state.NewFakeClock(epoch) + var spawns int + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "x": func(map[string]any) (state.ActorInstance, error) { spawns++; return ¬eTarget{}, nil }, + }), + } + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("tick-left") + 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) + 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 spawns != 0 { + t.Fatalf("live tick spawned x %d times, want none: S isn't active after the tick", spawns) + } + if every > 0 && tailLen(t, store, id) != 0 { + t.Fatalf("setup: %d records past the checkpoint, want none", tailLen(t, store, id)) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + for _, hh := range []struct { + name string + h *durable.Handle[string, string, stepCtx] + }{{"live", h}, {"recovered", recovered}} { + if cfg := fmt.Sprint(hh.h.Instance().Configuration()); cfg != "[out]" { + t.Fatalf("%s configuration %s, want [out]", hh.name, cfg) + } + if _, ok := hh.h.ActorRef(x); ok { + t.Fatalf("%s: x is running, want it stopped with S", hh.name) + } + } + if spawns != 0 { + t.Fatalf("x spawned %d times, want none", spawns) + } + }) + } +} diff --git a/durable/checkpoint_no_registry_test.go b/durable/checkpoint_no_registry_test.go new file mode 100644 index 00000000..3af0d8f1 --- /dev/null +++ b/durable/checkpoint_no_registry_test.go @@ -0,0 +1,121 @@ +package durable_test + +import ( + "context" + "strings" + "sync/atomic" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// noRegistryMachine invokes fn in "loading", which "begin" enters from "idle". Its +// onDone "done" stays in loading, through an Assign that counts it in done, so a +// settled service's state stays active; "poke" stays in loading too, leaving the +// service's activation alone. +func noRegistryMachine(fn state.ServiceFn[svcCtx], done *int) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("noReg"). + Service("fetch", fn). + Reducer("noteDone", func(in state.AssignCtx[svcCtx]) svcCtx { + *done++ + return in.Entity + }). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done")). + Initial("idle"). + Transition("idle").On("begin").GoTo("loading"). + Transition("loading").On("done").GoTo("loading").Assign("noteDone"). + Transition("loading").On("poke").GoTo("loading"). + Quench() +} + +var noRegistrySvc = state.InvokeID("noReg", "loading", 0) + +// countingRuns returns a ServiceFn that counts its runs. +func countingRuns(runs *int64) state.ServiceFn[svcCtx] { + return func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + return atomic.AddInt64(runs, 1), nil + } +} + +// TestCheckpoint_WithoutARegistry_KeepsTheSettledServices pins that a checkpoint a +// Handle recovered without WithServiceRegistry writes keeps the settled services the one +// before it held: a Handle with the registry settles loading's service while loading +// stays active, and checkpoints; one recovered without the registry Fires a step that +// leaves the service alone, and checkpoints again; then one recovered with the registry +// finds the service settled, and the ServiceFn doesn't run again. +func TestCheckpoint_WithoutARegistry_KeepsTheSettledServices(t *testing.T) { + ctx := context.Background() + var runs int64 + done := 0 + fn := countingRuns(&runs) + m := noRegistryMachine(fn, &done) + bare := []durable.Option[string, string, svcCtx]{durable.WithCheckpointEvery[string, string, svcCtx](1)} + withRegistry := append(append([]durable.Option[string, string, svcCtx]{}, bare...), durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))) + store, id := durable.NewMemStore(), durable.InstanceID("no-reg") + + h, err := durable.NewRunner(m, store, withRegistry...).Start(ctx, id, svcCtx{}, 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) + } + if _, ran, rerr := h.RunService(ctx, noRegistrySvc); !ran || rerr != nil { + t.Fatalf("RunService = %v, %v; want it settled", ran, rerr) + } + + nh, err := durable.Recover(ctx, m, store, id, bare...) + if err != nil { + t.Fatalf("Recover without the registry: %v", err) + } + if _, err = nh.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) without the registry: %v", err) + } + + rh, err := durable.Recover(ctx, m, store, id, withRegistry...) + if err != nil { + t.Fatalf("Recover with the registry: %v", err) + } + _, ran, err := rh.RunService(ctx, noRegistrySvc) + if err != nil { + t.Fatalf("RunService after the registry-less checkpoint: %v", err) + } + if got := atomic.LoadInt64(&runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want once: the registry-less checkpoint dropped the settled service", got) + } + if ran { + t.Fatal("RunService ran = true, want nothing in flight for a settled service") + } + if done != 1 { + t.Fatalf("onDone ran %d times, want once", done) + } +} + +// TestRecover_WithoutARegistry_RefusesAJournaledServiceRecord pins that Recover without +// WithServiceRegistry refuses a tail holding a service's settle, rather than replay it +// with no service runner: only a checkpoint that compacted that Record recovers without +// the registry. +func TestRecover_WithoutARegistry_RefusesAJournaledServiceRecord(t *testing.T) { + ctx := context.Background() + var runs int64 + done := 0 + fn := countingRuns(&runs) + m := noRegistryMachine(fn, &done) + store, id := durable.NewMemStore(), durable.InstanceID("no-reg-tail") + 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, "begin"); err != nil { + t.Fatalf("Fire(begin): %v", err) + } + if _, ran, rerr := h.RunService(ctx, noRegistrySvc); !ran || rerr != nil { + t.Fatalf("RunService = %v, %v; want it settled", ran, rerr) + } + if _, err = durable.Recover(ctx, m, store, id); err == nil || !strings.Contains(err.Error(), "requires a service registry") { + t.Fatalf("Recover without the registry = %v, want it refused for want of a registry", err) + } +} diff --git a/durable/dispatch_ctx_after_record_test.go b/durable/dispatch_ctx_after_record_test.go new file mode 100644 index 00000000..150b24c8 --- /dev/null +++ b/durable/dispatch_ctx_after_record_test.go @@ -0,0 +1,168 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// cancelAfterAppendStore is a MemStore that ends a step's context just after its +// Record is appended, as a host's deadline passing between the record and the +// dispatch would. It ends it once, when cancel is set. +type cancelAfterAppendStore struct { + *durable.MemStore + cancel *context.CancelFunc +} + +func (s cancelAfterAppendStore) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { + n, err := s.MemStore.Append(ctx, id, rec, opts...) + if *s.cancel != nil { + (*s.cancel)() + *s.cancel = nil + } + return n, err +} + +// ctxNotingHandler is an effect handler that notes whether each effect's context had +// ended, and, when honor is set, refuses the effect with the context's error. +type ctxNotingHandler struct { + honor bool + ended []bool +} + +func (c *ctxNotingHandler) handle(ctx context.Context, _ string, _ state.Effect) error { + c.ended = append(c.ended, ctx.Err() != nil) + if c.honor { + return ctx.Err() + } + return nil +} + +// effectFn is an EffectHandler's signature. +type effectFn = func(context.Context, string, state.Effect) error + +// TestStep_AContextThatEndsAfterTheRecord_DispatchesAsFireDoes pins what an effect +// handler sees when the step's context ends after the step is recorded and before +// its effects are dispatched, and that Tick and RunService match Fire. The dispatch +// runs under the caller's context, not a detached one, on every path. A handler that +// ignores the context applies the effect and the step succeeds; one that honors it +// fails the step with ErrEffectDispatch and the Handle with it, and Recover then +// sends the effect once, since the step was recorded. +func TestStep_AContextThatEndsAfterTheRecord_DispatchesAsFireDoes(t *testing.T) { + ctx := context.Background() + type path struct { + name string + // run starts an instance on st, wired to handle, drives it to the step under + // test, and runs that step on a context st ends after its append. It returns + // the step's error, and a func that recovers the instance with another handler. + run func(t *testing.T, st cancelAfterAppendStore, handle effectFn) (recoverWith func(effectFn) error, step error) + } + paths := []path{ + {"fire", func(t *testing.T, st cancelAfterAppendStore, handle effectFn) (func(effectFn) error, error) { + h, err := durable.NewRunner(effectMachine(), st, durable.WithEffectHandler[string, string, *runCtx](handle)). + Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + turn, cancel := context.WithCancel(ctx) + *st.cancel = cancel + _, stepErr := h.Fire(turn, "go") + return func(hh effectFn) error { + _, err := durable.Recover(ctx, effectMachine(), st, "i1", durable.WithEffectHandler[string, string, *runCtx](hh)) + return err + }, stepErr + }}, + {"tick", func(t *testing.T, st cancelAfterAppendStore, handle effectFn) (func(effectFn) error, error) { + clk := state.NewFakeClock(epoch) + opts := func(hh effectFn) []durable.Option[string, string, *runCtx] { + return []durable.Option[string, string, *runCtx]{ + durable.WithEffectHandler[string, string, *runCtx](hh), + durable.WithRunnerClock[string, string, *runCtx](clk), + } + } + h, err := durable.NewRunner(timerNotifyMachine(), st, opts(func(context.Context, string, state.Effect) error { return nil })...). + Start(ctx, "i1", &runCtx{}, 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) + } + // The Fire's effect went to a no-op handler and is marked; only the Tick's + // effect reaches handle, through a Handle recovered with it. + h, err = durable.Recover(ctx, timerNotifyMachine(), st, "i1", opts(handle)...) + if err != nil { + t.Fatalf("Recover before the tick: %v", err) + } + clk.Advance(2 * time.Second) + turn, cancel := context.WithCancel(ctx) + *st.cancel = cancel + _, stepErr := h.Tick(turn) + return func(hh effectFn) error { + _, err := durable.Recover(ctx, timerNotifyMachine(), st, "i1", opts(hh)...) + return err + }, stepErr + }}, + {"service", func(t *testing.T, st cancelAfterAppendStore, handle effectFn) (func(effectFn) error, error) { + var calls int64 + fn := counterService(&calls) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + h, err := durable.NewRunner(fetchThenWaitMachine(fn), st, reg, durable.WithEffectHandler[string, string, svcCtx](handle)). + Start(ctx, "i1", 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) + } + turn, cancel := context.WithCancel(ctx) + *st.cancel = cancel + _, _, stepErr := h.RunService(turn, state.InvokeID("fetchThenWait", "loading", 0)) + return func(hh effectFn) error { + _, err := durable.Recover(ctx, fetchThenWaitMachine(fn), st, "i1", reg, durable.WithEffectHandler[string, string, svcCtx](hh)) + return err + }, stepErr + }}, + } + for _, p := range paths { + t.Run(p.name+"/handler ignores ctx", func(t *testing.T) { + var cancel context.CancelFunc + st := cancelAfterAppendStore{durable.NewMemStore(), &cancel} + live := &ctxNotingHandler{} + recoverWith, stepErr := p.run(t, st, live.handle) + if stepErr != nil { + t.Fatalf("step = %v, want nil: the step was recorded, and the handler applied its effect", stepErr) + } + if len(live.ended) != 1 || !live.ended[0] { + t.Fatalf("handler saw ended contexts %v, want [true]: the dispatch runs under the caller's context", live.ended) + } + healthy := newEffectRecorder() + if err := recoverWith(healthy.handler()); err != nil { + t.Fatalf("Recover: %v", err) + } + if len(healthy.order) != 0 { + t.Fatalf("Recover sent %v, want nothing: live applied and marked the effect", healthy.order) + } + }) + t.Run(p.name+"/handler honors ctx", func(t *testing.T) { + var cancel context.CancelFunc + st := cancelAfterAppendStore{durable.NewMemStore(), &cancel} + live := &ctxNotingHandler{honor: true} + recoverWith, stepErr := p.run(t, st, live.handle) + if !errors.Is(stepErr, durable.ErrEffectDispatch) || !errors.Is(stepErr, durable.ErrHandleFailed) || !errors.Is(stepErr, context.Canceled) { + t.Fatalf("step = %v, want ErrEffectDispatch and ErrHandleFailed wrapping context.Canceled", stepErr) + } + healthy := newEffectRecorder() + if err := recoverWith(healthy.handler()); err != nil { + t.Fatalf("Recover: %v", err) + } + if len(healthy.order) != 1 { + t.Fatalf("Recover sent %v, want the recorded step's one effect", healthy.order) + } + }) + } +} diff --git a/durable/dispatch_store_internal_test.go b/durable/dispatch_store_internal_test.go new file mode 100644 index 00000000..6b8c1564 --- /dev/null +++ b/durable/dispatch_store_internal_test.go @@ -0,0 +1,43 @@ +package durable + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/state" +) + +type plainStoreCtx struct{} + +// plainStore hides MemStore's DispatchStore methods, so it tracks no dispatched effects. +type plainStore struct{ Store } + +// TestDispatch_WithoutADispatchStore_RefusesPermanently pins that dispatch itself +// refuses a handler wired with a Store that can't track dispatched effects, with the +// permanent ErrNoDispatchStore, should a path ever reach it without Start's or +// recover's refusal. It must not surface as a retryable ErrEffectDispatch. +func TestDispatch_WithoutADispatchStore_RefusesPermanently(t *testing.T) { + m := state.ForgeFor[plainStoreCtx]("plain"). + State("a"). + Initial("a"). + Quench() + applied := 0 + r := NewRunner(m, plainStore{NewMemStore()}, + WithEffectHandler[string, string, plainStoreCtx](func(context.Context, string, state.Effect) error { + applied++ + return nil + })) + des := []dispatchableEffect{{id: "0#0#demo.notify", effect: state.UnknownEffect{EffectKind: "demo.notify"}}} + + err := r.dispatch(context.Background(), "i1", des) + if !errors.Is(err, ErrNoDispatchStore) { + t.Fatalf("dispatch = %v, want ErrNoDispatchStore", err) + } + if errors.Is(err, ErrEffectDispatch) { + t.Fatalf("dispatch = %v, which matches the retryable ErrEffectDispatch", err) + } + if applied != 0 { + t.Fatalf("the handler ran %d times, want none", applied) + } +} diff --git a/durable/dispatch_store_required_test.go b/durable/dispatch_store_required_test.go new file mode 100644 index 00000000..92909024 --- /dev/null +++ b/durable/dispatch_store_required_test.go @@ -0,0 +1,173 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// noDispatchStore wraps a Store and hides its DispatchStore methods, so the Runner +// can't track which effects it applied. It counts the writes that reach the Store. +type noDispatchStore struct { + durable.Store + writes int +} + +func (s *noDispatchStore) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { + s.writes++ + return s.Store.Append(ctx, id, rec, opts...) +} + +func (s *noDispatchStore) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { + s.writes++ + return s.Store.Checkpoint(ctx, id, snapshot, throughStep, opts...) +} + +// mustRefuseNoDispatchStore fails unless err matches ErrNoDispatchStore and not +// ErrEffectDispatch or ErrHandleFailed. +func mustRefuseNoDispatchStore(t *testing.T, what string, err error) { + t.Helper() + if !errors.Is(err, durable.ErrNoDispatchStore) { + t.Fatalf("%s = %v, want ErrNoDispatchStore", what, err) + } + if errors.Is(err, durable.ErrEffectDispatch) || errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("%s = %v matches ErrEffectDispatch or ErrHandleFailed, want only ErrNoDispatchStore: retrying doesn't help", what, err) + } +} + +// TestEffectHandler_RefusesAStoreWithoutDispatch proves an effect handler wired with +// a Store that isn't a DispatchStore is refused with ErrNoDispatchStore, before any +// Store write or handler call, by Start, Recover and the stateless Fire. On main the +// handler was silently skipped. The refusal doesn't match ErrEffectDispatch: retrying +// doesn't help, so a caller that retries Recover on ErrEffectDispatch mustn't loop on +// it. +func TestEffectHandler_RefusesAStoreWithoutDispatch(t *testing.T) { + ctx := context.Background() + + t.Run("Start", func(t *testing.T) { + mem := durable.NewMemStore() + st := &noDispatchStore{Store: mem} + rec := newEffectRecorder() + h, err := durable.NewRunner(entryTwoEffectsMachine(), st, + durable.WithEffectHandler[string, string, *runCtx](rec.handler())). + Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")) + mustRefuseNoDispatchStore(t, "Start", err) + if h != nil { + t.Fatal("Start returned a Handle, want none") + } + if st.writes != 0 || rec.totalApplies() != 0 { + t.Fatalf("Start wrote %d times and applied %d effects, want none", st.writes, rec.totalApplies()) + } + if _, _, lerr := mem.Load(ctx, "i1"); !errors.Is(lerr, durable.ErrInstanceNotFound) { + t.Fatalf("Load after the refused Start = %v, want ErrInstanceNotFound", lerr) + } + }) + + // started returns a Store holding an instance started with no handler, after fired + // Fires, so with "go" it holds an effect not yet sent. + started := func(t *testing.T, fired ...string) *noDispatchStore { + t.Helper() + st := &noDispatchStore{Store: durable.NewMemStore()} + r := durable.NewRunner(effectMachine(), st) + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start with no handler: %v", err) + } + for _, ev := range fired { + if _, err := r.Fire(ctx, "i1", ev); err != nil { + t.Fatalf("Fire %s with no handler: %v", ev, err) + } + } + st.writes = 0 + return st + } + + for _, tc := range []struct { + name string + fired []string + }{{"no effect pending", nil}, {"an effect pending", []string{"go"}}} { + t.Run("Recover/"+tc.name, func(t *testing.T) { + st := started(t, tc.fired...) + rec := newEffectRecorder() + h, err := durable.Recover(ctx, effectMachine(), st, "i1", + durable.WithEffectHandler[string, string, *runCtx](rec.handler())) + mustRefuseNoDispatchStore(t, "Recover", err) + if h != nil { + t.Fatal("Recover returned a Handle, want none") + } + if st.writes != 0 || rec.totalApplies() != 0 { + t.Fatalf("Recover wrote %d times and applied %d effects, want none", st.writes, rec.totalApplies()) + } + }) + + t.Run("stateless Fire/"+tc.name, func(t *testing.T) { + st := started(t, tc.fired...) + _, before, _ := st.Load(ctx, "i1") + rec := newEffectRecorder() + ev := "go" + if len(tc.fired) > 0 { + ev = "bill" + } + _, err := durable.NewRunner(effectMachine(), st, + durable.WithEffectHandler[string, string, *runCtx](rec.handler())). + Fire(ctx, "i1", ev) + mustRefuseNoDispatchStore(t, "Fire", err) + if st.writes != 0 || rec.totalApplies() != 0 { + t.Fatalf("Fire wrote %d times and applied %d effects, want none", st.writes, rec.totalApplies()) + } + if _, tail, _ := st.Load(ctx, "i1"); len(tail) != len(before) { + t.Fatalf("the journal holds %d Records after the refused Fire, want %d", len(tail), len(before)) + } + }) + } + + t.Run("no handler", func(t *testing.T) { + st := started(t, "go") + h, err := durable.Recover(ctx, effectMachine(), st, "i1") + if err != nil { + t.Fatalf("Recover with no handler: %v", err) + } + if _, err := h.Fire(ctx, "bill"); err != nil { + t.Fatalf("Fire with no handler: %v", err) + } + if got := h.Instance().Current(); got != "billed" { + t.Fatalf("in %q, want billed", got) + } + }) +} + +// TestEffectHandler_DispatchStoresUnaffected proves MemStore and FileStore, which +// implement DispatchStore, take an effect handler: Start, the stateless Fire and +// Recover all run, and each effect applies once. +func TestEffectHandler_DispatchStoresUnaffected(t *testing.T) { + ctx := context.Background() + fs, err := durable.NewFileStore(t.TempDir()) + if err != nil { + t.Fatalf("NewFileStore: %v", err) + } + for _, tc := range []struct { + name string + st durable.Store + }{{"MemStore", durable.NewMemStore()}, {"FileStore", fs}} { + t.Run(tc.name, func(t *testing.T) { + rec := newEffectRecorder() + r := durable.NewRunner(effectMachine(), tc.st, + durable.WithEffectHandler[string, string, *runCtx](rec.handler())) + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + if _, err := r.Fire(ctx, "i1", "go"); err != nil { + t.Fatalf("Fire: %v", err) + } + if _, err := durable.Recover(ctx, effectMachine(), tc.st, "i1", + durable.WithEffectHandler[string, string, *runCtx](rec.handler())); err != nil { + t.Fatalf("Recover: %v", err) + } + if n := rec.totalApplies(); n != 1 { + t.Fatalf("applied %d effects, want the go step's one, once", n) + } + }) + } +} diff --git a/durable/dispatch_store_test.go b/durable/dispatch_store_test.go new file mode 100644 index 00000000..3ad5a0ff --- /dev/null +++ b/durable/dispatch_store_test.go @@ -0,0 +1,236 @@ +package durable_test + +import ( + "context" + "errors" + "strings" + "sync" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// dispatchProbeStore wraps a MemStore's dispatch tracking: it counts each call to +// Dispatched and MarkDispatched, and panics in either, or returns an error, when told +// to. +type dispatchProbeStore struct { + *durable.MemStore + mu sync.Mutex + dispatched, marks int + panicDispatched, panicMk bool + errDispatched, errMk error +} + +func newDispatchProbeStore(st *durable.MemStore) *dispatchProbeStore { + return &dispatchProbeStore{MemStore: st} +} + +func (s *dispatchProbeStore) Dispatched(ctx context.Context, id durable.InstanceID) (map[string]bool, error) { + s.mu.Lock() + s.dispatched++ + p, e := s.panicDispatched, s.errDispatched + s.mu.Unlock() + if p { + panic("Dispatched exploded") + } + if e != nil { + return nil, e + } + return s.MemStore.Dispatched(ctx, id) +} + +func (s *dispatchProbeStore) MarkDispatched(ctx context.Context, id durable.InstanceID, ids ...string) error { + s.mu.Lock() + s.marks++ + p, e := s.panicMk, s.errMk + s.mu.Unlock() + if p { + panic("MarkDispatched exploded") + } + if e != nil { + return e + } + return s.MemStore.MarkDispatched(ctx, id, ids...) +} + +func (s *dispatchProbeStore) counts() (dispatched, marks int) { + s.mu.Lock() + defer s.mu.Unlock() + return s.dispatched, s.marks +} + +// unmarkedFireEffect starts i1 on effectMachine and fires "go" with a handler that +// fails, so the journal holds step 0's effect unmarked for the next Recover to send. +func unmarkedFireEffect(t *testing.T) *durable.MemStore { + t.Helper() + ctx := context.Background() + st := durable.NewMemStore() + live := &stepIDHandler{failStep: "0"} + h, err := durable.NewRunner(effectMachine(), st, durable.WithEffectHandler[string, string, *runCtx](live.handle)). + Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Fire go: %v, want ErrEffectDispatch", err) + } + return st +} + +// TestDispatchStorePanic_ReturnsEffectDispatch proves a DispatchStore whose Dispatched +// or MarkDispatched panics fails Recover and the stateless Runner.Fire with +// ErrEffectDispatch, as a live step's dispatch and a panicking handler already do, +// rather than letting the panic out. +func TestDispatchStorePanic_ReturnsEffectDispatch(t *testing.T) { + ctx := context.Background() + healthy := durable.WithEffectHandler[string, string, *runCtx](newEffectRecorder().handler()) + cases := []struct { + name string + arm func(*dispatchProbeStore) + }{ + {"MarkDispatched", func(s *dispatchProbeStore) { s.panicMk = true }}, + {"Dispatched", func(s *dispatchProbeStore) { s.panicDispatched = true }}, + } + for _, tc := range cases { + t.Run(tc.name+"/Recover", func(t *testing.T) { + st := newDispatchProbeStore(unmarkedFireEffect(t)) + tc.arm(st) + err := noPanic(t, "Recover", func() error { + _, rerr := durable.Recover(ctx, effectMachine(), st, "i1", healthy) + return rerr + }) + if !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Recover: %v, want ErrEffectDispatch", err) + } + if !strings.Contains(err.Error(), "step 0 for") { + t.Fatalf("Recover: %v, want the message to name step 0", err) + } + }) + t.Run(tc.name+"/Runner.Fire", func(t *testing.T) { + st := newDispatchProbeStore(unmarkedFireEffect(t)) + tc.arm(st) + err := noPanic(t, "Runner.Fire", func() error { + _, ferr := durable.NewRunner(effectMachine(), st, healthy).Fire(ctx, "i1", "bill") + return ferr + }) + if !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Runner.Fire: %v, want ErrEffectDispatch", err) + } + }) + } + // Start applies its effects without the dispatched set, so a panicking + // MarkDispatched can't reach it; a step's live dispatch already turns it into + // ErrEffectDispatch. Pin both, so the three paths stay alike. + t.Run("MarkDispatched/live step", func(t *testing.T) { + st := newDispatchProbeStore(durable.NewMemStore()) + h, err := durable.NewRunner(effectMachine(), st, healthy).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + st.panicMk = true + err = noPanic(t, "Fire", func() error { + _, ferr := h.Fire(ctx, "go") + return ferr + }) + if !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Fire: %v, want ErrHandleFailed wrapping ErrEffectDispatch", err) + } + }) +} + +// pingMachine emits a notify on every "ping", so each Fire records one effect. +func pingMachine() *state.Machine[string, string, *runCtx] { + return state.ForgeFor[*runCtx]("ping"). + Action("notify", func(state.ActionCtx[*runCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + State("idle"). + Initial("idle"). + Transition("idle").On("ping").GoTo("idle").Do("notify"). + Quench() +} + +// TestRecover_LoadsTheDispatchedSetOncePerEffectRecord pins what Recover costs the +// Store: it loads the instance's whole dispatched set once for each tail Record that +// names effects, and marks nothing when every effect already landed. main did the same +// for a Fire's Records; this change adds a tick's and a service settle's at the same +// rate. Loading the set once per Recover would make this 1. +func TestRecover_LoadsTheDispatchedSetOncePerEffectRecord(t *testing.T) { + ctx := context.Background() + const n = 25 + st := newDispatchProbeStore(durable.NewMemStore()) + handler := durable.WithEffectHandler[string, string, *runCtx](newEffectRecorder().handler()) + h, err := durable.NewRunner(pingMachine(), st, handler).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for i := 0; i < n; i++ { + if _, err = h.Fire(ctx, "ping"); err != nil { + t.Fatalf("Fire ping %d: %v", i, err) + } + } + liveLoads, liveMarks := st.counts() + if _, err = durable.Recover(ctx, pingMachine(), st, "i1", handler); err != nil { + t.Fatalf("Recover: %v", err) + } + loads, marks := st.counts() + if got := loads - liveLoads; got != n { + t.Fatalf("Recover over %d effect Records loaded the dispatched set %d times, want %d", n, got, n) + } + if got := marks - liveMarks; got != 0 { + t.Fatalf("Recover marked %d effects, want none: every one landed live", got) + } +} + +var errDispatchStore = errors.New("dispatch table unavailable") + +// TestDispatchStoreError_ReturnsEffectDispatch proves a DispatchStore whose Dispatched +// or MarkDispatched returns an error fails a live step, Recover and the stateless +// Runner.Fire with ErrEffectDispatch wrapping the Store's error, as one that panics +// does: either way the effect isn't marked, and Recover sends it again. A live step's +// error is ErrHandleFailed too. +func TestDispatchStoreError_ReturnsEffectDispatch(t *testing.T) { + ctx := context.Background() + healthy := durable.WithEffectHandler[string, string, *runCtx](newEffectRecorder().handler()) + cases := []struct { + name string + arm func(*dispatchProbeStore) + }{ + {"MarkDispatched", func(s *dispatchProbeStore) { s.errMk = errDispatchStore }}, + {"Dispatched", func(s *dispatchProbeStore) { s.errDispatched = errDispatchStore }}, + } + want := func(t *testing.T, what string, err error) { + t.Helper() + if !errors.Is(err, durable.ErrEffectDispatch) || !errors.Is(err, errDispatchStore) { + t.Fatalf("%s: %v, want ErrEffectDispatch wrapping the Store's error", what, err) + } + } + for _, tc := range cases { + t.Run(tc.name+"/live step", func(t *testing.T) { + st := newDispatchProbeStore(durable.NewMemStore()) + h, err := durable.NewRunner(effectMachine(), st, healthy).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + tc.arm(st) + _, err = h.Fire(ctx, "go") + want(t, "Fire", err) + if !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("Fire: %v, want ErrHandleFailed", err) + } + }) + t.Run(tc.name+"/Recover", func(t *testing.T) { + st := newDispatchProbeStore(unmarkedFireEffect(t)) + tc.arm(st) + _, err := durable.Recover(ctx, effectMachine(), st, "i1", healthy) + want(t, "Recover", err) + }) + t.Run(tc.name+"/Runner.Fire", func(t *testing.T) { + st := newDispatchProbeStore(unmarkedFireEffect(t)) + tc.arm(st) + _, err := durable.NewRunner(effectMachine(), st, healthy).Fire(ctx, "i1", "bill") + want(t, "Runner.Fire", err) + }) + } +} diff --git a/durable/doc.go b/durable/doc.go index 559ca3b4..0cf88515 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -17,9 +17,12 @@ // recovery replays the exact recorded driving events and nondeterministic results // through the same pure transition function. // -// Exactly-once effects: a domain effect emitted by a transition is applied +// Exactly-once effects: a domain effect emitted by a step (Runner.Start's initial entry +// is at-least-once, and a parent transition an actor drives isn't dispatched) is applied // exactly once over the instance's lifetime — the live run plus any number of -// recoveries — even though the runtime's replay loop is at-least-once. Each +// recoveries — even though the runtime's replay loop is at-least-once. The exception is +// a crash or failed mark after the handler returned, or a handoff between owners, where +// an effect can apply twice, so keep handlers idempotent on EffectInstance plus the EffectID. Each // effect is stamped with a deterministic EffectID (step, ordinal, kind) and // deduplicated through the Store's dispatch set. // @@ -120,7 +123,7 @@ // publishing a message — as an Effect value the kernel routes out through // FireResult.Effects without applying. The Runner applies it through the caller- // supplied EffectHandler (WithEffectHandler), exactly once over the instance's -// lifetime. +// lifetime, with the exceptions under Exactly-once effects above. // // Each emitted effect is stamped with a deterministic EffectID derived from its // step, its emission ordinal within that step, and its kind — every component a @@ -132,6 +135,12 @@ // recovery redispatches it; a crash after dispatch finds the id marked and skips // it. // +// The dispatched set lives in a Store that implements DispatchStore, as MemStore and +// FileStore do. A Runner with an effect handler requires one: Start, Recover and the +// stateless Runner.Fire refuse any other Store with ErrNoDispatchStore before writing +// anything or calling the handler. Without a handler, any Store works and no effect is +// applied. +// // Kernel driver effects (services, timers, actors) are absorbed by their host // drivers and never reach the handler. // diff --git a/durable/effect.go b/durable/effect.go index 71da5ff3..be215cc1 100644 --- a/durable/effect.go +++ b/durable/effect.go @@ -34,8 +34,8 @@ import ( // Each dispatchable effect is stamped with an EffectID that is a pure function of // the step it was emitted at, its ordinal among the dispatchable effects of that // step, and its kind: "##". Every component is deterministic -// — the step is the Fire ordinal, emission order is fixed by the machine -// definition, and the kind is the effect's stable discriminant — so the same +// — the step is its journal ordinal (-1 for Start's entry effects), emission order is +// fixed by the machine definition, and the kind is the effect's stable discriminant — so the same // effect is stamped with the identical id on the live run and on every recovery // replay, which re-fires the same events and re-emits the same effects in the // same order. That stable identity is what makes the dedup set meaningful across @@ -49,6 +49,8 @@ import ( // (write-ahead: the intent to dispatch is durable before any dispatch). // 2. Dispatch each effect whose id is not already in the dispatched set, calling // the handler, and mark each id dispatched in the Store as it succeeds. +// 3. Checkpoint, if one is due. This comes last so a checkpoint never compacts an +// effect that hasn't landed. // // This yields exactly-once effect application over the at-least-once delivery the // runtime is built on: @@ -59,27 +61,55 @@ import ( // once) and, because it is then marked, never again. // - Crash AFTER dispatch (id marked): recovery re-emits the effect but finds its // id already marked and skips it — so it is not redispatched (exactly once). +// - Crash or failed mark AFTER the handler returned: the effect was applied but its +// id isn't marked, so recovery applies it again. The handler should be idempotent +// on EffectInstance plus the id for this window, and for a handoff, when two owners +// can run it at once. // - Handler error: the effect is left un-marked, and the Handle fails with // ErrHandleFailed wrapping ErrEffectDispatch, so Recover retries it -// (at-least-once until it succeeds; exactly-once thereafter). +// (at-least-once until it succeeds; exactly-once thereafter). A DispatchStore +// whose Dispatched or MarkDispatched fails leaves it un-marked too, and fails the +// same way. // // The dedup set is held by the Store (DispatchStore) so it shares the Record's // durability and survives checkpoint compaction — a delayed redispatch of an // already-applied, since-compacted effect is still recognized and skipped. // EffectHandler applies one emitted domain effect, identified by its stamped -// EffectID. The Runner calls it exactly once per EffectID over the lifetime of an -// instance (see WithEffectHandler). A non-nil error leaves the effect un-marked -// for Recover to retry, and fails the Handle with ErrHandleFailed wrapping -// ErrEffectDispatch and the error. +// EffectID. The Runner calls it once per EffectID over the lifetime of an instance +// (see WithEffectHandler), with three exceptions: a repeated Start can apply the initial +// entry's effects again (see Runner.Start), an effect applies again if the handler +// returned but the mark didn't land, and two owners can run it at once during a handoff. +// An id is unique only within its instance: EffectInstance reads the instance from ctx. +// A non-nil error leaves the effect un-marked for Recover to retry, and fails the Handle +// with ErrHandleFailed wrapping ErrEffectDispatch and the error. type EffectHandler func(ctx context.Context, effectID string, effect state.Effect) error +// effectInstanceKey is the ctx key for the instance an EffectHandler call belongs to. +type effectInstanceKey struct{} + +// withEffectInstance returns ctx carrying id for the handler. +func withEffectInstance(ctx context.Context, id InstanceID) context.Context { + return context.WithValue(ctx, effectInstanceKey{}, id) +} + +// EffectInstance returns the instance an EffectHandler call belongs to, from the ctx the +// handler received. A handler that keeps its own dedupe record must key on this plus the +// effect id, because effect ids repeat across instances. +func EffectInstance(ctx context.Context) (InstanceID, bool) { + id, ok := ctx.Value(effectInstanceKey{}).(InstanceID) + return id, ok +} + // DispatchStore is the dedup seam for idempotent effect dispatch: the Store // tracks which effect ids an instance has applied, so a (re)dispatch skips the // ones that already landed. It is an additive, optional capability — the core // Store interface is unchanged; a backend opts in by implementing these two -// methods, and the Runner dispatches effects only against a Store that does (the -// in-tree MemStore does). A persistent backend marks an id in the same +// methods. A Runner with an effect handler (WithEffectHandler) requires it: Start, +// Recover and the stateless Runner.Fire refuse a Store that doesn't implement it with +// ErrNoDispatchStore, before any Store write or handler call. A Runner with no handler +// dispatches nothing and needs neither method. The in-tree MemStore and FileStore +// implement it. A persistent backend marks an id in the same // transaction that records its side-effect acknowledgement to keep the guarantee // tight. type DispatchStore interface { @@ -96,6 +126,7 @@ type DispatchStore interface { // the same (step, ordinal, kind) inputs, so the id is stable. type dispatchableEffect struct { id string + step int // the step that produced the effect, for error messages effect state.Effect } @@ -149,37 +180,60 @@ func dispatchableEffects(step int, effects []state.Effect) []dispatchableEffect continue } id := fmt.Sprintf("%d#%d#%s", step, ordinal, effectKind(e)) - out = append(out, dispatchableEffect{id: id, effect: e}) + out = append(out, dispatchableEffect{id: id, step: step, effect: e}) ordinal++ } return out } +// metaMarshalError is the EffectEnvelope.Meta key under which recordEffects records +// why a KindedEffect's payload is missing: the message of the error its marshal +// returned. It follows the kernel's "crucible." namespace for reserved names. +const metaMarshalError = "crucible.marshalError" + // recordEffects returns the persisted form of a step's dispatchable effects: an // EffectEnvelope per effect carrying its stamped EffectID, so the write-ahead // Record durably names every effect that must be dispatched. A KindedEffect // marshals into a full envelope (kind + payload); a bare domain effect is named // by id and kind alone (its value is re-derived by replay, not reconstructed from -// the envelope). A marshal failure is reported so a non-serializable effect never -// silently drops from the durable record. -func recordEffects(des []dispatchableEffect) ([]state.EffectEnvelope, error) { +// the envelope). A KindedEffect whose payload won't marshal, such as one holding a +// chan, is recorded as a bare effect is, by id and kind with no payload, and its +// envelope's Meta holds the marshal error's message under "crucible.marshalError" +// (metaMarshalError). Replay re-derives its value, so it dispatches, live and on +// Recover, as any effect does, and the step doesn't fail. A MarshalJSON that panics is +// recorded the same way, with the panic's message in Meta. +func recordEffects(des []dispatchableEffect) []state.EffectEnvelope { if len(des) == 0 { - return nil, nil + return nil } out := make([]state.EffectEnvelope, 0, len(des)) for _, de := range des { env := state.EffectEnvelope{Kind: effectKind(de.effect), EffectID: de.id} if ke, ok := de.effect.(state.KindedEffect); ok { - marshaled, err := state.MarshalEffect(ke) + marshaled, err := marshalEffect(ke) if err != nil { - return nil, fmt.Errorf("durable: recording effect %q: %w", de.id, err) + env.Meta = map[string]any{metaMarshalError: validUTF8(err.Error())} + out = append(out, env) + continue } marshaled.EffectID = de.id env = marshaled } out = append(out, env) } - return out, nil + return out +} + +// marshalEffect is state.MarshalEffect with a panic in the effect's MarshalJSON +// returned as an error, so recordEffects records the effect by id and kind rather than +// let the panic out of a step the kernel has applied. +func marshalEffect(ke state.KindedEffect) (env state.EffectEnvelope, err error) { + defer func() { + if p := recover(); p != nil { + err = fmt.Errorf("effect payload panicked while encoding: %v", p) + } + }() + return state.MarshalEffect(ke) } // dispatchEffects applies a step's domain effects exactly once. It is called @@ -188,12 +242,64 @@ func recordEffects(des []dispatchableEffect) ([]state.EffectEnvelope, error) { // dispatched set it invokes the handler and, on success, marks the id dispatched. // A handler error stops dispatch and is returned wrapped in ErrEffectDispatch // with the failing effect left un-marked for a later recovery to retry. With no -// handler wired, or a Store that is not a DispatchStore, dispatch is a no-op (the -// ids are still recorded for a handler-equipped recovery). +// handler wired, dispatch is a no-op (the ids are still recorded for a +// handler-equipped recovery). A handler is only ever wired with a DispatchStore: +// Start and Recover refuse one without (see checkDispatchStore). func (h *Handle[S, E, C]) dispatchEffects(ctx context.Context, des []dispatchableEffect) error { return h.runner.dispatch(ctx, h.id, des) } +// checkDispatchStore refuses an effect handler wired with a Store that isn't a +// DispatchStore, which couldn't track which effects were applied. Start and recover, +// which Recover and the stateless Fire share, call it before they touch the Store, so +// every Handle that dispatches has dispatch tracking. The error wraps +// ErrNoDispatchStore, not ErrEffectDispatch: retrying doesn't help. +func (r *Runner[S, E, C]) checkDispatchStore(id InstanceID) error { + if r.cfg.effectHandler == nil { + return nil + } + if _, ok := r.store.(DispatchStore); !ok { + return fmt.Errorf("%w: instance %q: a Store that implements DispatchStore tracks the effects the handler applied, and %T doesn't; wire one, or drop WithEffectHandler", ErrNoDispatchStore, id, r.store) + } + return nil +} + +// dispatching reports whether des has effects to apply: a handler is wired and des +// isn't empty. Otherwise dispatch is a no-op. +func (r *Runner[S, E, C]) dispatching(des []dispatchableEffect) bool { + return len(des) > 0 && r.cfg.effectHandler != nil +} + +// applyStartEffects invokes the handler for the initial entry's domain effects. Like +// dispatch it is a no-op without a handler. It marks nothing, because the instance +// doesn't exist yet and nothing replays these effects. +func (r *Runner[S, E, C]) applyStartEffects(ctx context.Context, id InstanceID, des []dispatchableEffect) error { + if !r.dispatching(des) { + return nil + } + for _, de := range des { + if err := r.applyEffect(ctx, id, de); err != nil { + return err + } + } + return nil +} + +// applyEffect calls the effect handler for de, with the instance on its ctx. It wraps a +// handler error, or a panic in the handler, in ErrEffectDispatch, so Start, a step and +// Recover all fail the same way, rather than let a panic out. +func (r *Runner[S, E, C]) applyEffect(ctx context.Context, id InstanceID, de dispatchableEffect) (err error) { + defer func() { + if p := recover(); p != nil { + err = fmt.Errorf("%w: effect %q for %q: handler panicked: %v", ErrEffectDispatch, de.id, id, p) + } + }() + if herr := r.cfg.effectHandler(withEffectInstance(ctx, id), de.id, de.effect); herr != nil { + return fmt.Errorf("%w: effect %q for %q: %w", ErrEffectDispatch, de.id, id, herr) + } + return nil +} + // dispatchReplayEffects re-dispatches a replayed step's domain effects during // recovery: it re-stamps the re-emitted effects with the same deterministic ids // (step and emission order reproduce exactly) and applies only those not already @@ -207,30 +313,40 @@ func (r *Runner[S, E, C]) dispatchReplayEffects(ctx context.Context, id Instance // dispatch is the shared exactly-once apply loop used by the live path and by // recovery replay: it reads the instance's dispatched set, invokes the handler // for each not-yet-dispatched effect, and marks each id as it succeeds. It is a -// no-op without a handler or a DispatchStore. -func (r *Runner[S, E, C]) dispatch(ctx context.Context, id InstanceID, des []dispatchableEffect) error { - if len(des) == 0 || r.cfg.effectHandler == nil { +// no-op without a handler. An error or a panic in the Store's +// Dispatched or MarkDispatched becomes an ErrEffectDispatch error wrapping it, as +// applyEffect makes one in the handler, so a step and Recover fail the same way. +func (r *Runner[S, E, C]) dispatch(ctx context.Context, id InstanceID, des []dispatchableEffect) (err error) { + if !r.dispatching(des) { return nil } + // Start and recover refuse a handler without dispatch tracking, so this holds on + // every path today. Should a new one skip them, refuse here too, with the permanent + // ErrNoDispatchStore rather than a retryable ErrEffectDispatch. ds, ok := r.store.(DispatchStore) if !ok { - return nil + return r.checkDispatchStore(id) } + defer func() { + if p := recover(); p != nil { + err = fmt.Errorf("%w: step %d for %q: effect dispatch panicked: %v", ErrEffectDispatch, des[0].step, id, p) + } + }() dispatched, err := ds.Dispatched(ctx, id) if err != nil { - return fmt.Errorf("durable: loading dispatched set for %q: %w", id, err) + return fmt.Errorf("%w: loading dispatched set for %q: %w", ErrEffectDispatch, id, err) } for _, de := range des { if dispatched[de.id] { continue } - if err := r.cfg.effectHandler(ctx, de.id, de.effect); err != nil { - return fmt.Errorf("%w: effect %q for %q: %w", ErrEffectDispatch, de.id, id, err) + if err := r.applyEffect(ctx, id, de); err != nil { + return err } if err := ds.MarkDispatched(ctx, id, de.id); err != nil { - return fmt.Errorf("durable: marking effect %q dispatched for %q: %w", de.id, id, err) + return fmt.Errorf("%w: marking effect %q dispatched for %q: %w", ErrEffectDispatch, de.id, id, err) } } return nil diff --git a/durable/effect_marshal_panic_test.go b/durable/effect_marshal_panic_test.go new file mode 100644 index 00000000..4e16175b --- /dev/null +++ b/durable/effect_marshal_panic_test.go @@ -0,0 +1,106 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests pin a KindedEffect whose MarshalJSON panics: it is recorded by id and +// kind, as one whose marshal fails, rather than panicking out of a step the kernel +// applied. A Kind that panics still fails the Handle. + +// panicky is a KindedEffect whose MarshalJSON panics. +type panicky struct{} + +func (panicky) Kind() string { return "demo.panicky" } +func (panicky) MarshalJSON() ([]byte, error) { panic("marshal blew up") } + +// panickyKind is a KindedEffect whose Kind panics. +type panickyKind struct{} + +func (panickyKind) Kind() string { panic("kind blew up") } + +func emitting(eff state.Effect) func(state.ActionCtx[svcCtx]) (state.Effect, error) { + return func(state.ActionCtx[svcCtx]) (state.Effect, error) { return eff, nil } +} + +func panickyMachine(eff state.Effect) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("pnk"). + Action("emit", emitting(eff)). + State("idle"). + State("done").Final(). + Initial("idle"). + Transition("idle").On("go").GoTo("done").Do("emit"). + Quench() +} + +// fireCatching fires event on h and returns the panic that escaped, or the error. +func fireCatching(h *durable.Handle[string, string, svcCtx], event string) (panicked any, err error) { + defer func() { panicked = recover() }() + _, err = h.Fire(context.Background(), event) + return nil, err +} + +// A KindedEffect whose MarshalJSON panics is recorded as one whose marshal fails: by id +// and kind, with the panic's message in Meta under crucible.marshalError. The step +// doesn't panic or fail, and Recover replays it. +func TestUnmarshalableEffect_PanickingMarshal_RecordsByIDAndKind(t *testing.T) { + ctx := context.Background() + m := panickyMachine(panicky{}) + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store).Start(ctx, "pnk-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + p, ferr := fireCatching(h, "go") + if p != nil || ferr != nil { + t.Fatalf("Fire = %v, panic %v; want neither", ferr, p) + } + _, recs, err := store.Load(ctx, "pnk-1") + if err != nil || len(recs) != 1 || len(recs[0].Effects) != 1 { + t.Fatalf("Load = %d Records (err %v), want one with one effect", len(recs), err) + } + env := recs[0].Effects[0] + if env.Kind != "demo.panicky" || env.EffectID != "0#0#demo.panicky" || len(env.Payload) != 0 { + t.Fatalf("recorded %+v, want kind demo.panicky, id 0#0#demo.panicky and no payload", env) + } + if msg, _ := env.Meta[metaMarshalError].(string); !strings.Contains(msg, "marshal blew up") { + t.Fatalf("Meta = %v, want the panic's message under %q", env.Meta, metaMarshalError) + } + rh, err := durable.Recover(ctx, m, store, "pnk-1") + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := rh.Instance().Current(); got != "done" { + t.Fatalf("recovered in %q, want done", got) + } +} + +// Pins current behavior: a KindedEffect whose Kind panics has no kind to record it by, +// so it can't take the id-and-kind fallback. The panic leaves the Fire, and the Handle +// is failed first, as for any panic in host code during a step, so the caller can +// Recover. The kernel applied the transition, but nothing was journaled. +func TestUnmarshalableEffect_PanickingKind_FailsTheHandle(t *testing.T) { + ctx := context.Background() + m := panickyMachine(panickyKind{}) + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store).Start(ctx, "pnk-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if p, _ := fireCatching(h, "go"); p == nil || !strings.Contains(fmt.Sprint(p), "kind blew up") { + t.Fatalf("Fire panicked with %v, want the Kind panic", p) + } + if _, err := h.Fire(ctx, "go"); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("Fire after the panic = %v, want ErrHandleFailed", err) + } + if got := tailLen(t, store, "pnk-1"); got != 0 { + t.Fatalf("the journal holds %d Records, want none", got) + } +} diff --git a/durable/effect_recover_test.go b/durable/effect_recover_test.go new file mode 100644 index 00000000..aba5bcaf --- /dev/null +++ b/durable/effect_recover_test.go @@ -0,0 +1,409 @@ +package durable_test + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// stepIDHandler applies every effect except those of step failStep, for which it +// returns an error, and records every id it was called with, failed or not. +type stepIDHandler struct { + failStep string + tried []string + applied []string +} + +func (s *stepIDHandler) handle(_ context.Context, id string, _ state.Effect) error { + s.tried = append(s.tried, id) + if strings.HasPrefix(id, s.failStep+"#") { + return errors.New("downstream unavailable") + } + s.applied = append(s.applied, id) + return nil +} + +// panicHandler panics on every effect. +func panicHandler(context.Context, string, state.Effect) error { + panic("handler exploded") +} + +// noPanic runs f and turns a panic out of it into a test failure, so a test of a +// panic guard reports instead of crashing the test binary. +func noPanic(t *testing.T, what string, f func() error) (err error) { + t.Helper() + defer func() { + if p := recover(); p != nil { + t.Fatalf("%s panicked: %v", what, p) + } + }() + return f() +} + +// pairNotifyMachine has two parallel regions whose timers both fall due one second +// after "go", each emitting a different host effect, so one Tick fires both. +func pairNotifyMachine() *state.Machine[string, string, *runCtx] { + return state.ForgeFor[*runCtx]("pairNotify"). + Action("notify", func(state.ActionCtx[*runCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + Action("charge", func(state.ActionCtx[*runCtx]) (state.Effect, error) { + return chargeEffect{Cents: 500}, 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("notify"). + Transition("r1").After(time.Second).On("toR2").GoTo("r2").Do("charge"). + Quench() +} + +// assertAppliedOnceAsLive checks the recovered handler applied exactly the ids the +// live run tried and failed, each once, and nothing the live run already applied. +func assertAppliedOnceAsLive(t *testing.T, live *stepIDHandler, healthy *effectRecorder, wantFailed int) { + t.Helper() + var failed []string + for _, id := range live.tried { + if strings.HasPrefix(id, live.failStep+"#") { + failed = append(failed, id) + } + } + if len(failed) != wantFailed { + t.Fatalf("live run tried %d effects of step %s (%v), want %d", len(failed), live.failStep, live.tried, wantFailed) + } + for _, id := range failed { + if n := healthy.count(id); n != 1 { + t.Fatalf("Recover applied the live run's failed effect %q %d times, want once (applied %v)", id, n, healthy.ids()) + } + } + for _, id := range live.applied { + if n := healthy.count(id); n != 0 { + t.Fatalf("Recover applied %q again, which the live run already applied", id) + } + } + if n := healthy.totalApplies(); n != len(failed) { + t.Fatalf("Recover applied %d effects (%v), want the %d the live run failed", n, healthy.ids(), len(failed)) + } +} + +// TestRecover_RedispatchesAFailedTimerEffect proves an effect a timer transition +// emitted, whose dispatch failed live, is applied exactly once by Recover, under the +// EffectID the live attempt saw. +func TestRecover_RedispatchesAFailedTimerEffect(t *testing.T) { + ctx := context.Background() + st := durable.NewMemStore() + clk := state.NewFakeClock(epoch) + live := &stepIDHandler{failStep: "1"} // step 0 is "go", step 1 the tick + h, err := durable.NewRunner(timerNotifyMachine(), st, + durable.WithEffectHandler[string, string, *runCtx](live.handle), + durable.WithRunnerClock[string, string, *runCtx](clk)).Start(ctx, "i1", &runCtx{}, 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 _, err = h.Tick(ctx); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Tick: %v, want ErrHandleFailed wrapping ErrEffectDispatch", err) + } + healthy := newEffectRecorder() + if _, err = durable.Recover(ctx, timerNotifyMachine(), st, "i1", + durable.WithEffectHandler[string, string, *runCtx](healthy.handler()), + durable.WithRunnerClock[string, string, *runCtx](clk)); err != nil { + t.Fatalf("Recover: %v", err) + } + assertAppliedOnceAsLive(t, live, healthy, 1) +} + +// TestRecover_RedispatchesAFailedServiceSettleEffect proves the same for an effect +// the transition a service result drives emitted. +func TestRecover_RedispatchesAFailedServiceSettleEffect(t *testing.T) { + ctx := context.Background() + st := durable.NewMemStore() + var calls int64 + fn := counterService(&calls) + live := &stepIDHandler{failStep: "1"} // step 0 is "start", step 1 the settle + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(fetchThenWaitMachine(fn), st, + append(opts, durable.WithEffectHandler[string, string, svcCtx](live.handle))...).Start(ctx, "i1", 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) + } + if _, _, err = h.RunService(ctx, state.InvokeID("fetchThenWait", "loading", 0)); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("RunService: %v, want ErrEffectDispatch", err) + } + healthy := newEffectRecorder() + if _, err = durable.Recover(ctx, fetchThenWaitMachine(fn), st, "i1", + append(opts, durable.WithEffectHandler[string, string, svcCtx](healthy.handler()))...); err != nil { + t.Fatalf("Recover: %v", err) + } + assertAppliedOnceAsLive(t, live, healthy, 1) + if calls != 1 { + t.Fatalf("the service ran %d times, want once: Recover replays its recorded result", calls) + } +} + +// TestRecover_RedispatchesAMultiTimerTicksEffects proves a tick that fires two timers, +// each emitting an effect, re-dispatches both on Recover under the ids the live +// attempt saw. +func TestRecover_RedispatchesAMultiTimerTicksEffects(t *testing.T) { + ctx := context.Background() + st := durable.NewMemStore() + clk := state.NewFakeClock(epoch) + live := &stepIDHandler{failStep: "1"} + h, err := durable.NewRunner(pairNotifyMachine(), st, + durable.WithEffectHandler[string, string, *runCtx](live.handle), + durable.WithRunnerClock[string, string, *runCtx](clk)).Start(ctx, "i1", &runCtx{}, 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) + fired, err := h.Tick(ctx) + if len(fired) != 2 || !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Tick fired %d timers, err %v; want both, and ErrEffectDispatch", len(fired), err) + } + // The handler stops at the first failure, so the live run tried only the first + // effect; the tick's Record names both ids it stamped. + _, recs, err := st.Load(ctx, "i1") + if err != nil { + t.Fatalf("Load: %v", err) + } + var stamped []string + for _, r := range recs { + if r.Tick { + for _, env := range r.Effects { + stamped = append(stamped, env.EffectID) + } + } + } + if len(stamped) != 2 || len(live.tried) != 1 || live.tried[0] != stamped[0] { + t.Fatalf("the tick stamped %v and the live run tried %v; want two ids, the first tried live", stamped, live.tried) + } + live.tried = stamped + healthy := newEffectRecorder() + if _, err = durable.Recover(ctx, pairNotifyMachine(), st, "i1", + durable.WithEffectHandler[string, string, *runCtx](healthy.handler()), + durable.WithRunnerClock[string, string, *runCtx](clk)); err != nil { + t.Fatalf("Recover: %v", err) + } + assertAppliedOnceAsLive(t, live, healthy, 2) +} + +// TestStart_HandlerPanic_ReturnsEffectDispatchAndLeavesNoInstance proves a handler +// that panics on the initial entry's effect fails Start with ErrEffectDispatch, as a +// handler error does, and leaves no instance behind. +func TestStart_HandlerPanic_ReturnsEffectDispatchAndLeavesNoInstance(t *testing.T) { + ctx := context.Background() + st := durable.NewMemStore() + r := durable.NewRunner(entryNotifyMachine(), st, durable.WithEffectHandler[string, string, *runCtx](panicHandler)) + err := noPanic(t, "Start", func() error { + _, serr := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")) + return serr + }) + if !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Start: %v, want ErrEffectDispatch", err) + } + if _, _, err = st.Load(ctx, "i1"); !errors.Is(err, durable.ErrInstanceNotFound) { + t.Fatalf("Load after a failed Start: %v, want ErrInstanceNotFound", err) + } +} + +// TestRecover_HandlerPanic_ReturnsEffectDispatch proves a handler that panics while +// Recover re-dispatches a step's unmarked effect, a Fire's, a tick's or a service +// settle's, fails Recover with ErrEffectDispatch rather than panicking out of it. +func TestRecover_HandlerPanic_ReturnsEffectDispatch(t *testing.T) { + ctx := context.Background() + t.Run("fire", func(t *testing.T) { + st := durable.NewMemStore() + live := &stepIDHandler{failStep: "0"} + h, err := durable.NewRunner(effectMachine(), st, durable.WithEffectHandler[string, string, *runCtx](live.handle)). + Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Fire go: %v, want ErrEffectDispatch", err) + } + err = noPanic(t, "Recover", func() error { + _, rerr := durable.Recover(ctx, effectMachine(), st, "i1", durable.WithEffectHandler[string, string, *runCtx](panicHandler)) + return rerr + }) + if !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Recover: %v, want ErrEffectDispatch", err) + } + }) + t.Run("tick", func(t *testing.T) { + st := durable.NewMemStore() + clk := state.NewFakeClock(epoch) + live := &stepIDHandler{failStep: "1"} + h, err := durable.NewRunner(timerNotifyMachine(), st, + durable.WithEffectHandler[string, string, *runCtx](live.handle), + durable.WithRunnerClock[string, string, *runCtx](clk)).Start(ctx, "i1", &runCtx{}, 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 _, err = h.Tick(ctx); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Tick: %v, want ErrEffectDispatch", err) + } + err = noPanic(t, "Recover", func() error { + _, rerr := durable.Recover(ctx, timerNotifyMachine(), st, "i1", + durable.WithEffectHandler[string, string, *runCtx](panicHandler), + durable.WithRunnerClock[string, string, *runCtx](clk)) + return rerr + }) + if !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Recover: %v, want ErrEffectDispatch", err) + } + }) + t.Run("service", func(t *testing.T) { + st := durable.NewMemStore() + var calls int64 + fn := counterService(&calls) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + live := &stepIDHandler{failStep: "1"} + h, err := durable.NewRunner(fetchThenWaitMachine(fn), st, reg, + durable.WithEffectHandler[string, string, svcCtx](live.handle)).Start(ctx, "i1", 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) + } + if _, _, err = h.RunService(ctx, state.InvokeID("fetchThenWait", "loading", 0)); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("RunService: %v, want ErrEffectDispatch", err) + } + err = noPanic(t, "Recover", func() error { + _, rerr := durable.Recover(ctx, fetchThenWaitMachine(fn), st, "i1", reg, + durable.WithEffectHandler[string, string, svcCtx](panicHandler)) + return rerr + }) + if !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Recover: %v, want ErrEffectDispatch", err) + } + }) +} + +// olderVersionJournal copies src's journal for id into a fresh MemStore as a version +// before tick and service effects were dispatched would have left it: the checkpoint +// and every Record are of journal format 1, the tick and service Records name no +// effects, and only the Fire effects are marked dispatched. +func olderVersionJournal(t *testing.T, src *durable.MemStore, id durable.InstanceID) *durable.MemStore { + t.Helper() + ctx := context.Background() + snap, recs, err := src.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + dst := durable.NewMemStore() + if err = dst.Checkpoint(ctx, id, withCheckpointFormat(t, snap, 1), -1); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + stripped := 0 + for _, rec := range recs { + if len(rec.Event) == 0 { + if len(rec.Effects) > 0 { + stripped++ + } + rec.Effects = nil + } else { + for _, env := range rec.Effects { + if err = dst.MarkDispatched(ctx, id, env.EffectID); err != nil { + t.Fatalf("MarkDispatched: %v", err) + } + } + } + rec.Format = 1 + if _, err = dst.Append(ctx, id, rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + if stripped == 0 { + t.Fatal("no tick or service Record named an effect to strip") + } + return dst +} + +// TestRecover_DoesNotSendAnOlderVersionsTickOrServiceEffects proves Recover doesn't +// dispatch an effect a tick or service settle emitted under a version that never +// dispatched them: their Records name no effects, so there is nothing write-ahead to +// retry, and sending it now would apply an effect the run never applied. +func TestRecover_DoesNotSendAnOlderVersionsTickOrServiceEffects(t *testing.T) { + ctx := context.Background() + t.Run("tick", func(t *testing.T) { + st := durable.NewMemStore() + clk := state.NewFakeClock(epoch) + h, err := durable.NewRunner(timerNotifyMachine(), st, durable.WithRunnerClock[string, string, *runCtx](clk)). + Start(ctx, "i1", &runCtx{}, 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 _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + old := olderVersionJournal(t, st, "i1") + rec := newEffectRecorder() + if _, err = durable.Recover(ctx, timerNotifyMachine(), old, "i1", + durable.WithEffectHandler[string, string, *runCtx](rec.handler()), + durable.WithRunnerClock[string, string, *runCtx](clk)); err != nil { + t.Fatalf("Recover: %v", err) + } + if n := rec.totalApplies(); n != 0 { + t.Fatalf("Recover sent %d effects from an older version's tick (%v), want 0", n, rec.ids()) + } + }) + t.Run("service", func(t *testing.T) { + st := durable.NewMemStore() + var calls int64 + fn := counterService(&calls) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + h, err := durable.NewRunner(fetchThenWaitMachine(fn), st, reg).Start(ctx, "i1", 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) + } + mustRunService(t, h, state.InvokeID("fetchThenWait", "loading", 0)) + old := olderVersionJournal(t, st, "i1") + rec := newEffectRecorder() + if _, err = durable.Recover(ctx, fetchThenWaitMachine(fn), old, "i1", reg, + durable.WithEffectHandler[string, string, svcCtx](rec.handler())); err != nil { + t.Fatalf("Recover: %v", err) + } + if n := rec.totalApplies(); n != 0 { + t.Fatalf("Recover sent %d effects from an older version's service settle (%v), want 0", n, rec.ids()) + } + }) +} diff --git a/durable/effect_test.go b/durable/effect_test.go index bb065564..62a8e1f8 100644 --- a/durable/effect_test.go +++ b/durable/effect_test.go @@ -407,31 +407,6 @@ func TestRunner_EffectDispatch_BareEffect_StampedByType(t *testing.T) { } } -// nonDispatchStore wraps a Store WITHOUT implementing DispatchStore, so the -// Runner records effect ids but cannot dedup; dispatch must degrade to a no-op -// rather than panic. -type nonDispatchStore struct{ durable.Store } - -// TestRunner_EffectDispatch_NonDispatchStore_NoOp proves a Store that does not -// implement DispatchStore leaves dispatch inert (the ids are still recorded for a -// dispatch-capable backend on recovery). -func TestRunner_EffectDispatch_NonDispatchStore_NoOp(t *testing.T) { - ctx := context.Background() - st := nonDispatchStore{Store: durable.NewMemStore()} - rec := newEffectRecorder() - r := durable.NewRunner(effectMachine(), st, - durable.WithEffectHandler[string, string, *runCtx](rec.handler())) - if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { - t.Fatalf("Start: %v", err) - } - if _, err := r.Fire(ctx, "i1", "go"); err != nil { - t.Fatalf("Fire go: %v", err) - } - if n := rec.totalApplies(); n != 0 { - t.Fatalf("non-dispatch store applied %d effects, want 0 (inert)", n) - } -} - // timerNotifyMachine emits a kernel driver effect (a delayed `after` transition) on // the same step a domain effect fires, so the dispatcher must route the driver // effect to the Scheduler and only the domain effect to the handler. The timer @@ -507,3 +482,182 @@ func TestMemStore_DispatchSet_MarkAndQuery(t *testing.T) { t.Fatalf("unmarked id reported dispatched") } } + +// entryNotifyMachine emits a host effect on entering the state an instance starts +// in, so the effect originates in Start rather than Fire. +func entryNotifyMachine() *state.Machine[string, string, *runCtx] { + return state.ForgeFor[*runCtx]("entryNotify"). + Action("notify", func(state.ActionCtx[*runCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + State("ready").OnEntry("notify"). + Initial("ready"). + Quench() +} + +// TestRunner_EffectDispatch_Start_AppliesEntryEffect proves a domain effect emitted +// on entering the initial state reaches the handler. +func TestRunner_EffectDispatch_Start_AppliesEntryEffect(t *testing.T) { + ctx := context.Background() + rec := newEffectRecorder() + r := durable.NewRunner(entryNotifyMachine(), durable.NewMemStore(), + durable.WithEffectHandler[string, string, *runCtx](rec.handler())) + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("Start: %v", err) + } + if n := rec.totalApplies(); n != 1 { + t.Fatalf("handler applied %d effects, want 1 (the initial state's entry notify)", n) + } +} + +// TestRunner_EffectDispatch_TimerTransition_AppliesEffect proves a domain effect +// emitted by a timer-driven transition reaches the handler. +func TestRunner_EffectDispatch_TimerTransition_AppliesEffect(t *testing.T) { + ctx := context.Background() + rec := newEffectRecorder() + clk := state.NewFakeClock(epoch) + r := durable.NewRunner(timerNotifyMachine(), durable.NewMemStore(), + durable.WithEffectHandler[string, string, *runCtx](rec.handler()), + durable.WithRunnerClock[string, string, *runCtx](clk)) + h, err := r.Start(ctx, "i1", &runCtx{}, 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 _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if n := rec.totalApplies(); n != 2 { + t.Fatalf("handler applied %d effects, want 2 (the timer transition's notify)", n) + } +} + +// TestRunner_EffectDispatch_ServiceSettle_AppliesEffect proves a domain effect +// emitted by the transition a service result drives reaches the handler. +func TestRunner_EffectDispatch_ServiceSettle_AppliesEffect(t *testing.T) { + ctx := context.Background() + rec := newEffectRecorder() + var calls int64 + fn := counterService(&calls) + r := durable.NewRunner(fetchThenWaitMachine(fn), durable.NewMemStore(), + durable.WithEffectHandler[string, string, svcCtx](rec.handler()), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))) + h, err := r.Start(ctx, "i1", 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) + } + mustRunService(t, h, state.InvokeID("fetchThenWait", "loading", 0)) + if n := rec.totalApplies(); n != 1 { + t.Fatalf("handler applied %d effects, want 1 (the settle transition's notify)", n) + } +} + +// TestRunner_EffectDispatch_FailedThenCheckpointed_AppliedOnce proves an effect +// whose dispatch failed is still applied exactly once, live or on recovery, after +// a later checkpoint compacts its step. +func TestRunner_EffectDispatch_FailedThenCheckpointed_AppliedOnce(t *testing.T) { + ctx := context.Background() + st := durable.NewMemStore() + live := newEffectRecorder() + live.failKinds["demo.notify"] = errors.New("downstream unavailable") + opts := []durable.Option[string, string, *runCtx]{ + durable.WithEffectHandler[string, string, *runCtx](live.handler()), + durable.WithCheckpointEvery[string, string, *runCtx](2), + } + h, err := durable.NewRunner(effectMachine(), st, opts...).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err == nil { // step 0: its notify fails + t.Fatalf("Fire go: want the handler error") + } + delete(live.failKinds, "demo.notify") + if _, err = h.Fire(ctx, "bill"); err != nil { // step 1: checkpoint compacts step 0 + // A Handle that refuses Fires after a failed dispatch is resumed by Recover. + if h, err = durable.Recover(ctx, effectMachine(), st, "i1", opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = h.Fire(ctx, "bill"); err != nil { + t.Fatalf("Fire bill: %v", err) + } + } + + healthy := newEffectRecorder() + if _, err = durable.Recover(ctx, effectMachine(), st, "i1", + durable.WithEffectHandler[string, string, *runCtx](healthy.handler())); err != nil { + t.Fatalf("Recover: %v", err) + } + // go emits notify; bill emits charge and notify. Each applies exactly once. + ids := append(live.ids(), healthy.ids()...) + if len(ids) != 3 { + t.Fatalf("applied %d effect ids across live and recovery, want 3: %v", len(ids), ids) + } + for _, id := range ids { + if n := live.count(id) + healthy.count(id); n != 1 { + t.Fatalf("effect %q applied %d times, want once", id, n) + } + } +} + +// failingEntryMachine emits a host effect on entry, then fails the entry. +func failingEntryMachine() *state.Machine[string, string, *runCtx] { + return state.ForgeFor[*runCtx]("failingEntry"). + Action("notify", func(state.ActionCtx[*runCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + Action("boom", func(state.ActionCtx[*runCtx]) (state.Effect, error) { + return nil, errors.New("boom") + }). + State("ready").OnEntry("notify").OnEntry("boom"). + Initial("ready"). + Quench() +} + +// TestRunner_EffectDispatch_Start_FailedEntryAppliesNothing proves an effect emitted +// before a failed entry action doesn't reach the handler, as with a failed Fire. +func TestRunner_EffectDispatch_Start_FailedEntryAppliesNothing(t *testing.T) { + ctx := context.Background() + rec := newEffectRecorder() + r := durable.NewRunner(failingEntryMachine(), durable.NewMemStore(), + durable.WithEffectHandler[string, string, *runCtx](rec.handler())) + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("Start: %v", err) + } + if n := rec.totalApplies(); n != 0 { + t.Fatalf("handler applied %d effects from a failed entry, want 0", n) + } +} + +// TestEffectInstance_ReachesTheHandler proves a handler can tell instances apart, on +// Start and on a step. +func TestEffectInstance_ReachesTheHandler(t *testing.T) { + ctx := context.Background() + var seen []durable.InstanceID + handler := func(ctx context.Context, _ string, _ state.Effect) error { + id, ok := durable.EffectInstance(ctx) + if !ok { + t.Error("no instance on the handler's ctx") + } + seen = append(seen, id) + return nil + } + r := durable.NewRunner(entryNotifyMachine(), durable.NewMemStore(), + durable.WithEffectHandler[string, string, *runCtx](handler)) + for _, id := range []durable.InstanceID{"a", "b"} { + if _, err := r.Start(ctx, id, &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("Start: %v", err) + } + } + if len(seen) != 2 || seen[0] != "a" || seen[1] != "b" { + t.Fatalf("handler saw %v, want [a b]", seen) + } + if _, ok := durable.EffectInstance(ctx); ok { + t.Fatal("instance on a ctx the runner never touched") + } +} diff --git a/durable/effects_dropped_store_test.go b/durable/effects_dropped_store_test.go new file mode 100644 index 00000000..204ee2ce --- /dev/null +++ b/durable/effects_dropped_store_test.go @@ -0,0 +1,160 @@ +package durable_test + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// effectsDroppingStore is a Store that keeps every Record field but Effects, as a +// custom backend with a schema that has no column for the envelopes would. +type effectsDroppingStore struct{ *durable.MemStore } + +func (s effectsDroppingStore) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { + rec.Effects = nil + return s.MemStore.Append(ctx, id, rec, opts...) +} + +// TestRecover_StoreThatDropsEffects_SendsACrashedStepsEffects answers whether +// exactly-once depends on the Store keeping Record.Effects. A step whose dispatch +// failed live, as a crash between the append and the dispatch leaves it, holds its +// effect unmarked. Recover must send it once, under the id the live run stamped, even +// from a Store that didn't keep the envelopes: replay re-derives the effect, and the +// Record's format says this version dispatched it. Before this change a Fire's effects +// were sent this way whatever the Record held. +func TestRecover_StoreThatDropsEffects_SendsACrashedStepsEffects(t *testing.T) { + ctx := context.Background() + t.Run("fire", func(t *testing.T) { + st := effectsDroppingStore{durable.NewMemStore()} + live := &stepIDHandler{failStep: "0"} + h, err := durable.NewRunner(effectMachine(), st, durable.WithEffectHandler[string, string, *runCtx](live.handle)). + Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Fire go: %v, want ErrEffectDispatch", err) + } + healthy := newEffectRecorder() + if _, err = durable.Recover(ctx, effectMachine(), st, "i1", durable.WithEffectHandler[string, string, *runCtx](healthy.handler())); err != nil { + t.Fatalf("Recover: %v", err) + } + assertAppliedOnceAsLive(t, live, healthy, 1) + }) + t.Run("tick", func(t *testing.T) { + st := effectsDroppingStore{durable.NewMemStore()} + clk := state.NewFakeClock(epoch) + live := &stepIDHandler{failStep: "1"} + h, err := durable.NewRunner(timerNotifyMachine(), st, + durable.WithEffectHandler[string, string, *runCtx](live.handle), + durable.WithRunnerClock[string, string, *runCtx](clk)). + Start(ctx, "i1", &runCtx{}, 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 _, err = h.Tick(ctx); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Tick: %v, want ErrEffectDispatch", err) + } + healthy := newEffectRecorder() + if _, err = durable.Recover(ctx, timerNotifyMachine(), st, "i1", + durable.WithEffectHandler[string, string, *runCtx](healthy.handler()), + durable.WithRunnerClock[string, string, *runCtx](clk)); err != nil { + t.Fatalf("Recover: %v", err) + } + assertAppliedOnceAsLive(t, live, healthy, 1) + }) + t.Run("service", func(t *testing.T) { + st := effectsDroppingStore{durable.NewMemStore()} + var calls int64 + fn := counterService(&calls) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + live := &stepIDHandler{failStep: "1"} + h, err := durable.NewRunner(fetchThenWaitMachine(fn), st, reg, durable.WithEffectHandler[string, string, svcCtx](live.handle)). + Start(ctx, "i1", 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) + } + if _, _, err = h.RunService(ctx, state.InvokeID("fetchThenWait", "loading", 0)); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("RunService: %v, want ErrEffectDispatch", err) + } + healthy := newEffectRecorder() + if _, err = durable.Recover(ctx, fetchThenWaitMachine(fn), st, "i1", reg, + durable.WithEffectHandler[string, string, svcCtx](healthy.handler())); err != nil { + t.Fatalf("Recover: %v", err) + } + assertAppliedOnceAsLive(t, live, healthy, 1) + if calls != 1 { + t.Fatalf("the service ran %d times, want 1", calls) + } + }) +} + +// withCheckpointFormat returns the checkpoint envelope cp with its journal format set to +// format, as the version that wrote format would have left it. +func withCheckpointFormat(t *testing.T, cp []byte, format int) []byte { + t.Helper() + var env map[string]json.RawMessage + if err := json.Unmarshal(cp, &env); err != nil { + t.Fatalf("decoding the checkpoint envelope: %v", err) + } + env["format"] = json.RawMessage(itoa(format)) + out, err := json.Marshal(env) + if err != nil { + t.Fatalf("encoding the checkpoint envelope: %v", err) + } + return out +} + +func itoa(n int) string { + b, _ := json.Marshal(n) + return string(b) +} + +// TestRecover_OlderVersionsFireEffectIsSentWithoutEnvelopes keeps what every version +// did for a Fire: Recover sends its unmarked effects whatever the Record holds. The +// journal here is of format 1, from a version before tick and service effects were +// dispatched, and its Fire Record names no effects. +func TestRecover_OlderVersionsFireEffectIsSentWithoutEnvelopes(t *testing.T) { + ctx := context.Background() + src := durable.NewMemStore() + live := &stepIDHandler{failStep: "0"} + h, err := durable.NewRunner(effectMachine(), src, durable.WithEffectHandler[string, string, *runCtx](live.handle)). + Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("Fire go: %v, want ErrEffectDispatch", err) + } + snap, recs, err := src.Load(ctx, "i1") + if err != nil { + t.Fatalf("Load: %v", err) + } + old := durable.NewMemStore() + if err = old.Checkpoint(ctx, "i1", withCheckpointFormat(t, snap, 1), -1); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + for _, rec := range recs { + rec.Format, rec.Effects = 1, nil + if _, err = old.Append(ctx, "i1", rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + healthy := newEffectRecorder() + if _, err = durable.Recover(ctx, effectMachine(), old, "i1", durable.WithEffectHandler[string, string, *runCtx](healthy.handler())); err != nil { + t.Fatalf("Recover: %v", err) + } + assertAppliedOnceAsLive(t, live, healthy, 1) +} diff --git a/durable/error_message_internal_test.go b/durable/error_message_internal_test.go new file mode 100644 index 00000000..59a36441 --- /dev/null +++ b/durable/error_message_internal_test.go @@ -0,0 +1,44 @@ +package durable + +import ( + "encoding/json" + "errors" + "testing" +) + +// TestValidUTF8_MatchesAJSONRoundTrip pins validUTF8 to what a Store keeps: the string +// a JSON round trip gives back, byte for byte, for valid text, a lone bad byte, a +// truncated multi-byte sequence and an encoded surrogate. +func TestValidUTF8_MatchesAJSONRoundTrip(t *testing.T) { + for _, in := range []string{"plain", "café 
 <&>", "bad \xff byte", "cut \xe2\x82", "\xed\xa0\x80 surrogate", "� kept"} { + b, err := json.Marshal(in) + if err != nil { + t.Fatalf("Marshal(%q): %v", in, err) + } + var want string + if err = json.Unmarshal(b, &want); err != nil { + t.Fatalf("Unmarshal(%s): %v", b, err) + } + if got := validUTF8(in); got != want { + t.Fatalf("validUTF8(%q) = %q, want the JSON round trip's %q", in, got, want) + } + } +} + +// panicError's Error method panics. +type panicError struct{} + +func (panicError) Error() string { panic("boom") } + +// TestNormalizedErrorMessage pins the shared helper encodeEventData and +// replayableOutcome use: a normalized message, or errorMessage's error naming what +// panicked. +func TestNormalizedErrorMessage(t *testing.T) { + msg, err := normalizedErrorMessage(errors.New("bad \xff"), "error payload") + if err != nil || msg != "bad �" { + t.Fatalf("got %q, %v; want the normalized message", msg, err) + } + if _, err = normalizedErrorMessage(panicError{}, "service error"); err == nil || err.Error() != "service error panicked: boom" { + t.Fatalf("got %v, want the panic named as a service error's", err) + } +} diff --git a/durable/errors.go b/durable/errors.go index f24f15e3..3d28140b 100644 --- a/durable/errors.go +++ b/durable/errors.go @@ -13,6 +13,7 @@ const ( errorCheckpointNotAdvancing = "checkpoint does not advance" errorInstanceExists = "instance already exists" errorEffectDispatch = "effect dispatch failed" + errorNoDispatchStore = "effect handler needs a DispatchStore" errorStepOutOfRange = "time-travel step out of range" errorEventDataEncoding = "event data can't be recorded" errorRecordTooLarge = "record too large for the journal" @@ -88,10 +89,25 @@ var ( ErrInstanceExists = errors.New(errorPrefix + errorInstanceExists) // ErrEffectDispatch wraps a failure returned by the caller-supplied effect - // handler (WithEffectHandler) while applying an emitted effect, or a panic in it. The effect was + // handler (WithEffectHandler) while applying an emitted effect, or a panic in it, + // and an error or panic in the Store's dispatch tracking (DispatchStore's + // Dispatched or MarkDispatched), with the cause in its chain. The effect was // persisted (write-ahead) but not marked dispatched, so the Handle fails with - // ErrHandleFailed wrapping it, and Recover dispatches it again. Callers match - // this with errors.Is to tell a dispatch failure from a kernel transition or - // persistence error. + // ErrHandleFailed wrapping it, and Recover dispatches it again; a failure in + // Runner.Start leaves no instance. Recover fails with this error while the handler, + // or the dispatch tracking, still does, so retrying Recover can succeed once they + // recover. An effect handler wired with a Store that isn't a DispatchStore is + // refused with ErrNoDispatchStore instead, which this doesn't match. Callers match + // this with errors.Is to tell a dispatch failure from a kernel transition or a + // Record's persistence error. ErrEffectDispatch = errors.New(errorPrefix + errorEffectDispatch) + + // ErrNoDispatchStore is returned by Start, Recover and the stateless Runner.Fire, + // before they read or write the Store or call the handler, for an effect handler + // (WithEffectHandler) wired with a Store that doesn't implement DispatchStore, + // which has no dispatch tracking. It is a permanent configuration error: retrying + // doesn't help. Wire a Store that implements DispatchStore, as MemStore and + // FileStore do, or drop WithEffectHandler. It doesn't match ErrEffectDispatch, so a + // caller that retries Recover on a dispatch failure doesn't loop on it. + ErrNoDispatchStore = errors.New(errorPrefix + errorNoDispatchStore) ) diff --git a/durable/runner.go b/durable/runner.go index 7af0b366..f70da283 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -9,6 +9,7 @@ import ( "slices" "sync" "time" + "unicode/utf8" "github.com/stablekernel/crucible/state" ) @@ -108,9 +109,12 @@ func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st // // A step that applied to the kernel but may not have been recorded leaves the Handle out // 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, +// reaches the caller after the Handle fails. So does a RunService or DeliverToActor whose +// context ended during the step, a Tick whose context ended while its timers fired, and +// any step, Fire included, that drove a Fire refused because a context ended, the +// caller's or one middleware derived from it. A message to an actor that the actor +// refused because the step's context ended doesn't fail it: the message is lost, as +// actor deliveries are across Recover. 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 @@ -119,7 +123,8 @@ func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st // 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 -// newer owner holds the instance: stop, because recovering won't help. +// newer owner holds the instance: stop, because recovering won't help. A failed effect +// dispatch fails the Handle the same way, and Recover retries the effect. type Handle[S comparable, E comparable, C any] struct { runner *Runner[S, E, C] id InstanceID @@ -345,27 +350,91 @@ func (h *Handle[S, E, C]) drainClock() []state.JournalEntry { // durable seams compose: the scheduler arms or cancels delayed (`after`) timers (and // the Handle's timer table mirrors their deadlines for checkpointing), the service // runner starts or stops invoked services, and the actor system spawns or stops -// child-machine actors. It is the shared absorb the live seam methods (Fire, -// RunService, DeliverToActor, Tick) call for the effects they produced, so a state a -// settle or delivery enters arms whatever it declares — a service whose onDone spawns -// an actor, an actor whose onDone arms a timer, and so on. Absorbing a driver's -// 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) +// child-machine actors. It is the absorb Fire calls for the effects its event produced, +// so a forwardTo forwards that event; a settle's go through absorbSettle. Absorbing a +// driver's 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, event any, effects []state.Effect) { // 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. if hasTimerEffect(effects) { h.absorbTimers(ctx, effects) } + h.absorbRunners(ctx, event, effects) +} + +// absorbSettle is absorbDrivers for the effects of a service settle's own Fire, so a +// state the settle enters arms whatever it declares, such as a service whose onDone +// spawns an actor. The ServiceRunner absorbed those effects itself as it settled, so +// absorbSettle doesn't hand them to it again, which would arm each service it starts a +// second time, where replay arms it once: it forgets the settled services the effects +// start or stop, and arms the timers, then the actors, in absorbDrivers' order. +func (h *Handle[S, E, C]) absorbSettle(ctx context.Context, effects []state.Effect) { + if hasTimerEffect(effects) { + h.absorbTimers(ctx, effects) + } + forgetSettled(h.settled, effects) + h.absorbActors(ctx, nil, effects, nil) +} + +// absorbRunners feeds the effects event's transition produced into the service runner, +// then the actor system: absorbServices, then absorbActors. absorbDrivers calls it after +// arming the timers. +func (h *Handle[S, E, C]) absorbRunners(ctx context.Context, event any, effects []state.Effect) { + h.absorbServices(ctx, effects) + h.absorbActors(ctx, event, effects, nil) +} + +// absorbServices feeds a transition's effects into the service runner, forgetting the +// settled services each service the effects start or stop. Tick calls it for each +// timer transition it fired, whose timers the scheduler already armed, before +// absorbActors for any of them: a timer that leaves a state stops its services, and one +// that enters a state starts them, as a Fire does. +func (h *Handle[S, E, C]) absorbServices(ctx context.Context, effects []state.Effect) { + forgetSettled(h.settled, effects) if h.svc != nil { h.svc.Absorb(ctx, effects) } - if h.actors != nil { - h.actorFires.attempt(effects) - defer h.actorFires.driving(ctx)() - h.actors.Absorb(ctx, effects) +} + +// absorbActors feeds the effects event's transition produced into the actor system, +// which stops and spawns its actors and routes the parent's messages, so a forwardTo +// forwards event; a nil event, as a settle's absorb passes, forwards nothing. An actor +// it spawns can drive a parent Fire at once, so a caller absorbs every service of the +// step first (see absorbServices): the parent Fire then stops a service the step +// started, as it does after a Fire and on replay. +// +// absorbActors skips a state's spawn whose activation has ended by the time the system +// would take it: the actor would run for a state that isn't active, which Recover, +// spawning the actors of the configuration it ends in, never runs. That's so when a +// parent Fire an earlier spawn drove left the state, as when one region's actor sends +// the parent a message that exits another region's state (see parentFires.left), so +// absorbActors feeds the system one effect at a time. It's so too when a later effect +// of the step stops the actor (see stoppedLater): one in effects, or in later, the +// effects a later call of the same step absorbs, as when a later timer of a Tick +// leaves the state. A spawn the step's effects then make for a new activation of the +// state isn't skipped, unless a parent Fire left that one too. +func (h *Handle[S, E, C]) absorbActors(ctx context.Context, event any, effects, later []state.Effect) { + if h.actors == nil { + return + } + defer h.actorFires.driving(ctx)() + for i := range effects { + switch eff := effects[i].(type) { + case state.SpawnActor: + if h.actorFires.left(eff) || stoppedLater(eff, effects[i+1:], later) { + continue + } + case state.ForwardEvent: + // The actor system would deliver a nil event to the target. + if event == nil { + continue + } + } + one := effects[i : i+1 : i+1] + h.actorFires.attempt(one) + h.actors.AbsorbFor(ctx, event, one) } } @@ -498,7 +567,20 @@ func (h *Handle[S, E, C]) ID() InstanceID { return h.id } // 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. +// +// Start applies the initial entry's domain effects before the baseline write, and only +// if the entry succeeded: a failed entry still returns a Handle and a nil error, and +// Instance().InitialErr reports it. They're at-least-once, unlike a step's: a handler failure or a +// failed baseline write leaves no instance, so calling Start again re-applies every +// effect, as does a crash before the baseline. Overlapping Starts on one id, including a +// stale owner's, each apply them before the Store refuses all but one. To dedupe, key on +// EffectInstance plus the effect id. A handler wired only at Recover never sees them. +// With an effect handler wired, Start refuses a Store that isn't a DispatchStore with +// ErrNoDispatchStore, before it reads or writes the Store or calls the handler. 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.checkDispatchStore(id); err != nil { + return nil, err + } if _, _, err := r.store.Load(ctx, id); err == nil { return nil, fmt.Errorf("%w: %q", ErrInstanceExists, id) } else if !errors.Is(err, ErrInstanceNotFound) { @@ -518,10 +600,10 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt castOpts := append([]state.CastOption[S]{state.WithClock[S](recClock), state.WithUnboundedHistory[S]()}, opts...) inst := r.machine.Cast(input, castOpts...) - // Persist a baseline checkpoint at baselineStep (below the first fired step) - // so the instance is reconstructable from the Store before any event is fired. - // The baseline is the cast snapshot; the tail then accumulates fired steps on - // top of it. + // Encode a baseline checkpoint at baselineStep (below the first fired step), so the + // instance is reconstructable from the Store before any event is fired. The baseline + // is the cast snapshot; the tail then accumulates fired steps on top of it. Encoding + // comes before the effects, so an instance that can't be encoded applies none. snap, err := state.MarshalSnapshot(inst.Snapshot()) if err != nil { return nil, fmt.Errorf("durable: marshaling start snapshot for %q: %w", id, err) @@ -532,6 +614,16 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt if err != nil { return nil, fmt.Errorf("durable: marshaling start checkpoint envelope for %q: %w", id, err) } + // Apply the initial entry's domain effects before the instance exists: a handler + // failure then leaves nothing behind, so the caller can Start again. Nothing can + // re-derive these effects after the baseline, so they're at-least-once. An entry that + // failed applies none, as a failed Fire dispatches none. + if inst.InitialErr() == nil { + if err := r.applyStartEffects(ctx, id, dispatchableEffects(baselineStep, inst.InitialEffects())); err != nil { + return nil, err + } + } + if err := r.store.Checkpoint(ctx, id, baseEnv, baselineStep, WithCheckpointFence(r.cfg.fence)); err != nil { return nil, fmt.Errorf("durable: checkpointing start baseline for %q: %w", id, err) } @@ -570,13 +662,12 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, } + // The spawns go through absorbActors, so an actor whose state a starting actor's + // message left doesn't spawn, as for Fire: Recover, replaying that message, never + // spawns it. if actors != nil { actorFires.arm = h.absorbParentFire - actorFires.attempt(starts) - func() { - defer actorFires.driving(ctx)() - actors.Absorb(ctx, starts) - }() + h.absorbActors(ctx, nil, starts, nil) } // 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 @@ -605,7 +696,7 @@ func (r *Runner[S, E, C]) newServiceRunner(inst *state.Instance[S, E, C]) *state if r.cfg.serviceReg == nil { return nil } - return state.NewServiceRunner(inst, r.cfg.serviceReg) + return state.NewServiceRunner(inst, r.cfg.serviceReg).WithResultTransform(replayableOutcome) } // newActorSystem builds the kernel host driver for child-machine actors bound to @@ -642,6 +733,7 @@ type parentFires[S comparable] struct { 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 + exited map[string]bool // actors a parent Fire noted since the last take stopped: the activation of their state that spawned them ended } // actorLifecycle is what a step did to the actors: the ones it asked the system to @@ -739,6 +831,15 @@ func (p *parentFires[S]) note(pf state.ParentFire[S]) { } p.failed[pf.ActorID] = true } + // A parent Fire that leaves a state stops its actors (see left). + for _, eff := range pf.Result.Effects { + if e, ok := eff.(state.StopActor); ok { + if p.exited == nil { + p.exited = map[string]bool{} + } + p.exited[e.ID] = true + } + } ctx := p.ctx p.mu.Unlock() if p.arm != nil { @@ -777,10 +878,44 @@ func (p *parentFires[S]) take() []state.ParentFire[S] { p.mu.Lock() defer p.mu.Unlock() fires := p.fires - p.fires = nil + p.fires, p.exited = nil, nil return fires } +// left reports whether a parent Fire noted since the last take left the state that +// declares sp, so sp, a spawn a step's own transitions produced before that Fire, is +// for an activation of the state that has ended: the Fire stopped sp's actor. Spawning +// it would run an actor for a state that isn't active, or, if a later Fire entered the +// state again, a second time for one activation, when that Fire spawned its own. A +// dynamic spawn, which declares no state, is never left. It's safe on a nil collector. +func (p *parentFires[S]) left(sp state.SpawnActor) bool { + if p == nil || sp.State == "" { + return false + } + p.mu.Lock() + defer p.mu.Unlock() + return p.exited[sp.ID] +} + +// stoppedLater reports whether a StopActor for sp's actor follows sp in the effects a +// step absorbs after it, rest of them, then later: the activation of the state that +// spawns it ends within the step, so the actor would run for a state that isn't active +// once the step ends. A dynamic spawn, which declares no state, is never stopped this +// way: Recover doesn't spawn one either way. +func stoppedLater(sp state.SpawnActor, rest, later []state.Effect) bool { + if sp.State == "" { + return false + } + for _, effects := range [][]state.Effect{rest, later} { + for _, eff := range effects { + if stop, ok := eff.(state.StopActor); ok && stop.ID == sp.ID { + return true + } + } + } + return false +} + // parentFireErrs returns each parent Fire's error, nil ones included. func parentFireErrs[S comparable](fires []state.ParentFire[S]) []error { errs := make([]error, len(fires)) @@ -792,7 +927,9 @@ func parentFireErrs[S comparable](fires []state.ParentFire[S]) []error { // Fire drives one event through a durable instance identified by id, loading and // replaying it from the Store first, then recording the step. Handle.Fire describes -// how a state.WithEventData payload is handled, and when it's refused. It is the +// how a state.WithEventData payload is handled, and when it's refused. Loading can +// return ErrEffectDispatch before the event fires, as Recover can, or ErrNoDispatchStore +// for an effect handler with a Store that isn't a DispatchStore. It is the // stateless entry point (no Handle required); for a hot path that fires many // events in sequence, hold a Handle from Start or Recover and use Handle.Fire to // avoid reloading between steps. Calls on one id aren't serialized, and must not overlap @@ -815,7 +952,9 @@ func (r *Runner[S, E, C]) Fire(ctx context.Context, id InstanceID, event E, opts // policy makes due checkpoints. A checkpoint this step wrote for an earlier one, which // failed because ctx ended, isn't reported, since this step succeeded. If another // goroutine failed the Handle while this step was recording, Fire returns -// ErrHandleFailed saying the step was recorded; Recover sends its effects. +// ErrHandleFailed saying the step was recorded; Recover sends its effects. It applies +// the step's domain effects after the append and before any checkpoint; a failed +// dispatch fails the Handle with ErrHandleFailed. // // 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 @@ -823,10 +962,15 @@ func (r *Runner[S, E, C]) Fire(ctx context.Context, id InstanceID, event E, opts // 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. +// on the result Fire returned with that error. Only a parent Fire a context refused fails +// the step: a Fire that drove none records, even if ctx ends after the kernel applied +// it. A message to an actor, or an actor's start, that the actor refused because ctx +// ended is lost, as actor deliveries are across Recover; failing the step would have the +// retry run the actors' behaviors, and their side effects, again. 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 forwardTo on the event's transition forwards the event to the actor it names. // // 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 @@ -886,13 +1030,13 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi // arms each for the seam method that settles it next. The seams compose: a Fire // may enter a state that both invokes a service and spawns an actor and arms a // timer, and each driver must see its effects. - h.absorbDrivers(ctx, res.Effects) + h.absorbDrivers(ctx, event, 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. + // A context that ended can refuse an onError an actor the absorb spawned routes + // through the parent, or a message an actor sends the parent, so live never applied + // that Fire: record nothing, as Start and Recover do. A message to an actor refused + // because ctx ended is lost, as actor deliveries are across Recover, so the step + // records: failing it would have the retry run the actors' behaviors again. 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)) @@ -905,18 +1049,30 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi 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 - // be dispatched before any dispatch happens. - des := dispatchableEffects(step, res.Effects) - effEnvs, err := recordEffects(des) + rec := &Record{Step: h.nextStep, Event: []byte(res.Trace.EventPayload), EventData: payload.data, EventDataError: payload.errMsg, Entries: append(h.drainClock(), driven...)} + des, err := h.recordStep(ctx, rec, res.Effects) if err != nil { - return res, nil, nil, h.fail(err) + return res, nil, nil, err } - 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) + return res, rec, des, nil +} + +// recordStep makes a step durable, in write-ahead order, under the step lock. It stamps +// the step's domain effects with their deterministic ids and carries them in rec, so the +// append durably names every effect that must be dispatched before any dispatch +// happens, then appends rec and advances the next step. A step with effects is marked +// dispatching, so no checkpoint compacts it until finishStep, which the caller runs +// after releasing the step lock, has dispatched them; a step with no effects to dispatch +// may run finishStep under the lock, as DeliverToActor does. The kernel has already +// applied the step, so a failed encode or append fails the Handle; a failed checkpoint +// doesn't, because the Record is durable. This relies on the Append running inline, +// under the step lock, before the step returns: an Append deferred off this goroutine +// would acknowledge a step whose outcome isn't known, and the Handle couldn't fail. +func (h *Handle[S, E, C]) recordStep(ctx context.Context, rec *Record, effects []state.Effect) ([]dispatchableEffect, error) { + des := dispatchableEffects(rec.Step, effects) + rec.Effects = recordEffects(des) + if err := h.appendStep(ctx, rec.Step, rec); err != nil { + return nil, h.fail(err) } h.nextStep = rec.followingStep() h.out.mu.Lock() @@ -924,16 +1080,16 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi // Another goroutine's dispatch may have failed the Handle while this step held the // lock, and its caller may already be recovering. Leave this step's effects unmarked // in the journal for that Recover to send, rather than race it. - if err := h.recordedOnFailedLocked(step); err != nil { - return res, nil, nil, err + if err := h.recordedOnFailedLocked(rec.Step); err != nil { + return nil, err } if len(des) > 0 { if len(h.out.dispatching) == 0 { h.out.idle = make(chan struct{}) } - h.out.dispatching[step] = struct{}{} + h.out.dispatching[rec.Step] = struct{}{} } - return res, rec, des, nil + return des, nil } // finishStep dispatches a recorded step's domain effects, outside the step lock, then @@ -944,7 +1100,7 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi func (h *Handle[S, E, C]) finishStep(ctx context.Context, rec *Record, des []dispatchableEffect) error { var dispatchErr error if len(des) > 0 { - dispatchErr = h.dispatchGuarded(h.dispatchContext(ctx), rec.Step, des) + dispatchErr = h.dispatchEffects(h.dispatchContext(ctx), des) } h.out.mu.Lock() defer h.out.mu.Unlock() @@ -961,17 +1117,6 @@ func (h *Handle[S, E, C]) finishStep(ctx context.Context, rec *Record, des []dis return h.offerCheckpointLocked(ctx, rec) } -// dispatchGuarded dispatches des, turning a panic in the effect handler, or in the -// Store's dispatch tracking, into an ErrEffectDispatch error. -func (h *Handle[S, E, C]) dispatchGuarded(ctx context.Context, step int, des []dispatchableEffect) (err error) { - defer func() { - if p := recover(); p != nil { - err = fmt.Errorf("%w: step %d for %q: effect dispatch panicked: %v", ErrEffectDispatch, step, h.id, p) - } - }() - return h.dispatchEffects(ctx, des) -} - // Tick advances the Handle's delayed-transition scheduler: it fires every timer // whose recorded deadline is at or before the recording clock's current time, in // due order, re-firing the delayed events through the durable instance and @@ -979,36 +1124,70 @@ func (h *Handle[S, E, C]) dispatchGuarded(ctx context.Context, step int, des []d // timer loop (with a real clock) or a test calls it after advancing a fake clock. // It records one tick barrier — carrying the consumed clock readings and the // count of timers fired — so recovery re-derives the same timers at their -// recorded instants. It returns the FireResults of the timers it fired, in order. A +// recorded instants. Each fired transition's effects go to the service runner and the +// actor system too, as a Fire's do: a timer that leaves a state stops its services and +// its actors, and one that enters a state starts and spawns them. The tick journals the +// parent Fires an actor it spawned drove, and a context's ending that refuses one fails +// the Handle and records nothing, as for Fire. A message to an actor refused because +// ctx ended is lost, as for Fire. A forwardTo on a timer's transition forwards the +// timer's event, rebuilt with the Runner's event codec. If the codec can't rebuild it, +// Tick forwards nothing, records the tick and dispatches its effects as usual, and +// returns the results with the codec's error; the Handle carries on. +// 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. If ctx ends during the Tick, or a -// context derived from it (by middleware, say) refuses a timer's Fire, it fails the +// ErrHandleFailed saying the step was recorded. If ctx ends while the due timers fire, +// 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. +// reason, such as a failing guard, is recorded, and replay meets the same refusal. As +// Fire does, it dispatches the fired timers' domain effects once the tick is recorded; a +// failed dispatch fails the Handle with ErrHandleFailed, and Recover retries the effect. func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], error) { if err := h.acquire(ctx); err != nil { return nil, err } + results, rec, des, err := h.lockedTickStep(ctx) + if rec == nil { + return results, err + } + // Dispatch after releasing the step lock, as Fire does. An error that comes with a + // Record didn't stop the tick recording: a timer's event the codec couldn't rebuild + // to forward. + return results, errors.Join(err, h.finishStep(ctx, rec, des)) +} + +// lockedTickStep runs tickStep and releases the step lock however it returns. A panic +// in host code fails the Handle first, since the kernel may have fired a timer. +func (h *Handle[S, E, C]) lockedTickStep(ctx context.Context) ([]state.FireResult[S], *Record, []dispatchableEffect, error) { defer h.release() defer h.failOnPanic() + return h.tickStep(h.stepContext(ctx)) +} + +// tickStep is the part of Tick that holds the step lock: it fires the due timers and +// records the tick, naming their domain effects, before any is dispatched. It returns a +// nil Record when the tick recorded nothing. An error with a Record is the codec's for +// a timer's event it couldn't rebuild to forward (see firedEvent): the tick recorded. +// ctx is the step's marked context, as fireStep's is, so the timers' Fires and the +// services and actors their transitions start, with any parent Fire such an actor +// drives, run inside the step: one that calls back into the Handle gets +// ErrReentrantStep rather than wait on the step lock. +func (h *Handle[S, E, C]) tickStep(ctx context.Context) ([]state.FireResult[S], *Record, []dispatchableEffect, error) { if err := h.refuse(ctx); err != nil { - return nil, err + return nil, nil, nil, err } - results := h.sched.Tick(h.stepContext(ctx)) + results := h.sched.Tick(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)) + return results, nil, nil, 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: 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 @@ -1018,7 +1197,6 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro 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 @@ -1026,34 +1204,59 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro // and fired, so a checkpoint after the tick doesn't persist a fired timer. dropUnscheduled(h.timers, h.sched) } + // Hand each fired transition's effects to the service runner, in fire order, and only + // then to the actor system, in fire order, as a Fire that produced every transition's + // effects does: a timer that leaves a state stops its services and actors, and one + // that enters a state starts and spawns them. The scheduler armed their timers itself. + // An actor spawned for one timer can drive a parent Fire at once, which must see the + // services every timer started, so it stops one a later timer started rather than + // leave it in flight. Replay starts and stops the same services after the same + // mirroring, then re-fires the recorded parent Fires, so the two agree. + for i := range results { + h.absorbServices(ctx, results[i].Effects) + } + // A spawn a later timer's effects stop, the activation of its state ended within + // the tick, is skipped (see absorbActors), so each timer's absorb sees the effects of + // the timers after it. + var effects []state.Effect + for i := range results { + effects = append(effects, results[i].Effects...) + } + var forwardErrs []error + for i, end := 0, 0; i < len(results); i++ { + end += len(results[i].Effects) + event, err := h.firedEvent(results[i]) + if err != nil { + forwardErrs = append(forwardErrs, err) + } + h.absorbActors(ctx, event, results[i].Effects, effects[end:]) + } + // A context that ended during the absorb can refuse a parent Fire an actor the absorb + // spawned drove, as for Fire: record nothing. A message to an actor refused because + // ctx ended is lost, as for Fire. Every other parent Fire it drove applied after the + // tick's timers, so the tick journals them, and replay re-fires them after it. + fires := h.actorFires.take() + if refused := refusedByContext(parentFireErrs(fires)...); refused != nil { + return results, nil, nil, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, refused)) + } + driven, err := recordParentFires(fires, false) + if err != nil { + return results, nil, nil, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) + } + rec := &Record{Step: h.nextStep, Tick: true, TickSteps: len(results), Entries: append(h.drainClock(), driven...)} // A tick that read no clock and fired nothing records nothing: there is no // nondeterminism to journal and no step was produced. if len(rec.Entries) == 0 && rec.TickSteps == 0 { - return results, nil - } - if err := h.persistStep(ctx, step, &rec); err != nil { - return results, err - } - return results, nil -} - -// persistStep write-ahead appends rec for a step with no domain effects to dispatch, -// advances the next step, then offers its checkpoint. A failed append fails the -// Handle, because the kernel already applied the step; a failed checkpoint doesn't, -// because the Record is durable. This relies on the Append running inline, under the -// step lock, before the step returns: an Append deferred off this goroutine would -// acknowledge a step whose outcome isn't known, and the Handle couldn't fail. -func (h *Handle[S, E, C]) persistStep(ctx context.Context, step int, rec *Record) error { - if err := h.appendStep(ctx, step, rec); err != nil { - return h.fail(err) + return results, nil, nil, nil } - h.nextStep = rec.followingStep() - h.out.mu.Lock() - defer h.out.mu.Unlock() - if err := h.recordedOnFailedLocked(step); err != nil { - return err + des, err := h.recordStep(ctx, rec, effects) + if err != nil { + return results, nil, nil, err } - return h.offerCheckpointLocked(ctx, rec) + // A timer's event the codec couldn't rebuild forwarded nothing. The tick is + // recorded, as for a message an actor can't take, and Tick reports the error with a + // Record, so the Handle carries on. + return results, rec, des, errors.Join(forwardErrs...) } // recordedOnFailedLocked reports a step that was recorded while another goroutine failed @@ -1273,10 +1476,10 @@ type actorSetsCache[S comparable] struct { // 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. +// never settled isn't one: Recover starts it. A Handle with no service registry keeps +// the ones it recovered, so a later Recover with the registry doesn't run them again. func (h *Handle[S, E, C]) endedServices() []string { - if h.svc == nil || len(h.settled) == 0 { + if len(h.settled) == 0 { return nil } var ids []string @@ -1325,9 +1528,16 @@ func startsExcept[T state.Effect](effects []state.Effect, ids []string, id func( // 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) { +// parent a second time. It notes the running ones on the collector, so one whose spawn +// fails still counts as having started. +// +// A parent Fire a spawn drives can leave the state of an actor respawn hasn't spawned +// yet, as Start's can (see absorbActors): a new actor's message, or the onError of a +// running actor whose respawn fails. The new actors go through absorbActors, which +// skips such a spawn. The running ones respawn together, so one whose state such a Fire +// left respawns all the same; respawn then stops each whose state isn't active, as a +// Recover from the journal, replaying that Fire, never runs it. +func (h *Handle[S, E, C]) respawn(ctx context.Context, 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) { @@ -1336,9 +1546,28 @@ func respawn[S comparable, E comparable, C any](ctx context.Context, actors *sta } fresh = append(fresh, eff) } - fires.respawning(running) - actors.AbsorbRespawn(ctx, running) - actors.Absorb(ctx, fresh) + func() { + defer h.actorFires.driving(ctx)() + h.actorFires.attempt(running) + h.actorFires.respawning(running) + h.actors.AbsorbRespawn(ctx, running) + }() + h.absorbActors(ctx, nil, fresh, nil) + if len(running) == 0 { + return + } + // Every one of them was declared by an active leaf before the spawns, so one whose + // state isn't active now is one such a Fire left. Stopping one that isn't running, as + // one whose state that Fire left after it respawned, so the Fire stopped it, is a + // no-op. + var stops []state.Effect + active := declaredActors(h.inst.StartEffects()) + for _, eff := range running { + if sp := eff.(state.SpawnActor); !slices.Contains(active, sp.ID) { + stops = append(stops, state.StopActor{ID: sp.ID}) + } + } + h.absorbActors(ctx, nil, stops, nil) } // Recover reconstructs a durable instance purely from the Store: it loads the @@ -1349,7 +1578,11 @@ func respawn[S comparable, E comparable, C any](ctx context.Context, actors *sta // 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. +// doesn't fail it, as for Start: their behaviors already ran. It applies any recorded +// effect not yet marked dispatched, so it returns ErrEffectDispatch and no Handle while +// the effect handler keeps failing. With an effect handler wired, it refuses a Store +// that isn't a DispatchStore with ErrNoDispatchStore before it loads anything, whether +// or not an effect is waiting. 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) @@ -1360,6 +1593,9 @@ func Recover[S comparable, E comparable, C any](ctx context.Context, m *state.Ma // reproducing the live driver sequence (Fire+Absorb for external steps, Tick for // scheduler barriers), then continue live against the recording clock. func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S, E, C], error) { + if err := r.checkDispatchStore(id); err != nil { + return nil, err + } snapBytes, tail, err := r.store.Load(ctx, id) if err != nil { return nil, fmt.Errorf("durable: loading instance %q: %w", id, err) @@ -1449,7 +1685,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S 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)) + stepEffects, 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) } @@ -1459,12 +1695,16 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S 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 { + // Re-dispatch this step's domain effects, a Fire's, a settlement's or a tick's, + // 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. + // Replay re-derives the effects, so this doesn't depend on the Store keeping + // Record.Effects. A tick's or a settlement's Record from a version that didn't + // dispatch them, of a format before dispatchedStepsFormat, owes none: that run + // never applied them, so sending them now would apply effects it never did. + if sendsReplayedEffects(rec) { + if err := r.dispatchReplayEffects(ctx, id, rec.Step, stepEffects); err != nil { return nil, err } } @@ -1572,11 +1812,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S } 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) - }() + h.respawn(ctx, 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 @@ -1630,10 +1866,11 @@ func encodeEventData[E comparable](event E, opts []state.FireOption, maxBytes in } var payload eventPayload encoded := data + var msg string e, isErr := data.(error) if isErr { - msg, err := errorMessage(e) - if err != nil { + var err error + if msg, err = normalizedErrorMessage(e, "error payload"); err != nil { return payload, nil, fmt.Errorf("%w: %w", ErrEventDataEncoding, err) } encoded = msg @@ -1646,12 +1883,6 @@ func encodeEventData[E comparable](event E, opts []state.FireOption, maxBytes in return payload, nil, eventDataTooLarge(len(b), maxBytes) } if isErr { - // Take the message back from its JSON form, which is what a Store keeps: JSON - // replaces invalid UTF-8, so the raw message could differ from a replay's. - var msg string - if err = json.Unmarshal(b, &msg); err != nil { - return payload, nil, fmt.Errorf("%w: %w", ErrEventDataEncoding, err) - } payload.errMsg = &msg } else { payload.data = b @@ -1670,16 +1901,37 @@ func encodeEventData[E comparable](event E, opts []state.FireOption, maxBytes in return payload, append(append(live, opts...), state.WithEventData(value)), nil } -// errorMessage returns e.Error(), or an error if it panics, as a typed nil can. -func errorMessage(e error) (msg string, err error) { +// errorMessage returns e.Error(), or an error if it panics, as a typed nil can. what +// names e in that error, such as "error payload". +func errorMessage(e error, what string) (msg string, err error) { defer func() { if p := recover(); p != nil { - err = fmt.Errorf("error payload panicked: %v", p) + err = fmt.Errorf("%s panicked: %v", what, p) } }() return e.Error(), nil } +// normalizedErrorMessage returns e's message in the form a Store keeps it, so the live +// run and a replay can't differ: JSON replaces each byte of invalid UTF-8 with U+FFFD. +// It returns errorMessage's error if e's Error method panics. +func normalizedErrorMessage(e error, what string) (string, error) { + msg, err := errorMessage(e, what) + if err != nil { + return "", err + } + return validUTF8(msg), nil +} + +// validUTF8 returns s with each byte of invalid UTF-8 replaced by U+FFFD, as a round +// trip through JSON does. Converting to runes makes that replacement. +func validUTF8(s string) string { + if utf8.ValidString(s) { + return s + } + return string([]rune(s)) +} + // marshalPayload returns v's JSON form, or an error if a custom marshaler panics, so // a caller's payload can't panic out of Fire. func marshalPayload(v any) (b []byte, err error) { @@ -1786,13 +2038,16 @@ 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 +// stepCanceled reports why a step that consumed something 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. Such a step checks ctx itself because what it consumed can end on ctx +// without any Fire reporting it: a RunService's service, a DeliverToActor's delivery, +// and a Tick's due timers. Fire and Tick don't check ctx after their absorb: a message +// to an actor refused because ctx ended is lost, as actor deliveries are across +// Recover, and only a parent Fire refused by a context fails them. 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 { @@ -1803,8 +2058,8 @@ func stepCanceled(ctx context.Context, errs ...error) error { } // 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. +// fired), 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...) @@ -1833,6 +2088,33 @@ func (h *Handle[S, E, C]) failOnPanic() { } } +// firedEvent returns the event a timer's Fire fired, which the scheduler doesn't +// report, rebuilt from res's trace with the Runner's event codec, as replay rebuilds a +// recorded event, so a forwardTo on the timer's transition forwards it. It decodes only +// when there's a forward to carry it, an actor system wired and a ForwardEvent among +// res's effects, and is nil otherwise. It's nil too, so a forwardTo forwards nothing, +// for an event with no JSON form, and for one the codec can't decode, with the codec's +// error. Tick records the tick and reports that error, the Handle carrying on: the +// timers applied, so failing it would have Recover fire them, and run the actors' +// behaviors, again, only to meet the same error. That's as a step does when an actor +// can't take a message it sends. +func (h *Handle[S, E, C]) firedEvent(res state.FireResult[S]) (any, error) { + if h.actors == nil || len(res.Trace.EventPayload) == 0 || !slices.ContainsFunc(res.Effects, isForward) { + return nil, nil + } + event, err := h.runner.cfg.eventCodec.Decode(res.Trace.EventPayload) + if err != nil { + return nil, fmt.Errorf("durable: ticking %q: decoding a timer's event to forward it: %w", h.id, err) + } + return event, nil +} + +// isForward reports whether eff is a ForwardEvent. +func isForward(eff state.Effect) bool { + _, ok := eff.(state.ForwardEvent) + return ok +} + // resultErrs returns each result's error, nil ones included. func resultErrs[S comparable](results []state.FireResult[S]) []error { errs := make([]error, len(results)) @@ -1845,7 +2127,9 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { // 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. +// re-dispatch on top. A nil mirror tracks no deadlines. It returns the effects of the +// step's own work, a plain event's, a settlement's or a tick's timers', so Recover can +// re-dispatch their domain effects; nil for any other Record. // // - Parent Fires a Start's or Recover's spawns drove, recorded with the next step, // re-fire first, before the step's own work. @@ -1861,6 +2145,9 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { // 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. +// Each fired transition starts or stops its services, as the live Tick did, for a +// Record of tickDriversFormat or later, and its recorded parent Fires re-fire after +// the tick. // - 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. @@ -1873,48 +2160,61 @@ func replayRecord[S comparable, E comparable, C any]( rec *Record, mirror *armMirror, actorArms bool, -) (*state.FireResult[S], error) { - var fired *state.FireResult[S] +) ([]state.Effect, error) { + var stepEffects []state.Effect before, rest, err := splitActorEntries(rec) if err != nil { - return fired, fmt.Errorf("at step %d: %w", rec.Step, err) + return stepEffects, 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 + return stepEffects, 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) + return stepEffects, 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) + return stepEffects, 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) + return stepEffects, fmt.Errorf("replaying step %d: %w", rec.Step, res.Err) } replayArm(ctx, sched, svc, res.Effects, mirror) - fired = &res + stepEffects = res.Effects 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) + return stepEffects, 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) + stepEffects = append(stepEffects, effects...) } case rec.Tick: - mirrorTick(mirror, sched, sched.Tick(ctx)) + ticked := sched.Tick(ctx) + mirrorTick(mirror, sched, ticked) + for i := range ticked { + if rec.Format >= tickDriversFormat { + // The live Tick handed the transition's effects to the service runner, as + // replayArm does for a Fire's; its timers the scheduler armed itself. + replayRunners(ctx, svc, ticked[i].Effects, mirror) + } else { + // An older version's Tick left services alone. + mirror.forget(ticked[i].Effects) + } + stepEffects = append(stepEffects, ticked[i].Effects...) + } } // 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) + return stepEffects, replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror, actorArms) } // replayActors re-fires recorded parent transitions, in order. When actorArms, the @@ -1962,23 +2262,44 @@ 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. +// sendsReplayedEffects reports whether Recover sends the domain effects replaying rec +// produces: every version dispatched a Fire's, and a tick's or a service settle's since +// dispatchedStepsFormat. It reads the Record's format, not its effect envelopes, so a +// Store that doesn't keep Record.Effects loses no effect. +func sendsReplayedEffects(rec *Record) bool { + return len(rec.Event) > 0 || rec.Format >= dispatchedStepsFormat +} + +// journalFormat is the format this version writes in every Record and checkpoint. It is +// dispatchedStepsFormat. actorArmsFormat is the first format that arms the timers and +// services an actor-driven parent Fire's state declares. dispatchedStepsFormat is the +// first that dispatches a tick's and a service settle's domain effects, so Recover sends +// them. tickDriversFormat is the first whose Tick hands its timer transitions' effects +// to the service runner and the actor system, so replay starts and stops their services +// as it did. const ( - actorArmsFormat = 1 - journalFormat = actorArmsFormat + actorArmsFormat = 1 + dispatchedStepsFormat = 2 + tickDriversFormat = 2 + journalFormat = dispatchedStepsFormat ) // 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) } + replayRunners(ctx, svc, effects, mirror) +} + +// replayRunners starts or stops the services a replayed transition's effects declare, +// and forgets the settles of each, as the live absorbRunners did. Replay runs no actor: +// Recover spawns the actors of the states it ends in. svc may be nil. +func replayRunners[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], effects []state.Effect, mirror *armMirror) { + mirror.forget(effects) if svc != nil { svc.Absorb(ctx, effects) } @@ -2026,14 +2347,14 @@ func (m *armMirror) arm(effects []state.Effect) { // 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. +// fired: the ones sched no longer holds. The caller then hands the transitions' effects +// to the service runner, which forgets their settles, as the live Tick does. 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) } diff --git a/durable/runner_options.go b/durable/runner_options.go index b653c5e1..52b2687b 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -127,10 +127,17 @@ func WithActorPalette[S comparable, E comparable, C any](palette map[string]stat } // WithEffectHandler binds the seam the Runner calls to apply each emitted domain -// effect — an email, a charge, a published message: any at-most-once side effect -// a transition emits as a domain Effect value. A durable effect is applied +// effect — an email, a charge, a published message: any side effect +// a transition emits as a domain Effect value. Effects from a parent transition an actor +// drives aren't dispatched. The handler needs a Store that is a DispatchStore, as +// MemStore and FileStore are: with any other Store, Start, Recover and the stateless +// Runner.Fire refuse the configuration with ErrNoDispatchStore before they write to the +// Store or call the handler. A +// durable effect from a step is applied // exactly once over the whole lifetime of an instance (the live run plus any -// number of recoveries), deduped by a deterministic EffectID: the Runner stamps +// number of recoveries), except that it can apply twice after a crash or failed mark +// once the handler returned, or during a handoff, so keep the handler idempotent on +// EffectInstance plus the id. It is deduped by a deterministic EffectID: the Runner stamps // each emitted effect, write-ahead persists the step Record carrying those ids, // then invokes the handler for every id not already marked dispatched, marking // each as it succeeds. A handler error or panic fails the Handle with ErrHandleFailed, @@ -187,7 +194,8 @@ func WithEventDataDecoder[S comparable, E comparable, C any](d EventDataDecoder[ // Checkpoint, so a Handle that has lost the instance to a newer owner gets ErrFenced // instead of committing. Pass the token the host's lease issued; a retry by the same // owner keeps the same token. A non-positive token is the same as no token, which a -// fenced instance refuses. MarkDispatched is not fenced. +// fenced instance refuses. MarkDispatched is not fenced, so during a handoff an effect +// handler can run concurrently for one effect id. // // The token applies to every instance the Runner drives, so a host with a token per // instance passes it to Recover, or builds a Runner per instance. No fence token is written diff --git a/durable/service.go b/durable/service.go index 66dde8cd..8a19ecb5 100644 --- a/durable/service.go +++ b/durable/service.go @@ -29,8 +29,8 @@ import ( // The Runner wraps the kernel's reusable host driver, state.ServiceRunner, which // turns StartService / StopService effects into real ServiceFn executions and // re-fires each result through the invocation's onDone / onError event. On the live -// path RunService delegates to ServiceRunner.Run (resolve + run + settle), reads -// the raw outcome the service produced, and journals it as a JournalServiceResult +// path RunService delegates to ServiceRunner.Tick (resolve + run + settle), reads +// the outcome in its JSON-decoded form, and journals it as a JournalServiceResult // correlated by the invocation id. On recovery the recorded outcomes are replayed // in order through ServiceRunner.SettleDone / SettleError — the same settle methods // the live run drove — so the kernel re-fires the identical onDone / onError event @@ -55,7 +55,7 @@ type serviceResultPayload struct { // Result is the JSON-encoded successful return of the ServiceFn, present for a // SettleDone outcome. It is decoded to a Go value and re-fired through onDone so // the transition's Assign reads it from AssignCtx.Event exactly as on the live - // run. + // run, which settles with the same decoded form (see replayableOutcome). Result json.RawMessage `json:"result,omitempty"` // Error is the failure message for a SettleError outcome. It is reconstructed // into an error and re-fired through onError so the transition's Assign reads it @@ -80,9 +80,14 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { // 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 -// registry supplied with WithServiceRegistry; its raw result or error is journaled +// registry supplied with WithServiceRegistry; its result or error is journaled // as a JournalServiceResult correlated by id so recovery replays it without -// re-invoking the service. +// re-invoking the service. The outcome reaches the machine JSON-decoded, live as on +// replay, and the journal holds that form: a struct is a map, an integer a float64 that +// loses precision above 2^53. An error is message-only: an error with the same message, +// which errors.Is and errors.As no longer match, live or on replay. So onError's Assign +// and the ServiceRunner's LastError see a plain error even for an unbound service's +// *state.UnboundRefError. // // 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). It returns @@ -90,36 +95,68 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { // 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 result whose JSON form won't decode, such as a number beyond float64, 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 +// KindedEffect the settle emits whose payload won't marshal doesn't fail it: it is +// recorded by id and kind, as recordEffects says, and dispatches as any effect does. // 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. +// the result is recorded. A failed effect dispatch also returns ErrHandleFailed, but the +// result is recorded: Recover retries the effect and the service doesn't run again. +// +// A result whose JSON form won't decode, or that has no JSON form, such as a chan, is +// refused only after its settle applied: the onDone Assign runs once on an internal +// stand-in for the result (for one with no JSON form, the raw result), and the state +// onDone enters starts its actors and services. Only then does RunService return +// ErrHandleFailed, recording nothing, and after Recover the service runs again, its +// onDone Assign with it. An Assign that asserts the payload's type unchecked panics on +// the stand-in, which refuses the settle's Fire, and RunService still returns +// ErrHandleFailed. So keep a service's result JSON round-trippable, and have an onDone +// Assign check the payload's type rather than assume it. 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 } + res, ran, rec, des, err := h.lockedServiceStep(ctx, id) + if err != nil || rec == nil { + return res, ran, err + } + // Dispatch after releasing the step lock, as Fire does. + return res, true, h.finishStep(ctx, rec, des) +} + +// lockedServiceStep runs serviceStep and releases the step lock however it returns. A +// panic in host code fails the Handle first, since the settle may have applied. +func (h *Handle[S, E, C]) lockedServiceStep(ctx context.Context, id string) (state.FireResult[S], bool, *Record, []dispatchableEffect, error) { defer h.release() defer h.failOnPanic() + return h.serviceStep(ctx, id) +} + +// serviceStep is the part of RunService that holds the step lock: it runs and settles +// the service and records the step, naming its domain effects, before any is +// dispatched. It returns a nil Record when nothing was recorded. +func (h *Handle[S, E, C]) serviceStep(ctx context.Context, id string) (state.FireResult[S], bool, *Record, []dispatchableEffect, error) { if err := h.refuse(ctx); err != nil { - return state.FireResult[S]{}, false, err + return state.FireResult[S]{}, false, nil, nil, err } if h.svc == nil { - return state.FireResult[S]{}, false, fmt.Errorf("durable: no service registry wired for %q (supply WithServiceRegistry)", h.id) + return state.FireResult[S]{}, false, nil, nil, fmt.Errorf("durable: no service registry wired for %q (supply WithServiceRegistry)", h.id) } if !h.svc.HasPending(id) { - return state.FireResult[S]{}, false, nil + return state.FireResult[S]{}, false, nil, nil, nil } results := h.svc.Tick(h.stepContext(ctx), id) if len(results) == 0 { - return state.FireResult[S]{}, false, nil + return state.FireResult[S]{}, false, nil, nil, nil } res := results[0] // The service settled: unless the settle's own Fire leaves or re-enters the state @@ -127,24 +164,27 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire 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(h.stepContext(ctx), res.Effects) + // that arms a timer, starts another service, or spawns an actor. The ServiceRunner + // already started and stopped the services those effects name as it settled, so + // absorb them into the other drivers only, so the next seam method finds them armed + // — the service seam composes with the timer and actor seams in one instance. + h.absorbSettle(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. + // Recover re-arms it. This step rechecks ctx whatever its absorb handed the actor + // system, unlike Fire and Tick, which fail only on a parent Fire a context refused: + // the service itself ran under ctx, so its outcome can be one ctx's ending caused. 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)) + return res, true, nil, nil, 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 { - return res, true, h.fail(fmt.Errorf("durable: recording service %q result for %q: %w", id, h.id, err)) + return res, true, nil, nil, h.fail(fmt.Errorf("durable: recording service %q result for %q: %w", id, h.id, err)) } if h.svcBuf != nil { *h.svcBuf = append(*h.svcBuf, entry) @@ -155,17 +195,17 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire // 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)) + return res, true, nil, nil, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) } - step := h.nextStep // 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 + rec := &Record{Step: h.nextStep, Entries: append(append(h.drainClock(), h.drainServices()...), driven...)} + des, err := h.recordStep(ctx, rec, res.Effects) + if err != nil { + return res, true, nil, nil, err } - return res, true, nil + return res, true, rec, des, nil } // noteSettled records that the service id settled in its state's current activation. @@ -176,6 +216,37 @@ func (h *Handle[S, E, C]) noteSettled(id string) { h.settled[id] = true } +// replayableOutcome gives a service's outcome the form a replay supplies, so the live +// settle and a replay can't differ: a result in its JSON-decoded form, and an error as +// an error with its message as a Store keeps it (see normalizedErrorMessage). An Error +// method that panics settles with a message saying so, normalized the same way. A +// result with no JSON form is left as it is, and one whose JSON form won't decode is +// marked undecodableResult; recording either fails the Handle, so the step records +// nothing and a recovered Handle runs the service again. +func replayableOutcome(result any, err error) (any, error) { + if err != nil { + msg, perr := normalizedErrorMessage(err, "service error") + if perr != nil { + msg = validUTF8(perr.Error()) + } + return nil, errors.New(msg) + } + b, jerr := marshalPayload(result) + if jerr != nil { + return result, nil + } + var decoded any + if jerr = json.Unmarshal(b, &decoded); jerr != nil { + return undecodableResult{err: jerr}, nil + } + return decoded, nil +} + +// undecodableResult stands in for a service result whose JSON form won't decode, such +// as a number beyond float64, so recordServiceOutcome refuses it: a replay couldn't +// decode the journaled form, and every Recover would fail. +type undecodableResult struct{ err error } + // 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 @@ -186,7 +257,10 @@ func recordServiceOutcome(id string, lastResult func() (any, bool), lastErr erro msg := lastErr.Error() sp.Error = &msg } else if result, ok := lastResult(); ok { - raw, err := json.Marshal(result) + if u, bad := result.(undecodableResult); bad { + return state.JournalEntry{}, fmt.Errorf("service result won't decode from its JSON form: %w", u.err) + } + raw, err := marshalPayload(result) if err != nil { return state.JournalEntry{}, fmt.Errorf("marshaling service result: %w", err) } diff --git a/durable/service_error_message_test.go b/durable/service_error_message_test.go new file mode 100644 index 00000000..046c1d80 --- /dev/null +++ b/durable/service_error_message_test.go @@ -0,0 +1,58 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestRunService_AnUnboundServiceErrorIsMessageOnly pins a documented limit: errors are +// message-only, so onError's Assign sees a plain error with the message of an unbound +// service's *state.UnboundRefError, which errors.As doesn't match, live or on replay. +func TestRunService_AnUnboundServiceErrorIsMessageOnly(t *testing.T) { + ctx := context.Background() + var seen []any + m := state.ForgeFor[svcCtx]("unbound"). + Service("fetch", func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return nil, nil }). + Reducer("noteFail", func(in state.AssignCtx[svcCtx]) svcCtx { + seen = append(seen, in.Event) + return in.Entity + }). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready").Final(). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready"). + Transition("loading").On("fail").GoTo("failed").Assign("noteFail"). + Quench() + store := durable.NewMemStore() + // The registry binds no "fetch", so the service settles as unbound. + opt := durable.WithServiceRegistry[string, string, svcCtx](state.NewRegistry[svcCtx]()) + h, err := durable.NewRunner(m, store, opt).Start(ctx, "unb-1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, _, err = h.RunService(ctx, state.InvokeID("unbound", "loading", 0)); err != nil { + t.Fatalf("RunService: %v", err) + } + if _, err = durable.Recover(ctx, m, store, "unb-1", opt); err != nil { + t.Fatalf("Recover: %v", err) + } + if len(seen) != 2 { + t.Fatalf("onError's Assign ran %d times (%v), want 2: live and on replay", len(seen), seen) + } + want := (&state.UnboundRefError{Kind: "service", Name: "fetch"}).Error() + for i, when := range []string{"live", "on replay"} { + err, ok := seen[i].(error) + if !ok || err.Error() != want { + t.Fatalf("%s, onError's Assign saw %T %v, want an error saying %q", when, seen[i], seen[i], want) + } + var unbound *state.UnboundRefError + if errors.As(err, &unbound) { + t.Fatalf("%s, errors.As matched an *UnboundRefError, though errors are message-only", when) + } + } +} diff --git a/durable/service_outcome_test.go b/durable/service_outcome_test.go new file mode 100644 index 00000000..b6b205e6 --- /dev/null +++ b/durable/service_outcome_test.go @@ -0,0 +1,100 @@ +package durable_test + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// outcomeMachine invokes fn on entering "loading" and records what the onDone or +// onError Assign sees in *seen, live and on replay. +func outcomeMachine(fn state.ServiceFn[svcCtx], seen *[]string) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("outcome"). + Service("fetch", fn). + Reducer("noteDone", func(in state.AssignCtx[svcCtx]) svcCtx { + *seen = append(*seen, "done") + return in.Entity + }). + Reducer("noteError", func(in state.AssignCtx[svcCtx]) svcCtx { + if e, ok := in.Event.(error); ok { + *seen = append(*seen, e.Error()) + } + return in.Entity + }). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready").Final(). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready").Assign("noteDone"). + Transition("loading").On("fail").GoTo("failed").Assign("noteError"). + Quench() +} + +// TestRunService_ResultThatEncodesButWontDecode_FailsTheStep proves a result whose +// JSON form a replay can't decode, such as a number beyond float64, fails RunService +// with ErrHandleFailed and records nothing, as a result that won't encode does, so the +// instance stays recoverable with the service in flight again. +func TestRunService_ResultThatEncodesButWontDecode_FailsTheStep(t *testing.T) { + ctx := context.Background() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return json.RawMessage("1e400"), nil } + var seen []string + m := outcomeMachine(fn, &seen) + st := durable.NewMemStore() + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + id := state.InvokeID("outcome", "loading", 0) + if _, _, err = h.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService: %v, want ErrHandleFailed", err) + } + if _, recs, lerr := st.Load(ctx, "i1"); lerr != nil || len(recs) != 0 { + t.Fatalf("journal holds %d Records (err %v), want none", len(recs), lerr) + } + recovered, err := durable.Recover(ctx, m, st, "i1", opts...) + if err != nil { + t.Fatalf("Recover: %v, want the instance recoverable", err) + } + if got := recovered.Instance().Current(); got != "loading" { + t.Fatalf("recovered in %q, want loading with the service in flight again", got) + } +} + +// panickyError is a service error whose Error method panics with a message holding +// invalid UTF-8. +type panickyError struct{} + +func (panickyError) Error() string { panic("bad \xff byte") } + +// TestRunService_PanickingErrorMessage_LiveMatchesReplay proves an error whose Error +// method panics settles onError with the same message live and on replay, though the +// panic's text holds invalid UTF-8, and that the message doesn't call it an error +// payload. +func TestRunService_PanickingErrorMessage_LiveMatchesReplay(t *testing.T) { + ctx := context.Background() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return nil, panickyError{} } + var seen []string + m := outcomeMachine(fn, &seen) + st := durable.NewMemStore() + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + mustRunService(t, h, state.InvokeID("outcome", "loading", 0)) + if _, err = durable.Recover(ctx, m, st, "i1", opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + if len(seen) != 2 || seen[0] != seen[1] { + t.Fatalf("live and replay saw %q, want the same message", seen) + } + if strings.Contains(seen[0], "error payload") || !strings.Contains(seen[0], "panicked") { + t.Fatalf("onError saw %q, want a message saying the service error panicked", seen[0]) + } +} diff --git a/durable/service_test.go b/durable/service_test.go index 4d29a5d8..60f01872 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -472,6 +472,25 @@ func TestService_Determinism(t *testing.T) { } } +// fetchThenWaitMachine routes its service result into a state that arms a timer, +// emitting a host effect on the way, so both originate in RunService. +func fetchThenWaitMachine(fn state.ServiceFn[svcCtx]) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("fetchThenWait"). + Service("fetch", fn). + Action("notify", func(state.ActionCtx[svcCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("waiting"). + State("done").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("loading"). + Transition("loading").On("ok").GoTo("waiting").Do("notify"). + Transition("waiting").After(5 * time.Second).On("elapsed").GoTo("done"). + Quench() +} + // 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. @@ -993,3 +1012,39 @@ func TestRecover_StartsAServiceThatNeverSettled(t *testing.T) { } } } + +// TestRunService_AssignSeesTheDecodedResult proves a typed result reaches Assign in the +// form a replay supplies, so the two can't differ. +func TestRunService_AssignSeesTheDecodedResult(t *testing.T) { + type user struct{ Email string } + ctx := context.Background() + var seen []any + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return user{Email: "a@b.c"}, nil } + m := state.ForgeFor[svcCtx]("decoded"). + Service("fetch", fn). + Reducer("note", func(in state.AssignCtx[svcCtx]) svcCtx { + seen = append(seen, in.Event) + return in.Entity + }). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready").Final(). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready").Assign("note"). + Transition("loading").On("fail").GoTo("failed"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("d-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("decoded", "loading", 0)) + if _, err = durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + if len(seen) != 2 || fmt.Sprintf("%T:%v", seen[0], seen[0]) != fmt.Sprintf("%T:%v", seen[1], seen[1]) { + t.Fatalf("live and replay saw %#v", seen) + } +} diff --git a/durable/service_undecodable_settle_test.go b/durable/service_undecodable_settle_test.go new file mode 100644 index 00000000..fb5b3b19 --- /dev/null +++ b/durable/service_undecodable_settle_test.go @@ -0,0 +1,177 @@ +package durable_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// outOfRangeResult is a service result whose MarshalJSON emits a number beyond +// float64, so its JSON form encodes but won't decode. +type outOfRangeResult struct{} + +func (outOfRangeResult) MarshalJSON() ([]byte, error) { return []byte("1e400"), nil } + +// undecodableProbe counts what a settle with a result that won't decode drives: the +// onDone and onError Assigns, with the type of the event each saw, the actor the +// onDone state spawns, and the domain effects dispatched. +type undecodableProbe struct { + doneAssigns, errorAssigns int + doneEventType string + errorMessage string + spawns int + dispatched int +} + +// undecodableMachine invokes fetch in loading. Its onDone transition runs an Assign, +// emits a notify effect, and enters ready, which spawns child; its onError runs an +// Assign and enters failed. With assertString, the onDone Assign asserts its event is +// a string unchecked, as a reducer that trusts its service's result type does. +func undecodableMachine(fn state.ServiceFn[svcCtx], p *undecodableProbe, assertString bool) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("undecodable"). + Service("fetch", fn). + Actor("child"). + Action("notify", func(state.ActionCtx[svcCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + Reducer("noteDone", func(in state.AssignCtx[svcCtx]) svcCtx { + p.doneAssigns++ + p.doneEventType = fmt.Sprintf("%T", in.Event) + c := in.Entity + if assertString { + c.Notes = append(c.Notes, in.Event.(string)) + } + return c + }). + Reducer("noteError", func(in state.AssignCtx[svcCtx]) svcCtx { + p.errorAssigns++ + if e, ok := in.Event.(error); ok { + p.errorMessage = e.Error() + } + return in.Entity + }). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready").InvokeActor("child"). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready").Assign("noteDone").Do("notify"). + Transition("loading").On("fail").GoTo("failed").Assign("noteError"). + Quench() +} + +func undecodableOptions(fn state.ServiceFn[svcCtx], p *undecodableProbe) []durable.Option[string, string, svcCtx] { + return []durable.Option[string, string, svcCtx]{ + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + durable.WithActorPalette[string, string, svcCtx](map[string]state.ActorBehavior{ + "child": func(map[string]any) (state.ActorInstance, error) { + p.spawns++ + return &reentryGreeter{sent: true}, nil + }, + }), + durable.WithEffectHandler[string, string, svcCtx](func(context.Context, string, state.Effect) error { + p.dispatched++ + return nil + }), + } +} + +// TestRunService_UndecodableResult_SettlesOnDoneBeforeFailing pins what a ServiceFn +// result whose JSON form won't decode does today, and one with no JSON form at all, +// which takes the same path on the raw result. The live settle runs the onDone +// transition on a stand-in for the result: its Assign runs once and sees that +// stand-in, an unexported durable type, and the state it enters spawns its actor. +// Only then does recording refuse the result, so RunService fails the Handle with +// ErrHandleFailed, records nothing and dispatches nothing. The onError Assign never +// runs. A recovered Handle has the service in flight again and doesn't spawn the +// actor, and running the service again fails the same way. A reducer that asserts +// its event's type unchecked panics on the stand-in; the kernel turns that panic into +// the settle's Fire error, so the Fire doesn't apply, nothing spawns, and RunService +// still returns ErrHandleFailed rather than panicking. +func TestRunService_UndecodableResult_SettlesOnDoneBeforeFailing(t *testing.T) { + ctx := context.Background() + results := map[string]struct { + result any + seenType string + }{ + "json.Number": {json.Number("1e400"), "durable.undecodableResult"}, + "custom MarshalJSON": {outOfRangeResult{}, "durable.undecodableResult"}, + "json.RawMessage": {json.RawMessage("1e400"), "durable.undecodableResult"}, + // A result with no JSON form at all takes the same path, on the raw result. + "won't encode": {make(chan int), "chan int"}, + } + id := state.InvokeID("undecodable", "loading", 0) + for name, tc := range results { + t.Run(name, func(t *testing.T) { + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return tc.result, nil } + p := &undecodableProbe{} + m := undecodableMachine(fn, p, false) + st := durable.NewMemStore() + opts := undecodableOptions(fn, p) + h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, _, err = h.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService = %v, want ErrHandleFailed", err) + } + if p.doneAssigns != 1 || p.doneEventType != tc.seenType || p.errorAssigns != 0 { + t.Fatalf("onDone Assign ran %d times on %s, onError Assign %d times; want onDone once on %s, onError never", + p.doneAssigns, p.doneEventType, p.errorAssigns, tc.seenType) + } + if p.spawns != 1 || p.dispatched != 0 { + t.Fatalf("child spawned %d times, %d effects dispatched; want the onDone state's actor spawned once and nothing dispatched", p.spawns, p.dispatched) + } + if _, recs, lerr := st.Load(ctx, "i1"); lerr != nil || len(recs) != 0 { + t.Fatalf("journal holds %d Records (err %v), want none", len(recs), lerr) + } + recovered, err := durable.Recover(ctx, m, st, "i1", opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "loading" || p.spawns != 1 { + t.Fatalf("recovered in %q, child spawned %d times; want loading, with no new spawn", got, p.spawns) + } + if _, _, err = recovered.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService after Recover = %v, want ErrHandleFailed again", err) + } + if p.doneAssigns != 2 || p.spawns != 2 { + t.Fatalf("after the retry: onDone Assign ran %d times, child spawned %d; want 2 and 2", p.doneAssigns, p.spawns) + } + }) + } + t.Run("unchecked assertion refuses the Fire", func(t *testing.T) { + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return json.Number("1e400"), nil } + p := &undecodableProbe{} + m := undecodableMachine(fn, p, true) + st := durable.NewMemStore() + opts := undecodableOptions(fn, p) + h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + var panicked any + var res state.FireResult[string] + func() { + defer func() { panicked = recover() }() + res, _, err = h.RunService(ctx, id) + }() + if panicked != nil || !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService panicked %v, returned %v; want ErrHandleFailed and no panic", panicked, err) + } + if res.Err == nil || p.doneAssigns != 1 || p.spawns != 0 || p.dispatched != 0 { + t.Fatalf("settle's Fire error %v, onDone Assign ran %d times, child spawned %d, %d dispatched; want the Fire refused for the panic after one Assign, and no spawn or dispatch", + res.Err, p.doneAssigns, p.spawns, p.dispatched) + } + if got := h.Instance().Current(); got != "loading" { + t.Fatalf("live instance in %q, want loading: the refused Fire didn't apply", got) + } + if _, recs, lerr := st.Load(ctx, "i1"); lerr != nil || len(recs) != 0 { + t.Fatalf("journal holds %d Records (err %v), want none", len(recs), lerr) + } + }) +} diff --git a/durable/settle_absorb_internal_test.go b/durable/settle_absorb_internal_test.go new file mode 100644 index 00000000..272d2c34 --- /dev/null +++ b/durable/settle_absorb_internal_test.go @@ -0,0 +1,182 @@ +package durable + +import ( + "context" + "fmt" + "reflect" + "testing" + "time" + + "github.com/stablekernel/crucible/state" +) + +// These tests answer a review finding on serviceStep's absorb: the ServiceRunner's +// settle absorbs the follow-on effects of its own Fire, so a state its onDone enters +// starts its services, and serviceStep then handed the same effects to the runner +// again, arming each of those services a second time. Replay arms them once: it +// re-settles through the runner and arms only the timers after (replayArm with a nil +// runner). serviceStep must leave the services to the settle, as replay does, while it +// still forgets the settled services and arms the timers and actors. + +type absorbCtx struct { + Notes []string `json:"notes"` +} + +// absorbMachine invokes svcA in first; its onDone enters second, which invokes svcB and +// arms a timer, so the settle's follow-on effects start a service and schedule a timer. +func absorbMachine(svcA, svcB state.ServiceFn[absorbCtx]) *state.Machine[string, string, absorbCtx] { + return state.ForgeFor[absorbCtx]("absorb"). + Service("svcA", svcA). + Service("svcB", svcB). + Reducer("note", func(in state.AssignCtx[absorbCtx]) absorbCtx { + c := in.Entity + if r, ok := in.Event.(string); ok { + c.Notes = append(c.Notes, r) + } + return c + }). + State("first").Invoke("svcA", state.WithInvokeOnDone("aDone"), state.WithInvokeOnError("aFail")). + State("second").Invoke("svcB", state.WithInvokeOnDone("bDone"), state.WithInvokeOnError("bFail")). + State("done").Final(). + State("failed").Final(). + State("late").Final(). + Initial("first"). + Transition("first").On("aDone").GoTo("second").Assign("note"). + Transition("first").On("aFail").GoTo("failed"). + Transition("second").On("bDone").GoTo("done").Assign("note"). + Transition("second").On("bFail").GoTo("failed"). + Transition("second").After(time.Hour).On("late").GoTo("late"). + Quench() +} + +// TestRunService_SettleArmsItsFollowOnServiceOnce: svcA's onDone enters a state that +// invokes svcB. Live, the settle arms svcB once, as the replay of the journal does, so +// the live runner and a recovered one have armed the same activations; a checkpoint +// taken after the settle restores svcB once. svcB's ServiceFn runs exactly once, live +// and on each recovered Handle, and each ends where the live run did, with the +// settle's timer armed. +func TestRunService_SettleArmsItsFollowOnServiceOnce(t *testing.T) { + aID := state.InvokeID("absorb", "first", 0) + bID := state.InvokeID("absorb", "second", 0) + for _, mode := range []string{"live", "journal", "checkpoint"} { + t.Run(mode, func(t *testing.T) { + ctx := context.Background() + var aCalls, bCalls int + svcA := func(context.Context, state.ServiceCtx[absorbCtx]) (any, error) { + aCalls++ + return fmt.Sprintf("a-%d", aCalls), nil + } + svcB := func(context.Context, state.ServiceCtx[absorbCtx]) (any, error) { + bCalls++ + return fmt.Sprintf("b-%d", bCalls), nil + } + m := absorbMachine(svcA, svcB) + opts := []Option[string, string, absorbCtx]{ + WithServiceRegistry[string, string, absorbCtx](state.NewRegistry[absorbCtx]().Service("svcA", svcA).Service("svcB", svcB)), + WithRunnerClock[string, string, absorbCtx](state.NewFakeClock(time.Unix(1_700_000_000, 0))), + } + if mode == "checkpoint" { + opts = append(opts, WithCheckpointEvery[string, string, absorbCtx](1)) + } + store := NewMemStore() + h, err := NewRunner(m, store, opts...).Start(ctx, "a1", absorbCtx{}, state.WithInitialState("first")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if ok, rerr := runOnce(ctx, h, aID); rerr != nil || !ok { + t.Fatalf("RunService(svcA) = %v, %v", ok, rerr) + } + if len(h.timers) != 1 { + t.Errorf("live: the timer table is %v, want second's timer armed", h.timers) + } + + run := h + switch mode { + case "journal": + if run, err = Recover(ctx, m, store, "a1", opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + case "checkpoint": + snap, tail, lerr := store.Load(ctx, "a1") + if lerr != nil || len(tail) != 0 || snap == nil { + t.Fatalf("Load: %d tail Records (err %v), want the settle in a checkpoint", len(tail), lerr) + } + if run, err = Recover(ctx, m, store, "a1", opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + } + if !run.svc.HasPending(bID) || run.svc.Pending() != 1 { + t.Fatalf("%s: svcB in flight = %v with %d pending, want svcB alone", mode, run.svc.HasPending(bID), run.svc.Pending()) + } + if len(run.timers) != 1 { + t.Errorf("%s: the timer table is %v, want second's timer armed", mode, run.timers) + } + if ok, rerr := runOnce(ctx, run, bID); rerr != nil || !ok { + t.Fatalf("%s: RunService(svcB) = %v, %v", mode, ok, rerr) + } + if aCalls != 1 || bCalls != 1 { + t.Errorf("%s: svcA ran %d times and svcB %d, want once each", mode, aCalls, bCalls) + } + if got := run.inst.Current(); got != "done" { + t.Errorf("%s: ended in %q, want done", mode, got) + } + if got, want := run.inst.Snapshot().Context.Notes, []string{"a-1", "b-1"}; !reflect.DeepEqual(got, want) { + t.Errorf("%s: notes %v, want %v", mode, got, want) + } + }) + } +} + +// TestRunService_SettleThatReentersItsStateForgetsTheSettle: svcA's onDone leaves and +// re-enters the state that invokes it, so the settle starts a new activation of svcA. +// With the services left to the settle's own absorb, serviceStep must still forget that +// svcA settled, or the checkpoint the step makes records the new activation as settled +// and a Handle recovered from it doesn't run it. +func TestRunService_SettleThatReentersItsStateForgetsTheSettle(t *testing.T) { + ctx := context.Background() + calls := 0 + svcA := func(context.Context, state.ServiceCtx[absorbCtx]) (any, error) { + calls++ + return fmt.Sprintf("a-%d", calls), nil + } + m := state.ForgeFor[absorbCtx]("again"). + Service("svcA", svcA). + State("first").Invoke("svcA", state.WithInvokeOnDone("aDone"), state.WithInvokeOnError("aFail")). + State("failed").Final(). + Initial("first"). + Transition("first").On("aDone").GoTo("first").Reenter(). + Transition("first").On("aFail").GoTo("failed"). + Quench() + opts := []Option[string, string, absorbCtx]{ + WithServiceRegistry[string, string, absorbCtx](state.NewRegistry[absorbCtx]().Service("svcA", svcA)), + WithCheckpointEvery[string, string, absorbCtx](1), + } + store := NewMemStore() + h, err := NewRunner(m, store, opts...).Start(ctx, "r1", absorbCtx{}, state.WithInitialState("first")) + if err != nil { + t.Fatalf("Start: %v", err) + } + aID := state.InvokeID("again", "first", 0) + if ok, rerr := runOnce(ctx, h, aID); rerr != nil || !ok { + t.Fatalf("RunService = %v, %v", ok, rerr) + } + if !h.svc.HasPending(aID) || h.settled[aID] { + t.Fatalf("live: svcA in flight = %v, settled = %v; want a new activation in flight, not settled", h.svc.HasPending(aID), h.settled[aID]) + } + rh, err := Recover(ctx, m, store, "r1", opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if !rh.svc.HasPending(aID) { + t.Fatal("recovered from the checkpoint: svcA isn't in flight, want its new activation") + } + if ok, rerr := runOnce(ctx, rh, aID); rerr != nil || !ok || calls != 2 { + t.Fatalf("recovered RunService = %v, %v after %d calls, want svcA run a second time", ok, rerr, calls) + } +} + +// runOnce runs service id through h, reporting whether it ran and any error. +func runOnce[S comparable, E comparable, C any](ctx context.Context, h *Handle[S, E, C], id string) (bool, error) { + _, ok, err := h.RunService(ctx, id) + return ok, err +} diff --git a/durable/start_effects_contract_test.go b/durable/start_effects_contract_test.go new file mode 100644 index 00000000..bcf92072 --- /dev/null +++ b/durable/start_effects_contract_test.go @@ -0,0 +1,307 @@ +package durable_test + +// These tests pin Start's documented contract for the initial entry's domain effects: +// they are at-least-once. Start applies them before it writes the baseline and never +// marks them, and nothing replays them, so a handler failure, a failed baseline write +// or overlapping Starts re-apply them, and Recover never applies them. + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +const ( + startNotifyID = "-1#0#demo.notify" + startChargeID = "-1#1#demo.charge" +) + +// entryTwoEffectsMachine emits two host effects on entering its initial state. +func entryTwoEffectsMachine() *state.Machine[string, string, *runCtx] { + return state.ForgeFor[*runCtx]("entryTwo"). + Action("notify", func(state.ActionCtx[*runCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + Action("charge", func(state.ActionCtx[*runCtx]) (state.Effect, error) { + return chargeEffect{Cents: 500}, nil + }). + State("ready").OnEntry("notify").OnEntry("charge"). + State("done").Final(). + Initial("ready"). + Transition("ready").On("finish").GoTo("done"). + Quench() +} + +// startContractStore wraps a MemStore. It can fail Checkpoint once, and report an +// instance not found on its first lieLoads probes, as two Starts whose probes both ran +// before either wrote see it. It counts every call. +type startContractStore struct { + *durable.MemStore + mu sync.Mutex + failCheckpoint int + lieLoads int + calls map[string]int +} + +func newStartContractStore() *startContractStore { + return &startContractStore{MemStore: durable.NewMemStore(), calls: map[string]int{}} +} + +func (s *startContractStore) count(op string) { + s.mu.Lock() + defer s.mu.Unlock() + s.calls[op]++ +} + +func (s *startContractStore) callCount(op string) int { + s.mu.Lock() + defer s.mu.Unlock() + return s.calls[op] +} + +func (s *startContractStore) Load(ctx context.Context, id durable.InstanceID) ([]byte, []durable.Record, error) { + s.count("Load") + s.mu.Lock() + lie := s.lieLoads > 0 + if lie { + s.lieLoads-- + } + s.mu.Unlock() + if lie { + return nil, nil, fmt.Errorf("%w: %q", durable.ErrInstanceNotFound, id) + } + return s.MemStore.Load(ctx, id) +} + +func (s *startContractStore) Checkpoint(ctx context.Context, id durable.InstanceID, snap []byte, through int, opts ...durable.CheckpointOption) error { + s.count("Checkpoint") + s.mu.Lock() + fail := s.failCheckpoint > 0 + if fail { + s.failCheckpoint-- + } + s.mu.Unlock() + if fail { + return errors.New("checkpoint unavailable") + } + return s.MemStore.Checkpoint(ctx, id, snap, through, opts...) +} + +func (s *startContractStore) MarkDispatched(ctx context.Context, id durable.InstanceID, ids ...string) error { + s.count("MarkDispatched") + return s.MemStore.MarkDispatched(ctx, id, ids...) +} + +func handlerOpt(rec *effectRecorder) durable.Option[string, string, *runCtx] { + return durable.WithEffectHandler[string, string, *runCtx](rec.handler()) +} + +// mustNotExist fails unless the Store has no instance id. +func mustNotExist(t *testing.T, st durable.Store, id durable.InstanceID) { + t.Helper() + if _, _, err := st.Load(context.Background(), id); !errors.Is(err, durable.ErrInstanceNotFound) { + t.Fatalf("Load(%q) = %v, want ErrInstanceNotFound: a failed Start leaves no instance", id, err) + } +} + +// TestStart_HandlerFails_LeavesNoInstance_StartAgainReappliesEffects: a handler that +// fails on the second initial effect fails Start with ErrEffectDispatch and leaves no +// instance, so the caller can Start again, which applies the first effect a second +// time. Recover applies neither. +func TestStart_HandlerFails_LeavesNoInstance_StartAgainReappliesEffects(t *testing.T) { + ctx := context.Background() + st := newStartContractStore() + rec := newEffectRecorder() + rec.failKinds["demo.charge"] = errors.New("downstream unavailable") + r := durable.NewRunner(entryTwoEffectsMachine(), st, handlerOpt(rec)) + + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("first Start = %v, want ErrEffectDispatch", err) + } + mustNotExist(t, st, "i1") + if n := rec.count(startNotifyID); n != 1 { + t.Fatalf("notify applied %d times by the failed Start, want 1", n) + } + + delete(rec.failKinds, "demo.charge") + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("second Start = %v, want it to create the instance", err) + } + if _, err := durable.Recover(ctx, entryTwoEffectsMachine(), st, "i1", handlerOpt(rec)); err != nil { + t.Fatalf("Recover: %v", err) + } + if n := rec.count(startNotifyID); n != 2 { + t.Errorf("notify applied %d times, want 2: Start again re-applies it", n) + } + if n := rec.count(startChargeID); n != 1 { + t.Errorf("charge applied %d times, want 1: the retry's", n) + } +} + +// TestStart_BaselineCheckpointFails_RetryReappliesEffects: the effects apply before the +// baseline write, so a failed baseline Checkpoint leaves no instance, and the retried +// Start applies them again. +func TestStart_BaselineCheckpointFails_RetryReappliesEffects(t *testing.T) { + ctx := context.Background() + st := newStartContractStore() + st.failCheckpoint = 1 + rec := newEffectRecorder() + r := durable.NewRunner(entryNotifyMachine(), st, handlerOpt(rec)) + + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err == nil { + t.Fatal("first Start = nil, want the Checkpoint failure") + } + if n := rec.count(startNotifyID); n != 1 { + t.Fatalf("notify applied %d times before the failed baseline write, want 1", n) + } + mustNotExist(t, st, "i1") + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("retried Start: %v", err) + } + if n := rec.count(startNotifyID); n != 2 { + t.Errorf("notify applied %d times across the retry, want 2", n) + } +} + +// TestStart_OverlappingStarts_EachAppliesBeforeTheStoreRefusesTheLoser: two Starts on +// one id whose probes both ran before either wrote each apply the effects; the Store +// then refuses the second baseline. +func TestStart_OverlappingStarts_EachAppliesBeforeTheStoreRefusesTheLoser(t *testing.T) { + ctx := context.Background() + st := newStartContractStore() + st.lieLoads = 2 + rec := newEffectRecorder() + r := durable.NewRunner(entryNotifyMachine(), st, handlerOpt(rec)) + + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("first Start: %v", err) + } + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); !errors.Is(err, durable.ErrCheckpointNotAdvancing) { + t.Fatalf("second Start = %v, want ErrCheckpointNotAdvancing", err) + } + if n := rec.count(startNotifyID); n != 2 { + t.Errorf("notify applied %d times across overlapping Starts, want 2", n) + } +} + +// TestStart_OverlappingFencedOwners_EachAppliesBeforeTheStoreRefusesTheLoser: a stale +// owner (token 1) and a new one (token 2) whose probes both ran before either wrote +// each apply the effects, in either order, before the Store refuses the loser's +// baseline. The new owner's Recover applies none. +func TestStart_OverlappingFencedOwners_EachAppliesBeforeTheStoreRefusesTheLoser(t *testing.T) { + cases := []struct { + first, second int64 + wantLoserErr error + }{ + {2, 1, durable.ErrFenced}, + {1, 2, durable.ErrCheckpointNotAdvancing}, + } + for _, tc := range cases { + t.Run(fmt.Sprintf("token%d_then_token%d", tc.first, tc.second), func(t *testing.T) { + ctx := context.Background() + st := newStartContractStore() + st.lieLoads = 2 + rec := newEffectRecorder() + runner := func(tok int64) *durable.Runner[string, string, *runCtx] { + return durable.NewRunner(entryTwoEffectsMachine(), st, handlerOpt(rec), + durable.WithOwnerFence[string, string, *runCtx](tok)) + } + if _, err := runner(tc.first).Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("Start(token %d): %v", tc.first, err) + } + if _, err := runner(tc.second).Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); !errors.Is(err, tc.wantLoserErr) { + t.Fatalf("Start(token %d) = %v, want %v", tc.second, err, tc.wantLoserErr) + } + if n := rec.count(startNotifyID); n != 2 { + t.Errorf("notify applied %d times across both owners, want 2", n) + } + if _, err := durable.Recover(ctx, entryTwoEffectsMachine(), st, "i1", handlerOpt(rec), + durable.WithOwnerFence[string, string, *runCtx](2)); err != nil { + t.Fatalf("Recover(token 2): %v", err) + } + if n := rec.count(startNotifyID); n != 2 { + t.Errorf("notify applied %d times after the takeover, want still 2: Recover applies none", n) + } + }) + } +} + +// TestStart_InitialErr_AppliesNoEffects: an initial entry that failed applies no +// effects, at Start or at Recover. +func TestStart_InitialErr_AppliesNoEffects(t *testing.T) { + ctx := context.Background() + st := newStartContractStore() + rec := newEffectRecorder() + h, err := durable.NewRunner(failingEntryMachine(), st, handlerOpt(rec)).Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if h.Instance().InitialErr() == nil { + t.Fatal("InitialErr = nil, want the entry's error") + } + if _, err = durable.Recover(ctx, failingEntryMachine(), st, "i1", handlerOpt(rec)); err != nil { + t.Fatalf("Recover: %v", err) + } + if n := rec.totalApplies(); n != 0 { + t.Errorf("applied %d effects from a failed entry, want 0", n) + } +} + +// TestStart_HandlerWiredOnlyAtRecover_NeverSeesStartEffects: Start's effects are applied +// by Start or not at all. A handler first wired at Recover doesn't see them. +func TestStart_HandlerWiredOnlyAtRecover_NeverSeesStartEffects(t *testing.T) { + ctx := context.Background() + st := newStartContractStore() + if _, err := durable.NewRunner(entryTwoEffectsMachine(), st).Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("Start: %v", err) + } + rec := newEffectRecorder() + if _, err := durable.Recover(ctx, entryTwoEffectsMachine(), st, "i1", handlerOpt(rec)); err != nil { + t.Fatalf("Recover: %v", err) + } + if n := rec.totalApplies(); n != 0 { + t.Errorf("Recover's handler applied %d of Start's effects, want 0", n) + } +} + +// TestStart_HandlerSeesBaselineEffectIDsAndInstance_MarksNothing: at Start the handler +// gets each initial effect under its baseline id, "-1##", with the +// instance on its ctx, and Start marks none of them dispatched. +func TestStart_HandlerSeesBaselineEffectIDsAndInstance_MarksNothing(t *testing.T) { + ctx := context.Background() + st := newStartContractStore() + type call struct { + inst durable.InstanceID + ok bool + id string + } + var calls []call + handler := func(ctx context.Context, id string, _ state.Effect) error { + inst, ok := durable.EffectInstance(ctx) + calls = append(calls, call{inst, ok, id}) + return nil + } + if _, err := durable.NewRunner(entryTwoEffectsMachine(), st, + durable.WithEffectHandler[string, string, *runCtx](handler)).Start(ctx, "i1", &runCtx{}, state.WithInitialState("ready")); err != nil { + t.Fatalf("Start: %v", err) + } + want := []call{{"i1", true, startNotifyID}, {"i1", true, startChargeID}} + if len(calls) != len(want) || calls[0] != want[0] || calls[1] != want[1] { + t.Fatalf("handler saw %+v, want %+v", calls, want) + } + if n := st.callCount("MarkDispatched"); n != 0 { + t.Errorf("Start called MarkDispatched %d times, want none", n) + } + dispatched, err := st.Dispatched(ctx, "i1") + if err != nil { + t.Fatalf("Dispatched: %v", err) + } + if len(dispatched) != 0 { + t.Errorf("Start marked %v dispatched, want none", dispatched) + } +} diff --git a/durable/stopped_later_internal_test.go b/durable/stopped_later_internal_test.go new file mode 100644 index 00000000..143a0af1 --- /dev/null +++ b/durable/stopped_later_internal_test.go @@ -0,0 +1,33 @@ +package durable + +import ( + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestStoppedLater_SkipsOnlyAnActivationThatEndsInTheStep pins which spawns +// stoppedLater reports: a state's spawn a later effect stops, in its own call's effects +// or a later call's, and not the spawn for the activation that follows that stop, nor a +// dynamic spawn, nor another actor's. +func TestStoppedLater_SkipsOnlyAnActivationThatEndsInTheStep(t *testing.T) { + x := state.SpawnActor{ID: "x", State: "S"} + stopX := state.StopActor{ID: "x"} + dynamic := state.SpawnActor{ID: "x"} + for _, tc := range []struct { + name string + sp state.SpawnActor + rest, later []state.Effect + want bool + }{ + {"stopped later in the call", x, []state.Effect{stopX}, nil, true}, + {"stopped in a later call", x, nil, []state.Effect{stopX}, true}, + {"the activation after the stop", x, nil, nil, false}, + {"another actor stopped", x, []state.Effect{state.StopActor{ID: "y"}}, nil, false}, + {"a dynamic spawn", dynamic, []state.Effect{stopX}, nil, false}, + } { + if got := stoppedLater(tc.sp, tc.rest, tc.later); got != tc.want { + t.Errorf("%s: stoppedLater = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/durable/store.go b/durable/store.go index 0ba8ca0d..fddc867c 100644 --- a/durable/store.go +++ b/durable/store.go @@ -59,7 +59,11 @@ type Record struct { // Effects are the effects the step emitted, each with its deterministically // stamped EffectID, persisted before dispatch so a crash between persist and - // dispatch is recoverable: Resume re-dispatches, deduped by EffectID. + // dispatch is recoverable: Recover re-dispatches, deduped by EffectID. A + // KindedEffect whose payload won't marshal is recorded by EffectID and Kind with no + // Payload, as an effect that isn't a KindedEffect is, and its Meta holds the + // marshal error's message under "crucible.marshalError". Replay re-derives every + // effect's value, so none is rebuilt from its envelope. Effects []state.EffectEnvelope // Snapshot, when non-empty, is a full marshaled state.Snapshot captured at @@ -114,8 +118,11 @@ type Record struct { // 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. + // Record of format 1 or later, since an older run took no clock read for them. From + // format 2 the live run dispatched a tick's and a service settle's domain effects, so + // Recover sends them, and a Tick handed its timer transitions' effects to the service + // runner and the actor system, so replay starts and stops their services as it did; + // an older Record replays as that version ran it. A Store keeps it as it keeps Step. Format int `json:",omitempty"` } diff --git a/durable/tick_absorb_ctx_test.go b/durable/tick_absorb_ctx_test.go new file mode 100644 index 00000000..e78287c9 --- /dev/null +++ b/durable/tick_absorb_ctx_test.go @@ -0,0 +1,497 @@ +package durable_test + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// pingTarget is an actor that notes a ping delivered under a live context, and +// refuses one whose context ended, as an actor backed by an Instance does. +type pingTarget struct{ pinged bool } + +func (p *pingTarget) DeliverFire(ctx context.Context, ev any) (bool, any) { + if ev != "ping" || ctx.Err() != nil { + return false, nil + } + p.pinged = true + return true, nil +} +func (p *pingTarget) ChildEffects() []state.Effect { return nil } +func (p *pingTarget) Output() any { return nil } + +// pingSender is an actor that pings its sibling as it starts. +type pingSender struct { + target string + sent bool +} + +func (p *pingSender) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (p *pingSender) ChildEffects() []state.Effect { + if p.sent { + return nil + } + p.sent = true + return []state.Effect{state.SendTo{TargetID: p.target, Event: "ping"}} +} +func (p *pingSender) Output() any { return nil } + +// TestTick_AContextThatEndsWhileTheTickSpawnsActors_RecordsAndLosesTheMessage pins that +// Tick doesn't check its context after it hands the fired timers' effects to the actor +// system, unlike RunService: only a parent Fire refused by a context fails it. A timer +// enters pair, which spawns target and then sender, whose behavior runs as the deadline +// passes and which pings target as it starts. Target refuses the ping, its context +// having ended, and the ping is lost live, as actor deliveries are across Recover. The +// tick records, so a retry doesn't run the behaviors again. Recover starts both actors +// fresh, and sender's new start pings the new target. +func TestTick_AContextThatEndsWhileTheTickSpawnsActors_RecordsAndLosesTheMessage(t *testing.T) { + ctx := context.Background() + const machine = "tickSpawnCtx" + targetID := state.ActorID(machine, "pair", 0) + m := state.ForgeFor[stepCtx](machine). + Actor("target"). + Actor("sender"). + State("idle"). + State("waiting"). + State("pair").InvokeActor("target").InvokeActor("sender"). + Initial("idle"). + Transition("idle").On("go").GoTo("waiting"). + Transition("waiting").After(5 * time.Second).On("due").GoTo("pair"). + Quench() + clk := state.NewFakeClock(epoch) + cancel := func() {} + var targets []*pingTarget + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "target": func(map[string]any) (state.ActorInstance, error) { + targets = append(targets, &pingTarget{}) + return targets[len(targets)-1], nil + }, + "sender": func(map[string]any) (state.ActorInstance, error) { + cancel() // the deadline passes as sender starts + return &pingSender{target: targetID}, nil + }, + }), + } + store, id := durable.NewMemStore(), durable.InstanceID("tick-spawn-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) + } + before := tailLen(t, store, id) + clk.Advance(6 * time.Second) + turn, c := context.WithCancel(ctx) + cancel = c + _, tickErr := h.Tick(turn) + if turn.Err() == nil || len(targets) != 1 { + t.Fatalf("setup: context ended %v, live spawned %d targets; want it ended, with one target", turn.Err() != nil, len(targets)) + } + if tickErr != nil { + t.Fatalf("Tick = %v, want the step recorded: only a parent Fire refused by a context fails it", tickErr) + } + wantTail(t, store, id, before+1) + if targets[0].pinged { + t.Fatal("live target was pinged, want the ping it refused under the ended context lost") + } + + cancel = func() {} + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "pair" || len(targets) != 2 || !targets[1].pinged { + t.Fatalf("recovered in %q, %d targets spawned; want pair, with target respawned and pinged by sender's new start", got, len(targets)) + } +} + +// TestFire_AContextThatEndsWhileTheFireSpawnsActors_RecordsAndLosesTheMessage pins that +// Fire doesn't check its context after it hands the event's effects to the actor +// system, as Tick doesn't: only a parent Fire refused by a context fails it. The event +// enters pair, which spawns target and then sender, whose behavior runs as the deadline +// passes and which pings target as it starts. Target refuses the ping, its context +// having ended, and the ping is lost live, as actor deliveries are across Recover. The +// Fire records, so a retry doesn't run the behaviors again. Recover starts both actors +// fresh, and sender's new start pings the new target. +func TestFire_AContextThatEndsWhileTheFireSpawnsActors_RecordsAndLosesTheMessage(t *testing.T) { + ctx := context.Background() + const machine = "fireSpawnCtx" + targetID := state.ActorID(machine, "pair", 0) + m := state.ForgeFor[stepCtx](machine). + Actor("target"). + Actor("sender"). + State("idle"). + State("pair").InvokeActor("target").InvokeActor("sender"). + Initial("idle"). + Transition("idle").On("go").GoTo("pair"). + Quench() + cancel := func() {} + var targets []*pingTarget + opts := []stepOption{ + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "target": func(map[string]any) (state.ActorInstance, error) { + targets = append(targets, &pingTarget{}) + return targets[len(targets)-1], nil + }, + "sender": func(map[string]any) (state.ActorInstance, error) { + cancel() // the deadline passes as sender starts + return &pingSender{target: targetID}, nil + }, + }), + } + store, id := durable.NewMemStore(), durable.InstanceID("fire-spawn-ctx") + 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) + turn, c := context.WithCancel(ctx) + cancel = c + _, fireErr := h.Fire(turn, "go") + if turn.Err() == nil || len(targets) != 1 { + t.Fatalf("setup: context ended %v, live spawned %d targets; want it ended, with one target", turn.Err() != nil, len(targets)) + } + if fireErr != nil { + t.Fatalf("Fire = %v, want the step recorded: only a parent Fire refused by a context fails it", fireErr) + } + wantTail(t, store, id, before+1) + if targets[0].pinged { + t.Fatal("live target was pinged, want the ping it refused under the ended context lost") + } + + cancel = func() {} + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "pair" || len(targets) != 2 || !targets[1].pinged { + t.Fatalf("recovered in %q, %d targets spawned; want pair, with target respawned and pinged by sender's new start", got, len(targets)) + } +} + +// TestFire_ContextEndedWithNoActorPalette_Records pins that a Fire whose context ends +// once the kernel applied its event, here while the step armed its timer, and that drove +// no parent Fire, records. Without WithActorPalette, a state that declares an actor +// spawns none. +func TestFire_ContextEndedWithNoActorPalette_Records(t *testing.T) { + ctx := context.Background() + turn, cancel := context.WithCancel(ctx) + defer cancel() + m := state.ForgeFor[stepCtx]("fireNoPalette"). + Actor("target"). + State("idle"). + State("pair").InvokeActor("target"). + State("done"). + Initial("idle"). + Transition("idle").On("go").GoTo("pair"). + Transition("pair").After(time.Second).On("due").GoTo("done"). + Quench() + clk := &countingClock{Clock: state.NewFakeClock(epoch)} + store, id := durable.NewMemStore(), durable.InstanceID("fire-no-palette") + 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, "go") + 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 step recorded: no actor spawned, so the ended context cost nothing", err) + } + wantTail(t, store, id, before+1) + if got := h.Instance().Current(); got != "pair" { + t.Fatalf("state = %q, want pair", got) + } +} + +// endingActor is an actor whose delivery runs as the deadline passes: it ends the +// step's context, and keeps running. +type endingActor struct{ end func() } + +func (e endingActor) DeliverFire(context.Context, any) (bool, any) { + e.end() + return false, nil +} +func (endingActor) ChildEffects() []state.Effect { return nil } +func (endingActor) Output() any { return nil } + +// noteTarget is an actor that counts the messages delivered to it under a live +// context, and refuses one whose context ended, as an actor backed by an Instance does. +type noteTarget struct{ got int } + +func (n *noteTarget) DeliverFire(ctx context.Context, _ any) (bool, any) { + if ctx.Err() != nil { + return false, nil + } + n.got++ + return false, nil +} +func (*noteTarget) ChildEffects() []state.Effect { return nil } +func (*noteTarget) Output() any { return nil } + +// TestStep_AContextThatEndsWhileTheStepMessagesActors_RecordsAndLosesTheMessage pins +// that Fire and Tick don't fail when an actor refuses a message they sent it because +// their context ended. Pair runs ender and target; poke, and the timer due, each stay in +// pair and send ender a message, then target one, by SendTo or, for a Fire, by +// ForwardTo alone. Ender's delivery runs as the deadline passes, so target refuses its +// message, its context having ended. The message is lost, as actor deliveries are +// across Recover, and the step records: failing it would have the retry run the +// actors' behaviors again. A recovered Handle starts target fresh, without the message. +func TestStep_AContextThatEndsWhileTheStepMessagesActors_RecordsAndLosesTheMessage(t *testing.T) { + for _, step := range []string{"Fire", "Fire forward", "Tick"} { + t.Run(step, func(t *testing.T) { + ctx := context.Background() + machine := "messageCtx" + strings.ReplaceAll(step, " ", "") + enderID := state.ActorID(machine, "pair", 0) + targetID := state.ActorID(machine, "pair", 1) + b := state.ForgeFor[stepCtx](machine). + Actor("ender"). + Actor("target"). + State("idle"). + State("pair").InvokeActor("ender").InvokeActor("target"). + Initial("idle"). + Transition("idle").On("go").GoTo("pair") + switch step { + case "Fire": + b = b.Transition("pair").On("poke").GoTo("pair").SendTo(enderID, "x").SendTo(targetID, "ping") + case "Fire forward": + b = b.Transition("pair").On("poke").GoTo("pair").ForwardTo(enderID).ForwardTo(targetID) + default: + b = b.Transition("pair").After(5*time.Second).On("due").GoTo("pair").SendTo(enderID, "x").SendTo(targetID, "ping") + } + m := b.Quench() + clk := state.NewFakeClock(epoch) + cancel := func() {} + var targets []*noteTarget + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "ender": func(map[string]any) (state.ActorInstance, error) { + return endingActor{end: func() { cancel() }}, nil + }, + "target": func(map[string]any) (state.ActorInstance, error) { + targets = append(targets, ¬eTarget{}) + return targets[len(targets)-1], nil + }, + }), + } + store, id := durable.NewMemStore(), durable.InstanceID("message-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) + } + before := tailLen(t, store, id) + run := func(h *durable.Handle[string, string, stepCtx], ctx context.Context) error { + if step != "Tick" { + _, fireErr := h.Fire(ctx, "poke") + return fireErr + } + _, tickErr := h.Tick(ctx) + return tickErr + } + clk.Advance(6 * time.Second) + turn, c := context.WithCancel(ctx) + cancel = c + stepErr := run(h, turn) + if turn.Err() == nil || len(targets) != 1 || targets[0].got != 0 { + t.Fatalf("setup: context ended %v, live spawned %d targets, the first with %d messages; want it ended, with one target and none", + turn.Err() != nil, len(targets), targets[0].got) + } + + if stepErr != nil { + t.Fatalf("%s = %v, want the step recorded: only a parent Fire refused by a context fails it", step, stepErr) + } + wantTail(t, store, id, before+1) + + cancel = func() {} + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "pair" || len(targets) != 2 || targets[1].got != 0 { + t.Fatalf("recovered in %q, %d targets spawned; want pair, with target respawned once, without the lost message", got, len(targets)) + } + }) + } +} + +// liveOnceCtx is a context that ends partway through a step with no host code to +// end it, as a deadline does: once armed, it answers Err as live live more times, +// then as context.Canceled. +type liveOnceCtx struct { + context.Context + armed bool + live int +} + +func (c *liveOnceCtx) Err() error { + if !c.armed { + return nil + } + if c.live > 0 { + c.live-- + return nil + } + return context.Canceled +} + +// TestStep_AContextThatEndsWithNoActorWork_Records pins that a step whose context ends +// after the kernel applied it, and that drove no parent Fire, records. A machine with timers and a +// service but no actor palette enters loading, which starts fetch and arms expire, by a +// Fire and by a timer. The context ends after the kernel applied the step: for the +// Fire, as it arms expire; for the Tick, after the check that follows the timers' Fires, +// where no host code runs before the absorb, so the context reports it ended from its +// next check on. Handing a service to the runner runs nothing, so the ended context +// cost neither step anything: both record, with fetch in flight, live and recovered. +func TestStep_AContextThatEndsWithNoActorWork_Records(t *testing.T) { + for _, step := range []string{"Fire", "Tick"} { + t.Run(step, func(t *testing.T) { + ctx := context.Background() + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + machine := "noActorWork" + step + m := state.ForgeFor[stepCtx](machine). + Service("fetch", fetch). + State("idle"). + State("waiting"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("fetched")). + State("ready"). + Initial("idle"). + Transition("idle").On("load").GoTo("loading"). + Transition("idle").On("wait").GoTo("waiting"). + Transition("waiting").After(5 * time.Second).On("due").GoTo("loading"). + Transition("loading").After(time.Minute).On("expire").GoTo("idle"). + Transition("loading").On("fetched").GoTo("ready"). + Quench() + fc := state.NewFakeClock(epoch) + clk := &countingClock{Clock: fc} + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch)), + } + store, id := durable.NewMemStore(), durable.InstanceID("no-actor-work") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + turn := &liveOnceCtx{Context: ctx} + if step == "Fire" { + before := tailLen(t, store, id) + clk.onRead = func(int) { turn.armed = true } // arming expire, after the kernel returned + _, err = h.Fire(turn, "load") + clk.onRead = nil + if !turn.armed { + t.Fatal("the test didn't end the context") + } + if err != nil { + t.Fatalf("Fire = %v, want the step recorded: it handed the actor system nothing", err) + } + wantTail(t, store, id, before+1) + } else { + if _, err = h.Fire(ctx, "wait"); err != nil { + t.Fatalf("Fire(wait): %v", err) + } + before := tailLen(t, store, id) + fc.Advance(6 * time.Second) + base := clk.n + clk.onRead = func(n int) { + if n == base+3 { // the scheduler's last read, once due applied and expire armed + turn.armed, turn.live = true, 1 // live for the check after the timers' Fires + } + } + _, err = h.Tick(turn) + clk.onRead = nil + if !turn.armed || turn.live != 0 { + t.Fatalf("setup: armed %v, %d live answers left; want the context to end after the check that follows the timers' Fires", turn.armed, turn.live) + } + if err != nil { + t.Fatalf("Tick = %v, want the step recorded, as the Fire is: it handed the actor system nothing", err) + } + wantTail(t, store, id, before+1) + } + if got := h.Instance().Current(); got != "loading" { + t.Fatalf("state = %q, want loading", got) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + svcID := state.InvokeID(machine, "loading", 0) + for name, h := range map[string]*durable.Handle[string, string, stepCtx]{"live": h, "recovered": recovered} { + if _, ran, err := h.RunService(ctx, svcID); !ran || err != nil { + t.Fatalf("%s RunService = %v, %v; want fetch in flight and settled", name, ran, err) + } + } + }) + } +} + +// TestFire_AContextThatEndsWithNoActorToReach_Records pins that a Fire whose context +// ends after the kernel applied it, and that drove no parent Fire, records. Leave exits pair, which stops idler, and responds to the event's +// sender, which a host Fire doesn't have, then arms a timer, as the context ends. +// Stopping an actor runs nothing an ended context can refuse, and a response with no +// sender reaches no actor, so the Fire cost nothing and records, with idler stopped +// live and recovered. +func TestFire_AContextThatEndsWithNoActorToReach_Records(t *testing.T) { + ctx := context.Background() + const machine = "noActorToReach" + m := state.ForgeFor[stepCtx](machine). + Actor("idler"). + State("pair").InvokeActor("idler"). + State("away"). + Initial("pair"). + Transition("pair").On("leave").GoTo("away").Respond("bye"). + Transition("away").After(time.Second).On("back").GoTo("pair"). + Quench() + clk := &countingClock{Clock: state.NewFakeClock(epoch)} + idlers := 0 + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "idler": func(map[string]any) (state.ActorInstance, error) { idlers++; return ¬eTarget{}, nil }, + }), + } + store, id := durable.NewMemStore(), durable.InstanceID("no-actor-to-reach") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("pair")) + if err != nil { + t.Fatalf("Start: %v", err) + } + before := tailLen(t, store, id) + turn, cancel := context.WithCancel(ctx) + defer cancel() + clk.onRead = func(int) { cancel() } // arming back, after the kernel returned + _, err = h.Fire(turn, "leave") + 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 step recorded: it stopped an actor and responded to no one", err) + } + wantTail(t, store, id, before+1) + idlerID := state.ActorID(machine, "pair", 0) + if _, ok := h.ActorRef(idlerID); ok { + t.Fatal("idler still runs live, want it stopped") + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "away" || idlers != 1 { + t.Fatalf("recovered in %q with idler spawned %d times; want away, spawned once", got, idlers) + } +} diff --git a/durable/tick_drivers_test.go b/durable/tick_drivers_test.go index 4c8cd73b..f48f4552 100644 --- a/durable/tick_drivers_test.go +++ b/durable/tick_drivers_test.go @@ -2,7 +2,9 @@ package durable_test import ( "context" + "errors" "fmt" + "strings" "testing" "time" @@ -14,7 +16,6 @@ import ( // 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 } @@ -56,7 +57,6 @@ func TestTick_ATimerThatLeavesAServiceStateStopsTheService(t *testing.T) { // 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 @@ -106,3 +106,349 @@ func TestRecover_ATickEnteredStatesActorMatchesLive(t *testing.T) { t.Fatalf("live notes %s, recovered %s; want [hello] for both: the Tick's state spawns its greeter once", live, got) } } + +// TestRecover_AnOlderVersionsTickReplaysAsItRan pins that replay hands a tick's timer +// transitions to the service runner only for a Record of a format that did so live: an +// older version's Tick left the service of a state its timer left in flight, so a +// journal of format 1 replays with the service still in flight, as that run had it, +// and a later settle that run journaled still replays. This version's journal replays +// with the service stopped, as its live Tick left it. +func TestRecover_AnOlderVersionsTickReplaysAsItRan(t *testing.T) { + ctx := context.Background() + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { 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").After(5 * time.Second).On("timeout").GoTo("timedOut"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch)), + } + st := durable.NewMemStore() + h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", 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) + } + id := state.InvokeID("tickExit", "fetching", 0) + + snap, recs, err := st.Load(ctx, "i1") + if err != nil { + t.Fatalf("Load: %v", err) + } + old := durable.NewMemStore() + if err = old.Checkpoint(ctx, "i1", withCheckpointFormat(t, snap, 1), -1); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + for _, rec := range recs { + rec.Format = 1 + if _, err = old.Append(ctx, "i1", rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + + cur, err := durable.Recover(ctx, m, st, "i1", opts...) + if err != nil { + t.Fatalf("Recover this version's journal: %v", err) + } + if _, ran, rerr := cur.RunService(ctx, id); ran || rerr != nil { + t.Fatalf("RunService after recovering this version's journal = %v, %v; want nothing in flight", ran, rerr) + } + oh, err := durable.Recover(ctx, m, old, "i1", opts...) + if err != nil { + t.Fatalf("Recover the older journal: %v", err) + } + if _, ran, rerr := oh.RunService(ctx, id); !ran || rerr != nil { + t.Fatalf("RunService after recovering the older journal = %v, %v; want the service in flight, as that version's Tick left it", ran, rerr) + } + if _, err = durable.Recover(ctx, m, old, "i1", opts...); err != nil { + t.Fatalf("Recover after the settle the older run left in flight: %v", err) + } +} + +// TestRecover_AnOlderVersionsTickThenACheckpointAndASettle_FailsRecover pins today's +// upgrade path for a journal an older version wrote, of format 0 or 1, whose tick left +// fetching with fetch in flight, as that version's Tick did. Recover replays the tick +// as it ran, so the recovered Handle still has fetch in flight. Its next checkpoint, of +// this version's format, holds only the configuration's services, and timedOut declares +// none, so fetch isn't in it. RunService settles fetch after that checkpoint, and the +// settle's Record follows it in the tail, so every later Recover fails replaying a +// settle with no service in flight. This pins the current behavior for a decision: a +// Recover that stops, after its walk, the services such a tick left in flight would +// recover, as would replaying the tick with this version's rules, though that one fails +// on an older tail that settles fetch after the tick. +func TestRecover_AnOlderVersionsTickThenACheckpointAndASettle_FailsRecover(t *testing.T) { + for _, format := range []int{0, 1} { + t.Run(fmt.Sprintf("format %d", format), func(t *testing.T) { + ctx := context.Background() + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + m := state.ForgeFor[stepCtx]("tickUpgrade"). + Service("fetch", fetch). + State("idle"). + State("fetching").Invoke("fetch", state.WithInvokeOnDone("fetched")). + State("timedOut"). + Initial("idle"). + Transition("idle").On("begin").GoTo("fetching"). + Transition("fetching").After(5 * time.Second).On("timeout").GoTo("timedOut"). + Transition("timedOut").On("poke").GoTo("timedOut"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch)), + } + st := durable.NewMemStore() + h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", 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) + } + snap, recs, err := st.Load(ctx, "i1") + if err != nil { + t.Fatalf("Load: %v", err) + } + old := durable.NewMemStore() + if err = old.Checkpoint(ctx, "i1", withCheckpointFormat(t, snap, format), -1); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + for _, rec := range recs { + rec.Format = format + if _, err = old.Append(ctx, "i1", rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + + // Checkpoint after poke, not after the settle that follows it. + checkpointing := append(opts[:len(opts):len(opts)], durable.WithCheckpointEvery[string, string, stepCtx](2)) + oh, err := durable.Recover(ctx, m, old, "i1", checkpointing...) + if err != nil { + t.Fatalf("Recover the older journal: %v", err) + } + if _, err = oh.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if n := tailLen(t, old, "i1"); n != 0 { + t.Fatalf("setup: %d records after poke, want a checkpoint that compacted the tail", n) + } + id := state.InvokeID("tickUpgrade", "fetching", 0) + if _, ran, rerr := oh.RunService(ctx, id); !ran || rerr != nil { + t.Fatalf("RunService = %v, %v; want fetch in flight, as the older Tick left it", ran, rerr) + } + if n := tailLen(t, old, "i1"); n != 1 { + t.Fatalf("setup: %d records after the settle, want only the settle past the checkpoint", n) + } + _, err = durable.Recover(ctx, m, old, "i1", opts...) + if err == nil || !strings.Contains(err.Error(), "no in-flight service to settle") { + t.Fatalf("Recover after the settle = %v; today it fails with no in-flight service to settle", err) + } + }) + } +} + +// TestTick_AnActorsParentFireRefusedByAContext_RecordsNothing pins the ctx rule for a +// parent Fire an actor drives as a Tick spawns it: a timer enters greeting, whose +// greeter sends hello as it starts, and a middleware refuses hello under a context it +// derived and ended. Live never applied hello, so the Tick fails the Handle and records +// nothing, as Fire does: a recovered Handle re-arms the timer rather than replay a tick +// whose actor Fire was cut short. +func TestTick_AnActorsParentFireRefusedByAContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + note := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "hello") + return c + } + cancelOnHello := func(next state.FireFunc[string, string, stepCtx]) state.FireFunc[string, string, stepCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + if event == "hello" { + derived, cancel := context.WithCancel(ctx) + cancel() + return next(derived, event) + } + return next(ctx, event) + } + } + m := state.ForgeFor[stepCtx]("tickEnter"). + Use(cancelOnHello). + 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"). + 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-refused") + 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) + } + before := tailLen(t, store, id) + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); !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) + } + rh, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := rh.Instance().Current(); got != "waiting" { + t.Fatalf("recovered in %q, want waiting: the tick wasn't recorded", got) + } +} + +// TestTick_ATimerThatLeavesAnActorStateStopsTheActor pins that a timer-driven transition +// out of a state stops the actor that state spawned, as a Fire's exit does, and that a +// Handle recovered from the journal agrees: neither has the actor running. +func TestTick_ATimerThatLeavesAnActorStateStopsTheActor(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("tickLeave"). + Actor("greeter"). + State("idle"). + State("greeting").InvokeActor("greeter"). + State("quiet"). + Initial("idle"). + Transition("idle").On("go").GoTo("greeting"). + Transition("greeting").On("hello").GoTo("greeting"). + Transition("greeting").After(5 * time.Second).On("hush").GoTo("quiet"). + 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-leave") + 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) + } + actor := state.ActorID("tickLeave", "greeting", 0) + if _, ok := h.ActorRef(actor); !ok { + t.Fatal("entering greeting spawned no greeter") + } + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := h.Instance().Current(); got != "quiet" { + t.Fatalf("state = %q, want quiet", got) + } + if _, ok := h.ActorRef(actor); ok { + t.Fatal("the greeter still runs after the timer left greeting") + } + rh, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ok := rh.ActorRef(actor); ok { + t.Fatal("the recovered Handle runs the greeter, which the live Tick stopped") + } +} + +// TestTick_AnActorsParentFireCallingBack_IsRefused pins that a Tick drives the actors a +// timer spawns under its step's context, as Fire does: a greeter a state's entry spawns +// sends hello as it starts, and a middleware calls back into the Handle with the +// context hello's parent Fire carries. On Fire and on Tick that call gets +// ErrReentrantStep at once, instead of waiting on the step lock its step holds, which +// deadlocks. +func TestTick_AnActorsParentFireCallingBack_IsRefused(t *testing.T) { + for _, via := range []string{"Fire", "Tick"} { + t.Run(via, func(t *testing.T) { + ctx := context.Background() + var h *durable.Handle[string, string, stepCtx] + var viewErr error + viewOnHello := func(next state.FireFunc[string, string, stepCtx]) state.FireFunc[string, string, stepCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + if event == "hello" { + viewErr = h.View(ctx, func(*state.Instance[string, string, stepCtx]) {}) + } + return next(ctx, event) + } + } + m := state.ForgeFor[stepCtx]("tickCallback"). + Use(viewOnHello). + Actor("greeter"). + State("idle"). + State("waiting"). + State("greeting").InvokeActor("greeter"). + Initial("idle"). + Transition("idle").On("go").GoTo("waiting"). + Transition("waiting").On("now").GoTo("greeting"). + Transition("waiting").After(5 * time.Second).On("due").GoTo("greeting"). + Transition("greeting").On("hello").GoTo("greeting"). + Quench() + clk := state.NewFakeClock(epoch) + h, err := durable.NewRunner(m, durable.NewMemStore(), + 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 }, + }), + ).Start(ctx, "tick-callback", 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) + } + var stepErr error + done := make(chan struct{}) + go func() { + defer close(done) + if via == "Fire" { + _, stepErr = h.Fire(ctx, "now") + return + } + clk.Advance(6 * time.Second) + _, stepErr = h.Tick(ctx) + }() + waitFor(t, done, via) + if stepErr != nil { + t.Fatalf("%s: %v", via, stepErr) + } + if !errors.Is(viewErr, durable.ErrReentrantStep) { + t.Fatalf("the middleware's View = %v, want ErrReentrantStep", viewErr) + } + if got := h.Instance().Current(); got != "greeting" { + t.Fatalf("state = %q, want greeting", got) + } + }) + } +} diff --git a/durable/tick_forward_decode_test.go b/durable/tick_forward_decode_test.go new file mode 100644 index 00000000..1e26e208 --- /dev/null +++ b/durable/tick_forward_decode_test.go @@ -0,0 +1,176 @@ +package durable_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// errUndecodable is the error undecodableDue returns for the due event. +var errUndecodable = errors.New("can't decode due") + +// countingCodec is the JSON event codec, counting its decodes, that fails to decode +// the due event when failDue is set. +type countingCodec struct { + decodes int + failDue bool +} + +func (c *countingCodec) Decode(payload []byte) (string, error) { + c.decodes++ + var e string + if len(payload) == 0 { + return e, nil + } + if err := json.Unmarshal(payload, &e); err != nil { + return e, err + } + if c.failDue && e == "due" { + return "", errUndecodable + } + return e, nil +} + +// TestTick_RebuildsATimersEventOnlyToForwardIt pins that a Tick decodes a fired timer's +// event only when the timer's transition forwards it to an actor: with no actor +// palette, or a transition with no forwardTo, the codec isn't called. +func TestTick_RebuildsATimersEventOnlyToForwardIt(t *testing.T) { + for _, tc := range []struct { + name string + palette, forward bool + want int + }{ + {"no actor palette", false, false, 0}, + {"no forwardTo", true, false, 0}, + {"forwardTo", true, true, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + machine := "decodeOnce" + b := state.ForgeFor[stepCtx](machine).State("idle") + if tc.palette { + b = b.Actor("child").State("pair").InvokeActor("child") + } else { + b = b.State("pair") + } + b = b.Initial("idle"). + Transition("idle").On("go").GoTo("pair") + if tc.forward { + b = b.Transition("pair").After(5 * time.Second).On("due").GoTo("pair").ForwardTo(state.ActorID(machine, "pair", 0)) + } else { + b = b.Transition("pair").After(5 * time.Second).On("due").GoTo("pair") + } + m := b.Quench() + clk := state.NewFakeClock(epoch) + codec := &countingCodec{} + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithEventCodec[string, string, stepCtx](codec), + } + if tc.palette { + opts = append(opts, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": func(map[string]any) (state.ActorInstance, error) { return &recordingActor{}, nil }, + })) + } + h, err := durable.NewRunner(m, durable.NewMemStore(), opts...).Start(ctx, "decode", 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) + codec.decodes = 0 + if fired, err := h.Tick(ctx); err != nil || len(fired) != 1 { + t.Fatalf("Tick fired %d timers, err %v; want one", len(fired), err) + } + if codec.decodes != tc.want { + t.Fatalf("Tick decoded %d events, want %d", codec.decodes, tc.want) + } + }) + } +} + +// TestTick_ATimersEventTheCodecCantDecode_IsReported pins that a Tick whose timer +// forwards an event the Runner's codec can't rebuild reports the codec's error rather +// than forward nothing in silence, and forwards nothing to the actor. The tick is still +// recorded, its effects dispatched, and the Handle carries on, as for a message an actor can't take: the timers applied, and failing the Handle +// would have Recover fire them, and run the actors' behaviors, again, to meet the same +// error. +func TestTick_ATimersEventTheCodecCantDecode_IsReported(t *testing.T) { + ctx := context.Background() + machine := "undecodable" + childID := state.ActorID(machine, "pair", 0) + m := state.ForgeFor[stepCtx](machine). + Action("notify", func(state.ActionCtx[stepCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + Actor("child"). + State("idle"). + State("pair").InvokeActor("child"). + State("done"). + Initial("idle"). + Transition("idle").On("go").GoTo("pair"). + Transition("pair").After(5 * time.Second).On("due").GoTo("pair").ForwardTo(childID).Do("notify"). + Transition("pair").On("finish").GoTo("done"). + Quench() + clk := state.NewFakeClock(epoch) + var children []*recordingActor + dispatched := 0 + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithEventCodec[string, string, stepCtx](&countingCodec{failDue: true}), + durable.WithEffectHandler[string, string, stepCtx](func(context.Context, string, state.Effect) error { + dispatched++ + return nil + }), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": func(map[string]any) (state.ActorInstance, error) { + children = append(children, &recordingActor{}) + return children[len(children)-1], nil + }, + }), + } + store, id := durable.NewMemStore(), durable.InstanceID("undecodable") + 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) + fired, err := h.Tick(ctx) + if !errors.Is(err, errUndecodable) || errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("Tick = %v, want the codec's error, with the Handle carrying on", err) + } + if len(fired) != 1 || fired[0].Err != nil { + t.Fatalf("Tick fired %v, want the due timer applied", fired) + } + if len(children) != 1 || len(children[0].got) != 0 { + t.Fatalf("child got %v, want nothing forwarded", children[0].got) + } + if dispatched != 1 { + t.Fatalf("dispatched %d effects, want the due transition's notify", dispatched) + } + if _, err = h.Fire(ctx, "finish"); err != nil { + t.Fatalf("Fire(finish) after the Tick: %v, want the Handle healthy", err) + } + // The tick was recorded: a Recover replays it, then finish. + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if cfg := fmt.Sprint(recovered.Instance().Configuration()); cfg != "[done]" { + t.Fatalf("recovered configuration %s, want [done]", cfg) + } + if tail := tailLen(t, store, id); tail != 3 { + t.Fatalf("journal holds %d records, want go, the tick and finish", tail) + } +} diff --git a/durable/tick_order_test.go b/durable/tick_order_test.go new file mode 100644 index 00000000..88f17729 --- /dev/null +++ b/durable/tick_order_test.go @@ -0,0 +1,95 @@ +package durable_test + +import ( + "context" + "slices" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestTick_AnActorsParentFireSeesEveryTimersServices pins the order a Tick that fires +// several timers drives its runners in: every fired transition's services start or stop +// first, then the actors spawn, and their parent Fires run, as a Fire that produced all +// of the transitions' effects does, and as replay does. Two timers come due at the same +// instant in the two regions of a parallel state: the left one enters a state that +// spawns a leaver, which sends its parent "leave" as it starts; the right one enters a +// state that invokes fetch. "leave" moves the right region on, out of the state that +// invokes fetch, so fetch must not be left in flight: not live, not after a Recover from +// the journal, and not after one from a checkpoint. +func TestTick_AnActorsParentFireSeesEveryTimersServices(t *testing.T) { + ctx := context.Background() + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + m := state.ForgeFor[stepCtx]("tickOrder"). + Service("fetch", fetch). + Actor("leaver"). + State("idle"). + SuperState("par"). + Region("left"). + Initial("l0"). + SubState("l0"). + SubState("l1").InvokeActor("leaver"). + EndRegion(). + Region("right"). + Initial("r0"). + SubState("r0"). + SubState("r1").Invoke("fetch", state.WithInvokeOnDone("fetched")). + SubState("r2"). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("par"). + Transition("l0").After(5 * time.Second).On("leftDue").GoTo("l1"). + Transition("r0").After(5 * time.Second).On("rightDue").GoTo("r1"). + Transition("r1").On("leave").GoTo("r2"). + Transition("r1").On("fetched").GoTo("r1"). + Quench() + fetchID := state.InvokeID("tickOrder", "r1", 0) + for _, tc := range []struct { + name string + every int + }{{"journal", 0}, {"checkpoint", 1}} { + t.Run(tc.name, func(t *testing.T) { + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch)), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "leaver": func(map[string]any) (state.ActorInstance, error) { + return &starting{start: []state.Effect{state.SendParent{Event: "leave"}}}, nil + }, + }), + } + if tc.every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](tc.every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("tick-order") + 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 !slices.Contains(h.Instance().Configuration(), "r2") { + t.Fatalf("live states = %v, want r2: the leaver's leave moved the right region on", h.Instance().Configuration()) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + _, liveRan, liveErr := h.RunService(ctx, fetchID) + _, recRan, recErr := recovered.RunService(ctx, fetchID) + if liveRan || recRan || liveErr != nil || recErr != nil { + t.Fatalf("fetch in flight after r1 exited: live ran %v (%v), recovered ran %v (%v); want neither: live and replay must agree, with no service of an exited state in flight", + liveRan, liveErr, recRan, recErr) + } + }) + } +} diff --git a/durable/tick_service_checkpoint_test.go b/durable/tick_service_checkpoint_test.go new file mode 100644 index 00000000..d34e7251 --- /dev/null +++ b/durable/tick_service_checkpoint_test.go @@ -0,0 +1,138 @@ +package durable_test + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests pin what a Tick does to a service in flight: a timer transition hands its +// effects to the service runner, as a Fire does, so a timer that leaves the state that +// declares the service stops it, and one that re-enters the state starts a fresh +// activation. The live Handle, one recovered from the journal and one recovered from a +// checkpoint agree. + +var timerSvc = state.InvokeID("tsvc", "loading", 0) + +// timerSvcMachine invokes fn in "loading", which "begin" enters from "prep", itself +// entered from "idle" by "prep", so a run's Tick can land on a checkpoint. Its after +// timer leaves for "timedOut", or with reenter re-enters "loading". +func timerSvcMachine(fn state.ServiceFn[svcCtx], reenter bool) *state.Machine[string, string, svcCtx] { + f := state.ForgeFor[svcCtx]("tsvc"). + Service("fetch", fn). + State("idle"). + State("prep"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done")). + State("ready").Final(). + State("timedOut"). + Initial("idle"). + Transition("idle").On("prep").GoTo("prep"). + Transition("prep").On("begin").GoTo("loading"). + Transition("loading").On("done").GoTo("ready") + if reenter { + f = f.Transition("loading").After(5 * time.Second).On("redo").GoTo("loading").Reenter() + } else { + f = f.Transition("loading").After(5 * time.Second).On("timeout").GoTo("timedOut") + } + return f.Quench() +} + +// timerSvcRun starts an instance of timerSvcMachine, fires prep and begin, so loading's +// service is in flight, and Ticks its after timer, failing unless the timer fired. +// Every third step checkpoints, so the Tick's Record carries a checkpoint and anything +// recorded after it follows the checkpoint. +func timerSvcRun(t *testing.T, reenter bool) (*durable.Handle[string, string, svcCtx], *state.Machine[string, string, svcCtx], *durable.MemStore, []durable.Option[string, string, svcCtx], *int64) { + t.Helper() + ctx := context.Background() + runs := new(int64) + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + return atomic.AddInt64(runs, 1), nil + } + m := timerSvcMachine(fn, reenter) + clk := state.NewFakeClock(epoch) + store := durable.NewMemStore() + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + durable.WithCheckpointEvery[string, string, svcCtx](3), + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, "t-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for _, ev := range []string{"prep", "begin"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire %s: %v", ev, err) + } + } + clk.Advance(6 * time.Second) + if results, terr := h.Tick(ctx); terr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v; want the timer to fire", len(results), terr) + } + if ckpt, recs, lerr := store.Load(ctx, "t-1"); lerr != nil || len(ckpt) == 0 || len(recs) != 0 { + t.Fatalf("after the Tick the store holds a %d-byte checkpoint and %d Records (%v); want the Tick's checkpoint and nothing after it", len(ckpt), len(recs), lerr) + } + return h, m, store, opts, runs +} + +// TestTimerLeavingTheState_SettleAfterCheckpointStaysRecoverable: loading's service is +// in flight, its after timer leaves for timedOut, the Tick's Record carries a +// checkpoint, which holds only the services of the states the instance is in, and the +// live Handle then calls RunService. While Tick left the service in flight, that ran it +// and journaled its settle after the checkpoint, which replay couldn't apply ("no +// in-flight service to settle"), so every Recover failed. Now the timer stopped the +// service: RunService finds nothing in flight, records nothing, and every Recover +// succeeds. +func TestTimerLeavingTheState_SettleAfterCheckpointStaysRecoverable(t *testing.T) { + ctx := context.Background() + h, m, store, opts, runs := timerSvcRun(t, false) + _, ran, rerr := h.RunService(ctx, timerSvc) + for i := range 2 { + rh, err := durable.Recover(ctx, m, store, "t-1", opts...) + if err != nil { + t.Fatalf("Recover %d: %v; want the instance recoverable", i, err) + } + if got := rh.Instance().Current(); got != "timedOut" { + t.Fatalf("Recover %d in %q, want timedOut", i, got) + } + if _, hran, herr := rh.RunService(ctx, timerSvc); hran || herr != nil { + t.Fatalf("RunService after Recover %d = %v, %v; want nothing in flight", i, hran, herr) + } + } + if ran || rerr != nil || atomic.LoadInt64(runs) != 0 { + t.Fatalf("live RunService after the Tick = %v, %v with the ServiceFn run %d times; want nothing in flight: the timer stopped the service", ran, rerr, atomic.LoadInt64(runs)) + } +} + +// TestTimerReenteringTheState_SettleAfterCheckpointRunsTheFreshActivation: the timer +// re-enters loading, so the Tick stops the old activation and starts a fresh one, and +// the checkpoint the Tick's Record carries holds it in flight. RunService on the live +// Handle runs it, and a Recover after that settle, which follows the checkpoint, replays +// it and ends in ready, as live did, with the ServiceFn run once. +func TestTimerReenteringTheState_SettleAfterCheckpointRunsTheFreshActivation(t *testing.T) { + ctx := context.Background() + h, m, store, opts, runs := timerSvcRun(t, true) + if _, ran, err := h.RunService(ctx, timerSvc); !ran || err != nil { + t.Fatalf("live RunService after the Tick = %v, %v; want the fresh activation run and settled", ran, err) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("live in %q, want ready", got) + } + rh, err := durable.Recover(ctx, m, store, "t-1", opts...) + if err != nil { + t.Fatalf("Recover after the settle: %v; want the instance recoverable", err) + } + if got := rh.Instance().Current(); got != "ready" { + t.Fatalf("recovered in %q, want ready, as live", got) + } + if _, ran, rerr := rh.RunService(ctx, timerSvc); ran || rerr != nil { + t.Fatalf("RunService after Recover = %v, %v; want nothing in flight", ran, rerr) + } + if got := atomic.LoadInt64(runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want once", got) + } +} diff --git a/durable/unmarshalable_effect_test.go b/durable/unmarshalable_effect_test.go new file mode 100644 index 00000000..f3823c3c --- /dev/null +++ b/durable/unmarshalable_effect_test.go @@ -0,0 +1,289 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// badEffect is a KindedEffect with no JSON form: encoding/json can't encode a chan. +type badEffect struct { + Done chan struct{} `json:"done"` +} + +func (badEffect) Kind() string { return "demo.bad" } + +func emitBad[C any](state.ActionCtx[C]) (state.Effect, error) { + return badEffect{Done: make(chan struct{})}, nil +} + +// badEffectMachine emits a badEffect on "go", on the timer that follows, and on the +// settle of the service "loading" invokes, so each kind of step can emit one. +func badEffectMachine(fn state.ServiceFn[svcCtx]) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("bad"). + Service("fetch", fn). + Action("bad", emitBad[svcCtx]). + State("idle"). + State("waiting"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("done").Final(). + Initial("idle"). + Transition("idle").On("go").GoTo("done").Do("bad"). + Transition("idle").On("wait").GoTo("waiting"). + Transition("waiting").After(time.Second).GoTo("done").Do("bad"). + Transition("idle").On("load").GoTo("loading"). + Transition("loading").On("ok").GoTo("done").Do("bad"). + Quench() +} + +// badRun is a Runner set up for badEffectMachine with no effect handler, and the count +// of ServiceFn runs. +type badRun struct { + m *state.Machine[string, string, svcCtx] + store *durable.MemStore + clk *state.FakeClock + opts []durable.Option[string, string, svcCtx] + runs *int64 +} + +func newBadRun() *badRun { + runs := new(int64) + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + atomic.AddInt64(runs, 1) + return "ok", nil + } + clk := state.NewFakeClock(epoch) + return &badRun{ + m: badEffectMachine(fn), + store: durable.NewMemStore(), + clk: clk, + runs: runs, + opts: []durable.Option[string, string, svcCtx]{ + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + durable.WithRunnerClock[string, string, svcCtx](clk), + }, + } +} + +func (b *badRun) start(t *testing.T) *durable.Handle[string, string, svcCtx] { + t.Helper() + h, err := durable.NewRunner(b.m, b.store, b.opts...).Start(context.Background(), "bad-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + return h +} + +func (b *badRun) recover(t *testing.T) *durable.Handle[string, string, svcCtx] { + t.Helper() + h, err := durable.Recover(context.Background(), b.m, b.store, "bad-1", b.opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + return h +} + +// metaMarshalError is the EffectEnvelope.Meta key that holds why an effect's payload is +// missing. +const metaMarshalError = "crucible.marshalError" + +// mustRecordBadByIDAndKind fails unless the journal's Record at step names the +// badEffect it emitted by id and kind, with no payload and its marshal error in Meta. +func mustRecordBadByIDAndKind(t *testing.T, st *durable.MemStore, id durable.InstanceID, step int) { + t.Helper() + _, recs, err := st.Load(context.Background(), id) + if err != nil { + t.Fatalf("Load: %v", err) + } + for _, rec := range recs { + if rec.Step != step { + continue + } + if len(rec.Effects) != 1 { + t.Fatalf("step %d records %d effects, want the badEffect", step, len(rec.Effects)) + } + env := rec.Effects[0] + wantID := fmt.Sprintf("%d#0#demo.bad", step) + if env.Kind != "demo.bad" || env.EffectID != wantID || len(env.Payload) != 0 { + t.Fatalf("step %d records %+v, want kind demo.bad, id %s and no payload", step, env, wantID) + } + if msg, _ := env.Meta[metaMarshalError].(string); !strings.Contains(msg, "unsupported type") { + t.Fatalf("step %d Meta = %v, want the marshal error under %q", step, env.Meta, metaMarshalError) + } + return + } + t.Fatalf("no Record at step %d", step) +} + +// TestUnmarshalableEffect_NoHandler_RecordsByIDAndKind: with no WithEffectHandler wired, +// a step that emits a KindedEffect with no JSON form records it by id and kind, as an +// effect that isn't a KindedEffect is, with its marshal error in Meta, and succeeds, +// whatever the step: Fire, a Tick's timer, a RunService's settle, or the stateless +// Runner.Fire. On main a Fire failed this way; a Tick and a RunService didn't, since +// they recorded no effects. The ServiceFn runs once. +func TestUnmarshalableEffect_NoHandler_RecordsByIDAndKind(t *testing.T) { + ctx := context.Background() + t.Run("Fire", func(t *testing.T) { + b := newBadRun() + if _, err := b.start(t).Fire(ctx, "go"); err != nil { + t.Fatalf("Fire: %v", err) + } + mustRecordBadByIDAndKind(t, b.store, "bad-1", 0) + if got := b.recover(t).Instance().Current(); got != "done" { + t.Fatalf("recovered in %q, want done", got) + } + }) + t.Run("stateless Fire", func(t *testing.T) { + b := newBadRun() + b.start(t) + if _, err := durable.NewRunner(b.m, b.store, b.opts...).Fire(ctx, "bad-1", "go"); err != nil { + t.Fatalf("Runner.Fire: %v", err) + } + mustRecordBadByIDAndKind(t, b.store, "bad-1", 0) + }) + t.Run("Tick", func(t *testing.T) { + b := newBadRun() + if _, err := b.start(t).Fire(ctx, "wait"); err != nil { + t.Fatalf("Fire wait: %v", err) + } + b.clk.Advance(2 * time.Second) + if _, err := b.recover(t).Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + mustRecordBadByIDAndKind(t, b.store, "bad-1", 1) + if got := b.recover(t).Instance().Current(); got != "done" { + t.Fatalf("recovered in %q, want done", got) + } + }) + t.Run("RunService", func(t *testing.T) { + b := newBadRun() + if _, err := b.start(t).Fire(ctx, "load"); err != nil { + t.Fatalf("Fire load: %v", err) + } + if _, ran, err := b.recover(t).RunService(ctx, state.InvokeID("bad", "loading", 0)); !ran || err != nil { + t.Fatalf("RunService = %v, %v; want ran", ran, err) + } + mustRecordBadByIDAndKind(t, b.store, "bad-1", 1) + if got := b.recover(t).Instance().Current(); got != "done" { + t.Fatalf("recovered in %q, want done", got) + } + if got := atomic.LoadInt64(b.runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } + }) +} + +// badSteps drives b's instance to emit a badEffect through each kind of step, and +// names the effect id each records: Fire, a Tick's timer, a RunService's settle, and +// the stateless Runner.Fire. +var badSteps = []struct { + name string + id string + run func(t *testing.T, b *badRun) error +}{ + {"Fire", "0#0#demo.bad", func(t *testing.T, b *badRun) error { + _, err := b.start(t).Fire(context.Background(), "go") + return err + }}, + {"stateless Fire", "0#0#demo.bad", func(t *testing.T, b *badRun) error { + b.start(t) + _, err := durable.NewRunner(b.m, b.store, b.opts...).Fire(context.Background(), "bad-1", "go") + return err + }}, + {"Tick", "1#0#demo.bad", func(t *testing.T, b *badRun) error { + h := b.start(t) + if _, err := h.Fire(context.Background(), "wait"); err != nil { + t.Fatalf("Fire wait: %v", err) + } + b.clk.Advance(2 * time.Second) + _, err := h.Tick(context.Background()) + return err + }}, + {"RunService", "1#0#demo.bad", func(t *testing.T, b *badRun) error { + h := b.start(t) + if _, err := h.Fire(context.Background(), "load"); err != nil { + t.Fatalf("Fire load: %v", err) + } + _, _, err := h.RunService(context.Background(), state.InvokeID("bad", "loading", 0)) + return err + }}, +} + +// TestUnmarshalableEffect_HandlerAppliesItLiveOnce: with a handler wired, the effect +// reaches it once, live, as the value the action emitted, on every kind of step. +func TestUnmarshalableEffect_HandlerAppliesItLiveOnce(t *testing.T) { + for _, step := range badSteps { + t.Run(step.name, func(t *testing.T) { + b := newBadRun() + rec := newEffectRecorder() + b.opts = append(b.opts, durable.WithEffectHandler[string, string, svcCtx](rec.handler())) + if err := step.run(t, b); err != nil { + t.Fatalf("step: %v", err) + } + b.recover(t) + if n := rec.count(step.id); n != 1 || rec.totalApplies() != 1 { + t.Fatalf("the handler applied %s %d times (%d in all), want once", step.id, n, rec.totalApplies()) + } + if _, ok := rec.values[0].(badEffect); !ok { + t.Fatalf("the handler got %T, want the badEffect", rec.values[0]) + } + }) + } +} + +// TestUnmarshalableEffect_RecoverRetriesItOnce: with a handler wired, an effect whose +// dispatch failed live is applied once by Recover, however often it recovers. +func TestUnmarshalableEffect_RecoverRetriesItOnce(t *testing.T) { + for _, step := range badSteps { + t.Run(step.name, func(t *testing.T) { + b := newBadRun() + live := newEffectRecorder() + live.failKinds["demo.bad"] = errors.New("downstream unavailable") + opts := b.opts + b.opts = append(opts, durable.WithEffectHandler[string, string, svcCtx](live.handler())) + if err := step.run(t, b); !errors.Is(err, durable.ErrEffectDispatch) { + t.Fatalf("step: %v, want ErrEffectDispatch", err) + } + healthy := newEffectRecorder() + b.opts = append(opts, durable.WithEffectHandler[string, string, svcCtx](healthy.handler())) + b.recover(t) + b.recover(t) + if n := healthy.count(step.id); n != 1 || healthy.totalApplies() != 1 { + t.Fatalf("Recover applied %s %d times (%d in all), want once", step.id, n, healthy.totalApplies()) + } + if _, ok := healthy.values[0].(badEffect); !ok { + t.Fatalf("Recover's handler got %T, want the badEffect", healthy.values[0]) + } + if got := atomic.LoadInt64(b.runs); got > 1 { + t.Fatalf("the ServiceFn ran %d times, want at most 1", got) + } + }) + } +} + +// TestUnmarshalableEffect_HandlerWiredOnlyAtRecoverSeesIt: a handler wired only at +// Recover applies the effect a step recorded with no handler wired, once. +func TestUnmarshalableEffect_HandlerWiredOnlyAtRecoverSeesIt(t *testing.T) { + for _, step := range badSteps { + t.Run(step.name, func(t *testing.T) { + b := newBadRun() + if err := step.run(t, b); err != nil { + t.Fatalf("step: %v", err) + } + rec := newEffectRecorder() + b.opts = append(b.opts, durable.WithEffectHandler[string, string, svcCtx](rec.handler())) + b.recover(t) + b.recover(t) + if n := rec.count(step.id); n != 1 || rec.totalApplies() != 1 { + t.Fatalf("the Recover-only handler applied %s %d times (%d in all), want once", step.id, n, rec.totalApplies()) + } + }) + } +} diff --git a/examples/fooddelivery/fooddelivery.go b/examples/fooddelivery/fooddelivery.go index f7b50b8b..9c005ae0 100644 --- a/examples/fooddelivery/fooddelivery.go +++ b/examples/fooddelivery/fooddelivery.go @@ -388,10 +388,17 @@ func settleReducer(in state.AssignCtx[Order]) Order { // onDone event's payload — the saga's compensation made observable. func recordRefund(in state.AssignCtx[Order]) Order { c := in.Entity - if amount, ok := in.Event.(int64); ok { - c.Refund = amount - c.Log = append(c.Log, fmt.Sprintf("refunded:%d", amount)) + var amount int64 + switch v := in.Event.(type) { + case int64: + amount = v + case float64: // a durable Runner delivers a service result JSON-decoded + amount = int64(v) + default: + return c } + c.Refund = amount + c.Log = append(c.Log, fmt.Sprintf("refunded:%d", amount)) return c } diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 6617e6a6..632deef1 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -36,6 +36,10 @@ counts as an additive (minor) versus breaking (major) change. Use the 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. +- **`ServiceRunner.WithResultTransform`** rewrites a service's outcome before `Tick` + settles it, so a host that records outcomes can give the live run what a replay will see. + An unbound service still settles through onError: a transform that returns no error for + its `UnboundRefError` doesn't make it succeed. - **`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 diff --git a/state/result_transform_test.go b/state/result_transform_test.go new file mode 100644 index 00000000..71d81fa5 --- /dev/null +++ b/state/result_transform_test.go @@ -0,0 +1,74 @@ +package state_test + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestWithResultTransform_RewritesTheOutcomeTickSettles proves Tick settles a bound +// service with the transform's outcome, a result or an error, and that LastResult and +// LastError report the rewritten form. +func TestWithResultTransform_RewritesTheOutcomeTickSettles(t *testing.T) { + ctx := context.Background() + upper := func(result any, err error) (any, error) { + if err != nil { + return nil, errors.New("wrapped: " + err.Error()) + } + return strings.ToUpper(result.(string)), nil + } + cases := []struct { + name string + fn state.ServiceFn[*trec] + wantState string + wantNotes string + }{ + {"result", func(context.Context, state.ServiceCtx[*trec]) (any, error) { return "payload", nil }, "ready", "result:PAYLOAD"}, + {"error", func(context.Context, state.ServiceCtx[*trec]) (any, error) { return nil, errors.New("boom") }, "errored", "error:wrapped: boom"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var run *state.ServiceRunner[string, string, *trec] + m := invokeMachine(&run) + entity := &trec{} + inst := m.Cast(entity, state.WithInitialState("idle")) + run = state.NewServiceRunner(inst, state.NewRegistry[*trec]().Service("fetch", tc.fn)).WithResultTransform(upper) + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + res := run.Tick(ctx, state.InvokeID("loader", "loading", 0)) + if len(res) != 1 || res[0].NewState != tc.wantState { + t.Fatalf("Tick settled to %+v, want %q", res, tc.wantState) + } + if got := join(entity.notes); got != tc.wantNotes { + t.Fatalf("notes = %q, want %q", got, tc.wantNotes) + } + }) + } +} + +// TestWithResultTransform_UnboundServiceStillRoutesOnError proves a transform can't +// turn an unbound service into a success: a transform that returns a result and no +// error for the UnboundRefError still settles the service through onError, with the +// UnboundRefError. +func TestWithResultTransform_UnboundServiceStillRoutesOnError(t *testing.T) { + ctx := context.Background() + var run *state.ServiceRunner[string, string, *trec] + m := invokeMachine(&run) + entity := &trec{} + inst := m.Cast(entity, state.WithInitialState("idle")) + // A nil registry leaves "fetch" unbound. + run = state.NewServiceRunner(inst, nil).WithResultTransform(func(any, error) (any, error) { + return "fallback", nil + }) + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + res := run.Tick(ctx, state.InvokeID("loader", "loading", 0)) + if len(res) != 1 || res[0].NewState != "errored" { + t.Fatalf("an unbound service settled to %+v, want onError's errored", res) + } + var unbound *state.UnboundRefError + if !errors.As(run.LastError(), &unbound) { + t.Fatalf("LastError = %v, want the UnboundRefError", run.LastError()) + } +} diff --git a/state/runner.go b/state/runner.go index 699ebeb7..504c078f 100644 --- a/state/runner.go +++ b/state/runner.go @@ -97,6 +97,9 @@ type ServiceRunner[S comparable, E comparable, C any] struct { // transition's action. It is atomic so a concurrent reader sees a consistent // snapshot. lastResult atomic.Value // serviceOutcome + + // transform, when set, rewrites a ServiceFn's outcome before Tick settles it. + transform func(any, error) (any, error) } // serviceOutcome is the result/error pair a settled service exposes through @@ -217,6 +220,18 @@ func (r *ServiceRunner[S, E, C]) settle(ctx context.Context, id string, result a return res, true } +// WithResultTransform sets a function that rewrites a ServiceFn's outcome before Tick +// settles it, and returns the runner. A host that records outcomes uses it to give the +// live run the form a replay will see. LastResult and LastError then report the rewritten +// outcome. It also runs on an UnboundRefError, where only a non-nil returned error is +// used: a nil one leaves the UnboundRefError, so the service still settles through onError. It +// doesn't apply to SettleDone or SettleError, which take the outcome as given. Set it +// before the first Tick: the field isn't guarded. +func (r *ServiceRunner[S, E, C]) WithResultTransform(f func(result any, err error) (any, error)) *ServiceRunner[S, E, C] { + r.transform = f + return r +} + // Tick resolves and runs the in-flight service id against the bound registry, // settling it with the ServiceFn's result or error. It is the ServiceRunner's // advance verb — the host-driver counterpart of Scheduler.Tick and @@ -237,10 +252,21 @@ func (r *ServiceRunner[S, E, C]) Tick(ctx context.Context, id string) []FireResu } fn := r.resolve(rs.src.Name) if fn == nil { - res, _ := r.SettleError(ctx, id, &UnboundRefError{Kind: "service", Name: rs.src.Name}) + var err error = &UnboundRefError{Kind: "service", Name: rs.src.Name} + if r.transform != nil { + // An unbound service always settles as an error: a transform that returns + // no error can't turn it into a success. + if _, terr := r.transform(nil, err); terr != nil { + err = terr + } + } + res, _ := r.SettleError(ctx, id, err) return []FireResult[S]{res} } out, err := fn(ctx, ServiceCtx[C]{Entity: r.inst.entity, Params: rs.src.Params, Input: rs.input}) + if r.transform != nil { + out, err = r.transform(out, err) + } if err != nil { res, _ := r.SettleError(ctx, id, err) return []FireResult[S]{res}