From 0f578e910f8c924d4b509fedd5287b3b0c0d5756 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 5 Nov 2026 09:18:22 -0700 Subject: [PATCH 01/38] fix(durable): don't journal a step whose context ended partway A context ended during RunService, Tick or DeliverToActor stops the kernel's Fire, but the result was journaled anyway. Recovery then committed something the live instance never applied, or for an actor, failed on every attempt. Each now returns ErrHandleFailed and records nothing. Recover and StateAt fail on a canceled context instead of returning state short of the journal. Relates to #214. Signed-off-by: Ray Karnes --- docs/src/content/docs/durable/overview.md | 26 +-- durable/CHANGELOG.md | 7 + durable/README.md | 26 +-- durable/actor.go | 44 ++--- durable/actor_test.go | 42 +++++ durable/doc.go | 23 +-- durable/errors.go | 7 +- durable/runner.go | 50 ++++-- durable/runner_options.go | 18 +- durable/service.go | 45 +++-- durable/service_test.go | 201 ++++++++++++++++++++++ durable/timetravel.go | 12 +- 12 files changed, 400 insertions(+), 101 deletions(-) diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index 15ea16e8..25d9d2bc 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -72,8 +72,8 @@ the first time, and replayed verbatim on recovery: | Seam | Wire with | Recorded as | | --- | --- | --- | | **Clock** (timers) | `WithRunnerClock` | `JournalClockRead`, replayed so timers fire at the same recorded instants, wall-clock-independent; armed deadlines survive checkpoint compaction | -| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; the service runs once, then recovery replays its result through the kernel's settle seam | -| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; the behavior runs once, then recovery re-fires the recorded parent transition | +| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; a recorded result replays through the kernel's settle seam without re-running the service, and an unrecorded one (a context canceled during the service, a failed `Append`, a crash) runs again when the host calls `RunService` | +| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled actor doesn't re-run, and a running one restarts from its initial state on any `Recover` | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written: a @@ -140,16 +140,18 @@ context not derived from the step's. A step waiting for the lock stops when its ends. Read the instance with `View`, which takes the lock; `Instance()` is outside it. -A step that may not have been recorded fails the Handle with `ErrHandleFailed`. So does an -effect handler that returns an error or panics. Before `Recover`, call `Handle.Drain`, -which waits until no step of the failed Handle is still recording and no effect is still -being sent, so the recovered Handle loads every recorded step and can't send an effect -twice. Give `Drain` a context of its own, not the failed call's, and don't `Recover` -until it returns nil: an error means it didn't finish draining. A step that was recording when another goroutine failed the Handle returns -`ErrHandleFailed` saying it was recorded; `Recover` sends any of its effects. To move a healthy Handle's instance to a new Handle, stop -calling the old one and let its calls return first: a step can start after `Drain` -returns. `Recover` a new Handle with the same options to continue, unless the cause is `ErrFenced`: then a newer owner holds the -instance, so stop. +A step that may not have been recorded, or a `Tick`, `RunService` or `DeliverToActor` whose +context ended partway, fails the Handle with `ErrHandleFailed`. So does an effect handler +that returns an error or panics. Before `Recover`, call `Handle.Drain`, which waits until no +step of the failed Handle is still recording and no effect is still being sent, so the +recovered Handle loads every recorded step and can't send an effect twice. Give `Drain` a +context of its own, not the failed call's, and don't `Recover` until it returns nil: an +error means it didn't finish draining. A step that was recording when another goroutine +failed the Handle returns `ErrHandleFailed` saying it was recorded; `Recover` sends any of +its effects. To move a healthy Handle's instance to a new Handle, stop calling the old one +and let its calls return first: a step can start after `Drain` returns. `Recover` a new +Handle with the same options to continue, unless the cause is `ErrFenced`: then a newer +owner holds the instance, so stop. ## A note on serialized payloads diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 08003135..5eeba18a 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -116,6 +116,13 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. the step that tried it. A retry the Store refuses as not advancing means the first write landed, and counts as written. Any other checkpoint failure is returned, and after that only the next step the policy makes due tries again. +- **A step whose context ended partway isn't journaled.** A canceled `RunService`, `Tick` + or `DeliverToActor` used to record a result the live instance never applied, which + recovery then committed, or for an actor, failed on. Each now returns `ErrHandleFailed` + wrapping the error and records nothing. After `Recover` the service stays in flight and + must tolerate running again, the timer is re-armed, and the actor restarts. `Recover` + and `StateAt` now fail on a canceled context, rather than returning state short of the + journal. - **The next step survives a checkpoint that compacts tick barriers.** A checkpoint now records the step that follows it, in a `nextStep` field of its envelope. Recovery used the Trace count, which runs low past a tick barrier, so the next Fire could reuse a diff --git a/durable/README.md b/durable/README.md index 4f113340..d4c399db 100644 --- a/durable/README.md +++ b/durable/README.md @@ -82,8 +82,8 @@ the first time, and replayed verbatim on recovery: | Seam | Wire with | Recorded as | | --- | --- | --- | | **Clock** (timers) | `WithRunnerClock` | `JournalClockRead`, replayed so timers fire at the same recorded instants, wall-clock-independent; armed deadlines survive checkpoint compaction | -| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; the service runs once, then recovery replays its result through the kernel's settle seam | -| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; the behavior runs once, then recovery re-fires the recorded parent transition | +| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; a recorded result replays through the kernel's settle seam without re-running the service, and an unrecorded one (a context canceled during the service, a failed `Append`, a crash) runs again when the host calls `RunService` | +| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled actor doesn't re-run, and a running one restarts from its initial state on any `Recover` | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written (a @@ -151,16 +151,18 @@ context not derived from the step's. A step waiting for the lock stops when its ends. Read the instance with `View`, which takes the lock; `Instance()` is outside it. -A step that may not have been recorded fails the Handle with `ErrHandleFailed`. So does an -effect handler that returns an error or panics. Before `Recover`, call `Handle.Drain`, -which waits until no step of the failed Handle is still recording and no effect is still -being sent, so the recovered Handle loads every recorded step and can't send an effect -twice. Give `Drain` a context of its own, not the failed call's, and don't `Recover` -until it returns nil: an error means it didn't finish draining. A step that was recording when another goroutine failed the Handle returns -`ErrHandleFailed` saying it was recorded; `Recover` sends any of its effects. To move a healthy Handle's instance to a new Handle, stop -calling the old one and let its calls return first: a step can start after `Drain` -returns. `Recover` a new Handle with the same options to continue, unless the cause is `ErrFenced`: then a newer owner holds the -instance, so stop. +A step that may not have been recorded, or a `Tick`, `RunService` or `DeliverToActor` whose +context ended partway, fails the Handle with `ErrHandleFailed`. So does an effect handler +that returns an error or panics. Before `Recover`, call `Handle.Drain`, which waits until no +step of the failed Handle is still recording and no effect is still being sent, so the +recovered Handle loads every recorded step and can't send an effect twice. Give `Drain` a +context of its own, not the failed call's, and don't `Recover` until it returns nil: an +error means it didn't finish draining. A step that was recording when another goroutine +failed the Handle returns `ErrHandleFailed` saying it was recorded; `Recover` sends any of +its effects. To move a healthy Handle's instance to a new Handle, stop calling the old one +and let its calls return first: a step can start after `Drain` returns. `Recover` a new +Handle with the same options to continue, unless the cause is `ErrFenced`: then a newer +owner holds the instance, so stop. ## Caveat: serialized payloads diff --git a/durable/actor.go b/durable/actor.go index 496a2878..df444d6a 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -17,15 +17,14 @@ import ( // NOT a pure function of (configuration, context, event payload, machine // definition) and MUST be recorded to reproduce a run. // -// # Run exactly once, replay the result +// # Run once per recorded result, replay the result // -// A durable actor's behavior runs exactly once, on the live path, and the result -// it routes into the parent is recorded; on recovery the recorded result is -// replayed back through the SAME parent transition the live run drove, and the -// actor behavior is NEVER re-instantiated. This is the standard durable-execution -// guarantee: the child machine (with its side effects and its nondeterministic -// output) runs once, and recovery is a pure replay against the parent kernel rather -// than a re-execution of the actor tree. +// A durable actor's behavior runs on the live path and the result it routes into the +// parent is recorded; on recovery the recorded result is replayed back through the SAME +// parent transition the live run drove, so a settled actor never re-runs. This is the +// standard durable-execution guarantee: recovery is a pure replay against the parent +// kernel rather than a re-execution of the actor tree. An actor still running at recovery +// restarts from its initial state, because its own state isn't journaled. // // The Runner wraps the kernel's reusable host driver, state.ActorSystem, which // turns SpawnActor / StopActor effects into running child actors, owns each actor's @@ -90,25 +89,23 @@ type actorMessagePayload struct { HasData bool `json:"hasData,omitempty"` } -// DeliverToActor routes event into the running actor identified by ref exactly -// once, runs the actor (settling it when it reaches its final state), records each +// DeliverToActor routes event into the running actor identified by ref, runs the actor (settling it when it reaches its final state), records each // parent transition the delivery drove, and persists the produced step. The actor // behavior is resolved and run against the palette supplied with WithActorPalette; // the done-data, error, or parent-driving message it routes is journaled as a // JournalActorMessage correlated by the actor id so recovery replays it without // re-instantiating the actor. // -// It returns false for a ref that names no live actor (already settled, stopped, or -// never spawned), and false with the error when the Handle had already failed or ctx -// has ended. If the actor received the event but the delivery couldn't be recorded or -// appended, it returns true and ErrHandleFailed: the Handle has failed. If another -// goroutine failed the Handle while this step was recording, it returns true and -// ErrHandleFailed saying the step was recorded. A failed checkpoint returns true and -// that error, and the Handle carries on. The kernel -// transitions the delivery drove do not themselves fail. When a delivery wasn't -// recorded, on a recovered Handle an InvokeActor actor restarts from its initial state, -// and a Spawn actor doesn't return. Resending a recorded delivery repeats -// any message it sends the parent. +// It returns whether the actor was found running: false for a ref that names no live +// actor (already settled, stopped, or never spawned), or false and an error when no +// palette is wired, the Handle has failed, or ctx ended before the delivery. Once the +// actor ran it returns true with any error. A failed Append, a result that won't encode, +// or a ctx that ended during the delivery returns ErrHandleFailed and records nothing: on +// a recovered Handle an InvokeActor actor restarts from its initial state, and a Spawn +// actor doesn't return. If another goroutine failed the Handle while this step was +// recording, it returns true and ErrHandleFailed saying the step was recorded. A failed +// Checkpoint returns the plain error, and the delivery is recorded. Resending a recorded +// delivery repeats any message it sends the parent. func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef, event any) (bool, error) { if err := h.acquire(ctx); err != nil { return false, err @@ -126,6 +123,11 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef if !delivered { return false, nil } + // A context that ended during the delivery can stop a parent Fire partway, and a + // refused Fire leaves a Trace replay can't re-fire. Record nothing. + if err := ctx.Err(); err != nil { + return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) + } output, settled, settleErr := h.actorOutcome() entries, err := recordActorTransitions(ref.ID, h.inst.History(), before, output, settled, settleErr) diff --git a/durable/actor_test.go b/durable/actor_test.go index f8af0cd5..ef3cd6f5 100644 --- a/durable/actor_test.go +++ b/durable/actor_test.go @@ -2,6 +2,7 @@ package durable_test import ( "context" + "errors" "fmt" "sync/atomic" "testing" @@ -704,3 +705,44 @@ func TestActor_Determinism(t *testing.T) { t.Fatalf("two live runs diverged:\n run1=%s\n run2=%s", s1, s2) } } + +// TestDeliverToActor_ContextEndedPartway_RecordsNothing proves a delivery whose context +// ended records nothing, so every later Recover still works. +func TestDeliverToActor_ContextEndedPartway_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := supervisorMachine() + store := durable.NewMemStore() + id := durable.InstanceID("sup-cancel") + turn, cancel := context.WithCancel(ctx) + defer cancel() + behavior := func(map[string]any) (state.ActorInstance, error) { + child := state.ForgeFor[actorCtx]("child"). + State("working"). + State("done").Final(). + Initial("working"). + Transition("working").On("finish").GoTo("done"). + Quench() + inst := child.Cast(actorCtx{}, state.WithInitialState[string]("working")) + return state.NewActor(inst, func(*state.Instance[string, string, actorCtx]) any { + cancel() // the turn ends after the child finishes, before the parent settles + return "late" + }), nil + } + opts := []durable.Option[string, string, actorCtx]{ + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{"spawnChild": behavior}), + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for spawned child") + } + if _, err = h.DeliverToActor(turn, ref, "finish"); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("DeliverToActor = %v, want ErrHandleFailed", err) + } + if _, err = durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("Recover: %v", err) + } +} diff --git a/durable/doc.go b/durable/doc.go index 2a0bff56..1d98c5bf 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -99,17 +99,18 @@ // was compacted out of the tail is re-armed from its persisted deadline rather // than lost. // -// Invoked services (WithServiceRegistry): a service (`invoke`) runs exactly once -// on the live path; its result is journaled as a JournalServiceResult. On -// recovery the recorded result is replayed back through the same kernel settle -// seam — the service is never re-invoked and the same onDone or onError event -// re-fires with the same data. -// -// Child-machine actors (WithActorPalette): an actor's behavior runs exactly once -// on the live path; each parent transition the delivery drives is journaled as a -// JournalActorMessage. On recovery the recorded transition is re-fired directly -// through the parent with the recorded done-data — the actor behavior is never -// re-instantiated. +// Invoked services (WithServiceRegistry): a service (`invoke`) runs on the live path; +// its result is journaled as a JournalServiceResult. On recovery the recorded result is +// replayed back through the same kernel settle seam — that service is never re-invoked +// and the same onDone or onError event re-fires with the same data. A result that +// wasn't recorded has nothing to replay, so the service runs again when the host calls +// RunService. +// +// Child-machine actors (WithActorPalette): an actor's behavior runs on the live path; +// each parent transition the delivery drives is journaled as a JournalActorMessage. On +// recovery the recorded transition is re-fired directly through the parent with the +// recorded done-data, so a settled actor never re-runs. An actor still running at +// recovery restarts from its initial state, because its own state isn't journaled. // // # Idempotent effect dispatch // diff --git a/durable/errors.go b/durable/errors.go index 111a4bd7..4342dd1e 100644 --- a/durable/errors.go +++ b/durable/errors.go @@ -57,9 +57,10 @@ var ( // ErrHandleFailed is reported by a Handle's Fire, Tick, RunService, DeliverToActor // and View once a step applied to the live instance but may not have been recorded, - // or an effect handler failed, on that call and every later one. It wraps the cause. - // Call Handle.Drain, then Recover a new Handle with the same options to continue, - // unless the cause is ErrFenced: then a newer owner holds the instance, so stop. + // a Tick, RunService or DeliverToActor's context ended partway, or an effect handler + // failed, on that call and every later one. It wraps the cause. Call Handle.Drain, + // then Recover a new Handle with the same options to continue, unless the cause is + // ErrFenced: then a newer owner holds the instance, so stop. ErrHandleFailed = errors.New(errorPrefix + errorHandleFailed) // ErrReentrantStep is reported by a Handle's Fire, Tick, RunService, DeliverToActor diff --git a/durable/runner.go b/durable/runner.go index 6c4a71c5..090fb287 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -40,15 +40,16 @@ import ( // deadline or testing dueness — is journaled and returned verbatim on recovery, // making timer-driven transitions durable and replay wall-clock-independent. // -// Invoked services are the second recorded seam: a service runs exactly once on -// the live path (Handle.RunService, against the registry supplied with -// WithServiceRegistry) and its result is journaled as a JournalServiceResult; on -// recovery the recorded result is replayed back through the kernel's settle seam, -// so the service is never re-invoked and the same onDone / onError event re-fires -// with the same data. +// Invoked services are the second recorded seam: a service runs on the live path +// (Handle.RunService, against the registry supplied with WithServiceRegistry) and its +// result is journaled as a JournalServiceResult; on recovery the recorded result is +// replayed back through the kernel's settle seam, so that service is never re-invoked +// and the same onDone / onError event re-fires with the same data. A result that wasn't +// recorded has nothing to replay, so the service runs again when the host calls +// RunService. // // Child-machine actors are the third recorded seam: an actor's behavior runs -// exactly once on the live path (Handle.DeliverToActor, against the palette +// on the live path (Handle.DeliverToActor, against the palette // supplied with WithActorPalette) and each parent transition the delivery drives — // the actor's onDone / onError, or a message it sends — is journaled as a // JournalActorMessage; on recovery the recorded transition is replayed by re-firing @@ -101,13 +102,14 @@ func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st // lock; Instance returns it outside the lock. A stateless Runner.Fire builds its own // Handle, so it isn't serialized with this one. // -// A step that applied to the kernel but may not have been recorded leaves the Handle out -// of step with the journal. That call and every later one return ErrHandleFailed, -// wrapping the cause, which can be a context that ended during the Store write. Before -// recovering, call Drain: a step on another goroutine may still be recording, which a -// recovered Handle wouldn't load, or sending an effect, which it would send again. Recovering a healthy Handle's instance -// instead needs this Handle's calls to have returned first. Recover a new Handle with the same -// options to continue. A service +// A step that applied to the kernel but may not have been recorded, or a Tick, RunService +// or DeliverToActor whose context ended partway, leaves the Handle out of step with the +// journal. That call and every later one return ErrHandleFailed, wrapping the cause, +// which can be a context that ended during the Store write. Before recovering, call +// Drain: a step on another goroutine may still be recording, which a recovered Handle +// wouldn't load, or sending an effect, which it would send again. Recovering a healthy +// Handle's instance instead needs this Handle's calls to have returned first. Recover a +// new Handle with the same options to continue. A service // 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 @@ -749,6 +751,16 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro return nil, err } results := h.sched.Tick(h.stepContext(ctx)) + // A context that ended partway makes 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 timer. + if err := ctx.Err(); err != nil { + for i := range results { + if results[i].Err != nil { + return results, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, err)) + } + } + } step := h.nextStep rec := Record{Step: step, Tick: true, TickSteps: len(results), Entries: h.drainClock()} @@ -888,7 +900,7 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // snapshot (firing nothing, no IO), and replays the tail's recorded driving // events through the kernel to reach the instance's live state. The returned // Handle continues recording subsequent Fires. Recover reports ErrInstanceNotFound -// for an instance that was never started. +// for an instance that was never started, and the context's error if ctx ends. 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) @@ -959,6 +971,11 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S armed := map[string]pendingTimer{} for i := range tail { + // A canceled context can stop a replayed settle or tick with no error, leaving + // state short of the journal, so check it before each Record. + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } rec := &tail[i] switch { case hasActorEntry(rec): @@ -1107,6 +1124,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S } } } + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } return &Handle[S, E, C]{ runner: r, id: id, diff --git a/durable/runner_options.go b/durable/runner_options.go index 614afe83..b653c5e1 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -94,10 +94,10 @@ func WithRunnerClock[S comparable, E comparable, C any](c state.Clock) Option[S, } // WithServiceRegistry binds the invoked-service implementations the Runner runs on -// the live path and resolves on recovery. A durable service runs exactly once — -// live — and its result is recorded; on recovery the recorded result is replayed -// through the same settle seam and the service is never re-invoked, so the registry -// is consulted only to execute a service the first time. Supply it for any machine +// the live path and resolves on recovery. A durable service runs live and its result is +// recorded; on recovery the recorded result is replayed through the same settle seam and +// that service is never re-invoked, so the registry is consulted only to execute a +// service whose result isn't recorded. Supply it for any machine // that declares `invoke` states; a purely event-driven or timer-driven machine // needs none. The registry binds the same ServiceFns the machine declares, by name // (state.NewRegistry().Service(name, fn)). @@ -111,11 +111,11 @@ func WithServiceRegistry[S comparable, E comparable, C any](reg *state.Registry[ // WithActorPalette binds the child-machine actor behaviors the Runner spawns and // runs on the live path and resolves on recovery, keyed by the actor src name (the -// name passed to InvokeActor or the Spawn built-in). A durable actor's behavior -// runs exactly once — live — and its done-data, error, or parent-driving message is -// recorded; on recovery the recorded result is replayed back through the same parent -// transition and the behavior is never re-instantiated, so the palette is consulted -// only to run an actor the first time. Supply it for any machine that spawns child +// name passed to InvokeActor or the Spawn built-in). A durable actor's behavior runs +// live and its done-data, error, or parent-driving message is recorded; on recovery the +// recorded result is replayed back through the same parent transition and that behavior +// is never re-instantiated, so the palette is consulted only to run an actor whose +// result isn't recorded. Supply it for any machine that spawns child // actors; a machine that spawns none needs none. Each behavior is the actor-model // analog of a ServiceFn, registered by the same src name the machine declares. func WithActorPalette[S comparable, E comparable, C any](palette map[string]state.ActorBehavior) Option[S, E, C] { diff --git a/durable/service.go b/durable/service.go index 490f8b46..8fb06124 100644 --- a/durable/service.go +++ b/durable/service.go @@ -16,14 +16,15 @@ import ( // (configuration, context, event payload, machine definition) and MUST be recorded // to reproduce a run. // -// # Run exactly once, replay the result +// # Run once per recorded result, replay the result // -// A durable service runs exactly once, on the live path, and its result is -// recorded; on recovery the recorded result is replayed back through the same -// settle seam, and the service is NEVER re-invoked. This is the standard -// durable-execution guarantee: the external call (with its side effects and its -// nondeterministic output) happens once, and recovery is a pure replay against the -// kernel rather than a re-execution of the host's services. +// A durable service runs on the live path and its result is recorded; on recovery the +// recorded result is replayed back through the same settle seam, and that service is +// NEVER re-invoked. This is the standard durable-execution guarantee: recovery is a pure +// replay against the kernel rather than a re-execution of the host's services. A result +// that wasn't recorded, after a context canceled during the service, a failed Append or a +// crash, has nothing to replay, so it stays in flight, runs again when the host calls +// RunService, and must tolerate a second run. // // The Runner wraps the kernel's reusable host driver, state.ServiceRunner, which // turns StartService / StopService effects into real ServiceFn executions and @@ -75,7 +76,7 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { return out } -// RunService runs the in-flight invoked service identified by id exactly once, +// RunService runs the in-flight invoked service identified by id, // records its outcome, and settles it — firing the invocation's onDone (on // success) or onError (on failure) event through the durable instance and // recording the produced step. The service is resolved and executed against the @@ -84,14 +85,18 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { // re-invoking the service. // // It returns the routed FireResult and true, or the zero result and false when id -// names no in-flight service (already settled, stopped, or never started), or false -// and the error when the Handle had already failed or ctx has ended. If the service -// settled but its outcome couldn't be recorded or appended, it returns the result, -// true and ErrHandleFailed: the Handle has failed. If another goroutine failed the -// Handle while this step was recording, it returns the result, true and ErrHandleFailed -// saying the step was recorded. A failed checkpoint returns the result, true and that -// error, and the Handle carries on. A recovered Handle has an -// unrecorded service in flight again, and RunService runs it a second time. +// names no in-flight service (already settled, stopped, or never started). It returns +// false and an error when no registry is wired, the Handle has failed, or ctx ended +// before the service started. +// +// Once the service has run, it returns true with any error. A failed Append, a result +// that won't encode, or a ctx that ended during the service returns ErrHandleFailed and +// records nothing: a recovered Handle has the service in flight again, and RunService +// runs it a second time. If another goroutine failed the Handle while this step was +// recording, it returns the result, true and ErrHandleFailed saying the step was +// recorded. That error also matches the cause, so test ErrHandleFailed first: it alone +// means Recover is needed. A failed Checkpoint returns the plain error, and the result +// is recorded. func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.FireResult[S], bool, error) { if err := h.acquire(ctx); err != nil { return state.FireResult[S]{}, false, err @@ -113,6 +118,14 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire } res := results[0] + // A context canceled during the service stops the settle's Fire before it applies, + // so the instance never saw this result: journaling it would commit it on recovery. + // The runner has already dropped the service, so this Handle can't run it again; + // Recover re-arms it. + if res.Err != nil && ctx.Err() != nil { + return res, true, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, res.Err)) + } + // 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 diff --git a/durable/service_test.go b/durable/service_test.go index df1d4db8..bf4fb5f0 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -6,6 +6,7 @@ import ( "fmt" "sync/atomic" "testing" + "time" "github.com/stablekernel/crucible/durable" "github.com/stablekernel/crucible/state" @@ -470,3 +471,203 @@ func TestService_Determinism(t *testing.T) { t.Fatalf("two live runs diverged:\n run1=%s\n run2=%s", s1, s2) } } + +// TestService_ResultFromCanceledTurn_NotCommittedOnRecover proves a service result +// whose settle is canceled with the turn's context, and so never reaches the live +// instance, is not committed by recovery either. +func TestService_ResultFromCanceledTurn_NotCommittedOnRecover(t *testing.T) { + ctx := context.Background() + turnCtx, cancel := context.WithCancel(ctx) + defer cancel() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + cancel() // the turn's deadline passes while the call is in flight + return "late", nil + } + m := fetchMachine(fn) + store := durable.NewMemStore() + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + runner := durable.NewRunner(m, store, opts...) + h, err := runner.Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + _, _, _ = h.RunService(turnCtx, state.InvokeID("fetch", "loading", 0)) + + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + // Compare state, not bytes: live keeps the Trace of the refused settle. + if live, got := h.Instance().Current(), recovered.Instance().Current(); got != live || live != "loading" { + t.Fatalf("recovered %q, live %q, want both loading: the canceled turn's result was committed", got, live) + } + if notes := recovered.Instance().Entity().Notes; len(notes) != 0 { + t.Fatalf("recovered notes %v, want none", notes) + } +} + +// TestService_CanceledTurn_RecoverRerunsTheService proves the canceled result isn't +// journaled, the Handle refuses further steps, and a recovered Handle can run the +// service to completion. +func TestService_CanceledTurn_RecoverRerunsTheService(t *testing.T) { + ctx := context.Background() + turnCtx, cancel := context.WithCancel(ctx) + defer cancel() + calls := 0 + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + calls++ + cancel() + return "late", nil + } + m := fetchMachine(fn) + store := durable.NewMemStore() + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + invoke := state.InvokeID("fetch", "loading", 0) + if _, _, err = h.RunService(turnCtx, invoke); !errors.Is(err, context.Canceled) { + t.Fatalf("RunService = %v, want context.Canceled", err) + } + if _, err = h.Fire(ctx, "start"); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("Fire after the cancel = %v, want ErrHandleFailed", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ok, err := recovered.RunService(ctx, invoke); err != nil || !ok { + t.Fatalf("RunService after Recover = (%v, %v)", ok, err) + } + if calls != 2 { + t.Fatalf("service ran %d times, want 2", calls) + } +} + +// TestRecover_CanceledContext_DoesNotLoseARecordedResult proves a canceled Recover +// reports the cancellation rather than a Handle short of the journal. +func TestRecover_CanceledContext_DoesNotLoseARecordedResult(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchMachine(fn) + store := durable.NewMemStore() + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + mustRunService(t, h, state.InvokeID("fetch", "loading", 0)) + canceled, cancel := context.WithCancel(ctx) + cancel() + if _, err = durable.Recover(canceled, m, store, id, opts...); !errors.Is(err, context.Canceled) { + t.Fatalf("Recover = %v, want context.Canceled", err) + } +} + +// TestStateAt_CanceledContext_ReportsIt proves a canceled historical read reports the +// cancellation, not a view short of the journal. +func TestStateAt_CanceledContext_ReportsIt(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchMachine(fn) + store := durable.NewMemStore(durable.WithHistory()) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + mustRunService(t, h, state.InvokeID("fetch", "loading", 0)) + canceled, cancel := context.WithCancel(ctx) + cancel() + if _, err = durable.StateAt(canceled, m, store, id, 0, opts...); !errors.Is(err, context.Canceled) { + t.Fatalf("StateAt = %v, want context.Canceled", err) + } +} + +// TestRecover_CanceledContext_ChainedServices_ReportsIt proves a canceled replay of two +// chained services reports the cancellation, not a journal that looks corrupt. +func TestRecover_CanceledContext_ChainedServices_ReportsIt(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := chainMachine(fn, fn) + store := durable.NewMemStore() + id := durable.InstanceID("chain-1") + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](chainRegistry(fn, fn))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("first")) + if err != nil { + t.Fatalf("Start: %v", err) + } + mustRunService(t, h, state.InvokeID("chain", "first", 0)) + mustRunService(t, h, state.InvokeID("chain", "second", 0)) + canceled, cancel := context.WithCancel(ctx) + cancel() + if _, err = durable.Recover(canceled, m, store, id, opts...); !errors.Is(err, context.Canceled) { + t.Fatalf("Recover = %v, want context.Canceled", err) + } +} + +// TestTick_ContextEndedPartway_RecordsNothing proves a due timer the kernel refused isn't +// journaled: the Handle fails and the journal doesn't grow. +func TestTick_ContextEndedPartway_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := timerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + turn, cancel := context.WithCancel(ctx) + defer cancel() + clk := &cancelingClock{Clock: state.NewFakeClock(epoch)} + opts := []durable.Option[string, string, *timerCtx]{durable.WithRunnerClock[string, string, *timerCtx](clk)} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + _, before, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + clk.Clock.(*state.FakeClock).Advance(6 * time.Second) + clk.onNow = cancel // the turn ends as the Tick reads the clock + if _, err = h.Tick(turn); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("Tick = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + clk.onNow = nil + _, after, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(after) != len(before) { + t.Fatalf("journal grew from %d to %d records", len(before), len(after)) + } +} + +// cancelingClock runs onNow once on the next clock read. +type cancelingClock struct { + state.Clock + onNow func() +} + +func (c *cancelingClock) Now() time.Time { + if c.onNow != nil { + f := c.onNow + c.onNow = nil + f() + } + return c.Clock.Now() +} diff --git a/durable/timetravel.go b/durable/timetravel.go index ed19ff79..3f2ed864 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -101,7 +101,8 @@ func (v *TimeTravelView[S, E, C]) Step() int { return v.step } // historical read applies no side effect. // // step must be in [BaselineStep, lastRecordedStep]; a step outside that range -// reports ErrStepOutOfRange, and an unknown instance reports ErrInstanceNotFound. +// reports ErrStepOutOfRange, an unknown instance reports ErrInstanceNotFound, and an +// ended ctx reports its error. func StateAt[S comparable, E comparable, C any]( ctx context.Context, m *state.Machine[S, E, C], @@ -241,6 +242,11 @@ func replayThrough[S comparable, E comparable, C any]( } for i := range bounded { + // A canceled context can stop a replayed settle or tick with no error, leaving + // state short of the journal, so check it before each Record. + if err := ctx.Err(); err != nil { + return err + } rec := &bounded[i] switch { case hasActorEntry(rec): @@ -282,7 +288,9 @@ func replayThrough[S comparable, E comparable, C any]( // applies no side effect. } } - return nil + // A canceled context can stop a replayed settle or tick without an error reaching + // here, which would hand back a view short of the journal. + return ctx.Err() } // boundRecords returns the prefix of records whose first ordinal falls at or below From 805561e7ec8fac024f12a65bb7c300f6f8b0630a Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 11 Nov 2026 14:15:19 -0700 Subject: [PATCH 02/38] fix(durable): check RunService's context after absorbing the settle RunService checked for an ended context before absorbing the settle's effects. A context that ended during that absorb, or after a clean settle, let the step be journaled although the absorb ran on an ended context: an actor spawn could fail on it and its onError Fire be refused. It now fails the Handle on any context that ended by the end of the absorb, as DeliverToActor does, and absorbs with the step's marked context, so an actor that calls back in gets ErrReentrantStep instead of waiting. An absorb-driven onError isn't journaled on any path, refused or not; that predates this change and is tracked separately. Docs: RunService, the README and overview cause lists and the CHANGELOG cover the absorb case; Tick's doc says a canceled Tick's results weren't recorded; two test comments no longer claim a service or actor runs exactly once. Signed-off-by: Ray Karnes --- docs/src/content/docs/durable/overview.md | 2 +- durable/CHANGELOG.md | 4 +- durable/README.md | 2 +- durable/actor.go | 5 ++- durable/integration_test.go | 6 ++- durable/runner.go | 5 ++- durable/runner_example_test.go | 10 +++-- durable/service.go | 22 ++++++----- durable/service_test.go | 46 +++++++++++++++++++++++ 9 files changed, 80 insertions(+), 22 deletions(-) diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index 25d9d2bc..d371d1f2 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -72,7 +72,7 @@ the first time, and replayed verbatim on recovery: | Seam | Wire with | Recorded as | | --- | --- | --- | | **Clock** (timers) | `WithRunnerClock` | `JournalClockRead`, replayed so timers fire at the same recorded instants, wall-clock-independent; armed deadlines survive checkpoint compaction | -| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; 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, a failed `Append`, a crash) runs again when the host calls `RunService` | +| **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 failed `Append`, a crash) runs again when the host calls `RunService` | | **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled actor doesn't re-run, and a running one restarts from its initial state on any `Recover` | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 5eeba18a..06132167 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -119,7 +119,9 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **A step whose context ended partway isn't journaled.** A canceled `RunService`, `Tick` or `DeliverToActor` used to record a result the live instance never applied, which recovery then committed, or for an actor, failed on. Each now returns `ErrHandleFailed` - wrapping the error and records nothing. After `Recover` the service stays in flight and + wrapping the error and records nothing; `RunService` and `DeliverToActor` do so for any + context that ended by the end of the step, `RunService` including the absorb of its + settle's effects. After `Recover` the service stays in flight and must tolerate running again, the timer is re-armed, and the actor restarts. `Recover` and `StateAt` now fail on a canceled context, rather than returning state short of the journal. diff --git a/durable/README.md b/durable/README.md index d4c399db..ade9dd05 100644 --- a/durable/README.md +++ b/durable/README.md @@ -82,7 +82,7 @@ the first time, and replayed verbatim on recovery: | Seam | Wire with | Recorded as | | --- | --- | --- | | **Clock** (timers) | `WithRunnerClock` | `JournalClockRead`, replayed so timers fire at the same recorded instants, wall-clock-independent; armed deadlines survive checkpoint compaction | -| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; 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, a failed `Append`, a crash) runs again when the host calls `RunService` | +| **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 failed `Append`, a crash) runs again when the host calls `RunService` | | **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled actor doesn't re-run, and a running one restarts from its initial state on any `Recover` | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | diff --git a/durable/actor.go b/durable/actor.go index df444d6a..a4ea7290 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -89,8 +89,9 @@ type actorMessagePayload struct { HasData bool `json:"hasData,omitempty"` } -// DeliverToActor routes event into the running actor identified by ref, runs the actor (settling it when it reaches its final state), records each -// parent transition the delivery drove, and persists the produced step. The actor +// DeliverToActor routes event into the running actor identified by ref, runs the +// actor (settling it when it reaches its final state), records each parent +// transition the delivery drove, and persists the produced step. The actor // behavior is resolved and run against the palette supplied with WithActorPalette; // the done-data, error, or parent-driving message it routes is journaled as a // JournalActorMessage correlated by the actor id so recovery replays it without diff --git a/durable/integration_test.go b/durable/integration_test.go index c5426a39..270414c9 100644 --- a/durable/integration_test.go +++ b/durable/integration_test.go @@ -22,7 +22,8 @@ var errInjectedEffectCrash = errors.New("injected: crashed mid effect dispatch") // a delayed (`after`) timer — driven through the Runner over both the in-memory and // the on-disk Store, with crashes injected at each seam boundary. It proves the // seams compose: a recovery at any point reaches a snapshot byte-identical to a -// never-crashed reference, each external call (service, actor) happens exactly once, +// never-crashed reference, each external call (service, actor) happens once per +// recorded result (none of these crash points falls inside a call), // each domain effect is applied exactly once, and the timer fires from its recorded // deadline regardless of the wall clock at recovery. @@ -458,7 +459,8 @@ func finishPipeline(t *testing.T, ctx context.Context, h *durable.Handle[string, // TestIntegration_CrashMatrix_MemStore is the capstone over the in-memory Store: the // pipeline machine — service + actor + effect + timer — recovers byte-identically to -// a never-crashed reference at every crash point, invoking each seam exactly once. +// a never-crashed reference at every crash point, invoking each seam once per +// recorded result. func TestIntegration_CrashMatrix_MemStore(t *testing.T) { newStore := func() durable.Store { return durable.NewMemStore() } runCrashMatrix(t, "MemStore", newStore) diff --git a/durable/runner.go b/durable/runner.go index 090fb287..141f4367 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -741,7 +741,10 @@ func (h *Handle[S, E, C]) dispatchGuarded(ctx context.Context, step int, des []d // recorded instants. It returns the FireResults of the timers it fired, in order. A // failed checkpoint returns them with that error, and the Handle carries on. If another // goroutine failed the Handle while this step was recording, it returns them with -// ErrHandleFailed saying the step was recorded. +// ErrHandleFailed saying the step was recorded. If ctx ends partway, so the kernel +// refuses a due timer's Fire, it fails the Handle with ErrHandleFailed and records +// nothing: 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. func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], error) { if err := h.acquire(ctx); err != nil { return nil, err diff --git a/durable/runner_example_test.go b/durable/runner_example_test.go index 2fd92fa0..a6f2b530 100644 --- a/durable/runner_example_test.go +++ b/durable/runner_example_test.go @@ -159,10 +159,11 @@ func quoteMachine(fn state.ServiceFn[*quoteCtx]) *state.Machine[string, string, } // ExampleHandle_RunService shows the invoked-service record/replay seam: a pricing -// service runs exactly once on the live path (its returned quote recorded), and on +// service runs once on the live path (its returned quote recorded), and on // recovery the recorded quote is replayed back through the same settle seam without // re-invoking the service — so the recovered instance reaches the same state and -// context, and the service's call count never advances past one. +// context, and the service's call count never advances past one. (A turn whose +// context ends partway records nothing, and a recovered Handle runs it again.) func ExampleHandle_RunService() { ctx := context.Background() var calls int @@ -232,10 +233,11 @@ func fulfillmentMachine() *state.Machine[string, string, *fulfillmentCtx] { } // ExampleHandle_DeliverToActor shows the actor record/replay seam: a child shipping -// actor runs exactly once on the live path (its done-data recorded), and on recovery +// actor runs once on the live path (its done-data recorded), and on recovery // the recorded done-data is replayed back through the same parent onDone without // re-running the actor — so the recovered instance reaches the same state and -// context, and the actor's run count never advances past one. +// context, and the actor's run count never advances past one. (A delivery whose +// context ends partway records nothing, and a recovered Handle restarts the actor.) func ExampleHandle_DeliverToActor() { ctx := context.Background() var runs int diff --git a/durable/service.go b/durable/service.go index 8fb06124..2a7d9020 100644 --- a/durable/service.go +++ b/durable/service.go @@ -90,7 +90,8 @@ 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 failed Append, a result -// that won't encode, or a ctx that ended during the service returns ErrHandleFailed and +// that won't encode, or a ctx that ended during the service or while its settle's +// effects were absorbed (even after a clean settle) returns ErrHandleFailed and // records nothing: a recovered Handle has the service in flight again, and RunService // runs it a second time. If another goroutine failed the Handle while this step was // recording, it returns the result, true and ErrHandleFailed saying the step was @@ -118,19 +119,20 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire } res := results[0] - // A context canceled during the service stops the settle's Fire before it applies, - // so the instance never saw this result: journaling it would commit it on recovery. - // The runner has already dropped the service, so this Handle can't run it again; - // Recover re-arms it. - if res.Err != nil && ctx.Err() != nil { - return res, true, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, res.Err)) - } - // The settle re-fired the invocation's onDone / onError, which may enter a state // that arms a timer, starts another service, or spawns an actor. Absorb those // effects into every driver so the next seam method finds them armed — the service // seam composes with the timer and actor seams in one instance. - h.absorbDrivers(ctx, res.Effects) + h.absorbDrivers(h.stepContext(ctx), res.Effects) + + // A context that ended during the service or the absorb can stop the settle's Fire, + // or a Fire an actor spawn routes, before it applies, so the instance may not have + // seen this result: journaling it would commit on recovery what live never applied. + // The runner has already dropped the service, so this Handle can't run it again; + // Recover re-arms it. + if err := ctx.Err(); err != nil { + return res, true, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, err)) + } entry, err := recordServiceOutcome(id, h.svc.LastResult, h.svc.LastError()) if err != nil { diff --git a/durable/service_test.go b/durable/service_test.go index bf4fb5f0..4df880a8 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -671,3 +671,49 @@ func (c *cancelingClock) Now() time.Time { } return c.Clock.Now() } + +// TestService_ContextEndedDuringAbsorb_RecordsNothing proves a service that settles +// cleanly, and whose context then ends while the settle's actor spawn is absorbed, +// fails the Handle and records nothing: the spawn's onError Fire was refused, so the +// live instance never applied what the journal would otherwise commit. +func TestService_ContextEndedDuringAbsorb_RecordsNothing(t *testing.T) { + ctx := context.Background() + turnCtx, cancel := context.WithCancel(ctx) + defer cancel() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return "ok", nil } + spawn := func(map[string]any) (state.ActorInstance, error) { + cancel() // the turn's deadline passes while the settle's spawn is absorbed + return nil, errors.New("worker unavailable") + } + m := state.ForgeFor[svcCtx]("absorb"). + Service("fetch", fn). + Actor("spawnChild"). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("loading"). + Transition("loading").On("ok").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed"). + Quench() + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store, + durable.WithServiceRegistry[string, string, svcCtx](state.NewRegistry[svcCtx]().Service("fetch", fn)), + durable.WithActorPalette[string, string, svcCtx](map[string]state.ActorBehavior{"spawnChild": spawn})). + Start(ctx, "absorb-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + before := tailLen(t, store, "absorb-1") + _, ran, err := h.RunService(turnCtx, state.InvokeID("absorb", "loading", 0)) + if !ran || !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService = %v, %v; want true, ErrHandleFailed", ran, err) + } + if after := tailLen(t, store, "absorb-1"); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } +} From 1b501bd42da72b8420fe72a3224bdde79febc03f Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 11 Nov 2026 14:23:15 -0700 Subject: [PATCH 03/38] ci: run nothing on a draft PR A draft PR ran only the gate, which failed on purpose, so each push to a draft left a red check and used a runner. GitHub has no draft filter on the pull_request trigger, so a run is still recorded, but now every job, the gate included, skips on a draft. GitHub won't merge a draft, and marking it ready starts a run in which the gate runs and must pass. This reopens a window the failing gate closed: a skipped required check counts as passing, so a PR merged in the seconds between marking it ready and its new run starting would merge without CI. The header of ci.yml says so; we accept it to keep drafts free of runs. Signed-off-by: Ray Karnes --- .github/workflows/ci.yml | 27 +++++++++++++-------------- CONTRIBUTING.md | 4 ++-- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 38847e61..1733b8b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,8 +1,14 @@ name: CI -# A draft PR runs only the gate, which fails until the PR is marked ready, so work -# under review spends no CI time. Marking it ready (ready_for_review) runs the full -# CI, as does every later push to a ready PR. +# A draft PR runs no jobs: every job, the gate included, skips while the PR is a +# draft, so work under review spends no CI time. GitHub still records a run for each +# push, with every job skipped. Marking it ready (ready_for_review) runs the full CI, +# as does every later push to a ready PR. +# +# The cost: a skipped required check counts as passing, so the draft's skipped `gate` +# reads as passed until the ready run starts, when its pending `gate` blocks a merge. +# A PR merged in the seconds between marking it ready and that run starting would +# merge without CI. We accept that window to keep drafts free of runs and red checks. on: pull_request: branches: [main] @@ -24,8 +30,8 @@ env: jobs: # Detect whether anything other than docs changed. Docs-only PRs skip the Go - # lint/test/vuln/coverage/bench jobs entirely; the `gate` job below still runs - # and is the single required status check, so such PRs stay mergeable. + # lint/test/vuln/coverage/bench jobs entirely; on a ready PR the `gate` job below + # still runs and is the single required status check, so such PRs stay mergeable. changes: if: ${{ !github.event.pull_request.draft }} runs-on: ubuntu-latest @@ -597,19 +603,12 @@ jobs: # docs) as a pass — so such PRs stay mergeable without running every matrix. # `bench` is advisory and is deliberately excluded so a benchmark regression # never blocks a merge. + # It skips on a draft, like every job here; the header says why, and what it costs. gate: - if: always() + if: ${{ always() && !github.event.pull_request.draft }} needs: [changes, lint, tests, sink, source, vuln, coverage, docs] runs-on: ubuntu-latest steps: - # On a draft every other job is skipped, and a skipped required check would - # count as passing for this commit. Fail instead, so a PR can't be marked ready - # and merged before its CI has run. - - name: Fail on a draft - if: ${{ github.event.pull_request.draft }} - run: | - echo "::error::Draft PR: CI runs when it's marked ready for review." - exit 1 - name: Fail if a required job did not pass if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }} run: | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7881c94a..56931fe7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -136,8 +136,8 @@ Run `mage -l` to list everything. Each target iterates the suite's modules. Before you push, **tests, lint, vet, and `govulncheck` must all pass.** The quickest way to verify locally is `mage check`. CI runs the same gates across a -OS matrix on every ready PR. A draft PR runs only the `gate` check, which fails until -the PR is marked ready for review; marking it ready runs the full CI. +OS matrix on every ready PR. A draft PR runs no jobs, the `gate` check included; +marking it ready for review runs the full CI. Docs-only pull requests (changing only `*.md`, `docs/`, `LICENSE`, or `NOTICE`) skip the Go matrix automatically and are gated solely by the aggregate `gate` From 3fb4e20f18cad85c19cb09bc53f4a28ac4afb49b Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 11 Nov 2026 17:02:35 -0700 Subject: [PATCH 04/38] feat(state): report the errors of parent Fires an ActorSystem drove TakeParentFireErrors returns the errors of the parent Fires the system drove since the last call, and clears them. A host that records what a delivery or a spawn drove can then tell a parent transition refused because its context ended, which replay can't reproduce, from one that applied or was refused for a reason replay meets again. Signed-off-by: Ray Karnes --- state/CHANGELOG.md | 5 +++++ state/actor_system.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 1d55a005..16f19426 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -13,6 +13,11 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Added +- **`ActorSystem.TakeParentFireErrors`** returns the errors of the parent Fires the + system drove since the last call, and clears them, so a host that records a delivery + or spawn can tell a parent transition refused because its context ended from one + that applied. + - **`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/actor_system.go b/state/actor_system.go index 10c7a84b..09060a82 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -155,6 +155,11 @@ type ActorSystem[S comparable, E comparable, C any] struct { // never silently swallowed. Read through LastEscalation. lastEscalation *ActorEscalation + // parentFireErrs holds the errors of the parent Fires the system drove since the + // last TakeParentFireErrors, so a host can tell a parent transition refused + // because its context ended from one that applied. Guarded by mu. + parentFireErrs []error + // escalationHandler is the optional host policy invoked for each escalation. It // is nil by default — the default escalation behavior (record + inspect) needs no // handler — and wired with WithEscalationHandler. @@ -387,6 +392,7 @@ func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err return } res := s.parent.Fire(ctx, ev) + s.noteParentFire(res) s.Absorb(ctx, res.Effects) } @@ -668,6 +674,7 @@ func (s *ActorSystem[S, E, C]) fireParentFrom(ctx context.Context, event any, se s.mu.Unlock() res := s.parent.Fire(ctx, ev) + s.noteParentFire(res) s.Absorb(ctx, res.Effects) s.mu.Lock() @@ -729,6 +736,7 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any payload = output } res := s.parent.Fire(ctx, ev, WithEventData(payload)) + s.noteParentFire(res) s.Absorb(ctx, res.Effects) return res, true } @@ -788,3 +796,25 @@ func (s *ActorSystem[S, E, C]) LastError() error { defer s.mu.Unlock() return s.lastOutcome.err } + +// noteParentFire records a parent Fire's error for TakeParentFireErrors. +func (s *ActorSystem[S, E, C]) noteParentFire(res FireResult[S]) { + if res.Err == nil { + return + } + s.mu.Lock() + s.parentFireErrs = append(s.parentFireErrs, res.Err) + s.mu.Unlock() +} + +// TakeParentFireErrors returns the errors of the parent Fires the system has driven +// since the last call, in order, and clears them. A parent Fire refused because the +// context it ran under ended reports that context's error, so a host that records +// what a delivery or spawn drove can tell a refusal it can't replay from one it can. +func (s *ActorSystem[S, E, C]) TakeParentFireErrors() []error { + s.mu.Lock() + defer s.mu.Unlock() + errs := s.parentFireErrs + s.parentFireErrs = nil + return errs +} From 76f87910a9971ef6d5ee7965373a85345ec7888d Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 11 Nov 2026 17:02:35 -0700 Subject: [PATCH 05/38] fix(durable): one rule for a step refused by an ended context Tick, RunService and DeliverToActor each guarded a canceled step their own way: Tick failed only when a timer's Fire was refused, the others on any ended context, and none saw a refusal from a context middleware derived from the caller's. One helper, stepCanceled, now decides for all three: a step records nothing and fails the Handle once its context ended by the end of the step, or a Fire it drove (a parent Fire the actor system drove included) was refused with a context's error. A parent Fire refused for another reason, such as a failing guard, is still recorded. Its actor journal entry now says it was refused, and replay accepts the same refusal instead of failing every Recover on it. Recover and StateAt walked the journal in two parallel loops; both now use one replayRecord, with Recover adding its deadline table and effect re-dispatch on top. Tests now check the journal where their names say nothing was recorded, and cover a Tick ended after its timer applied, settles and deliveries refused by a derived context, and a deterministic actor refusal that recovers. DeliverToActor's comment states the right mechanism, and the ErrHandleFailed doc lists its causes. Signed-off-by: Ray Karnes --- docs/src/content/docs/durable/overview.md | 3 +- durable/CHANGELOG.md | 9 +- durable/README.md | 3 +- durable/actor.go | 29 ++- durable/actor_test.go | 101 ++++++++- durable/errors.go | 14 +- durable/runner.go | 238 ++++++++++++++-------- durable/service.go | 9 +- durable/service_test.go | 119 ++++++++++- durable/timetravel.go | 43 +--- 10 files changed, 418 insertions(+), 150 deletions(-) diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index d371d1f2..b501131e 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -141,7 +141,8 @@ ends. Read the instance with `View`, which takes the lock; `Instance()` is outside it. A step that may not have been recorded, or a `Tick`, `RunService` or `DeliverToActor` whose -context ended partway, fails the Handle with `ErrHandleFailed`. So does an effect handler +context, or one derived from it, ended during the step, fails the Handle with +`ErrHandleFailed`. So does an effect handler that returns an error or panics. Before `Recover`, call `Handle.Drain`, which waits until no step of the failed Handle is still recording and no effect is still being sent, so the recovered Handle loads every recorded step and can't send an effect twice. Give `Drain` a diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 06132167..847bb337 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -119,9 +119,12 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **A step whose context ended partway isn't journaled.** A canceled `RunService`, `Tick` or `DeliverToActor` used to record a result the live instance never applied, which recovery then committed, or for an actor, failed on. Each now returns `ErrHandleFailed` - wrapping the error and records nothing; `RunService` and `DeliverToActor` do so for any - context that ended by the end of the step, `RunService` including the absorb of its - settle's effects. After `Recover` the service stays in flight and + wrapping the error and records nothing. One rule covers all three: a step records + nothing once its context ended by the end of the step, or a Fire it drove was refused + with a context's error, which catches a context middleware derived from the caller's. + A Fire refused for another reason, such as a failing guard, is still recorded, and + replay now meets the same refusal instead of failing Recover on it. After `Recover` + the service stays in flight and must tolerate running again, the timer is re-armed, and the actor restarts. `Recover` and `StateAt` now fail on a canceled context, rather than returning state short of the journal. diff --git a/durable/README.md b/durable/README.md index ade9dd05..75cde198 100644 --- a/durable/README.md +++ b/durable/README.md @@ -152,7 +152,8 @@ ends. Read the instance with `View`, which takes the lock; `Instance()` is outside it. A step that may not have been recorded, or a `Tick`, `RunService` or `DeliverToActor` whose -context ended partway, fails the Handle with `ErrHandleFailed`. So does an effect handler +context, or one derived from it, ended during the step, fails the Handle with +`ErrHandleFailed`. So does an effect handler that returns an error or panics. Before `Recover`, call `Handle.Drain`, which waits until no step of the failed Handle is still recording and no effect is still being sent, so the recovered Handle loads every recorded step and can't send an effect twice. Give `Drain` a diff --git a/durable/actor.go b/durable/actor.go index a4ea7290..7f5691a3 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -87,6 +87,11 @@ type actorMessagePayload struct { // it; a message-driven fire (SendParent) leaves it false so replay re-fires the // parent plainly, letting the event itself supply the assign's data. HasData bool `json:"hasData,omitempty"` + // Refused reports that the live parent Fire was refused (a guard failed, no + // transition matched, ...), so replay expects the same refusal instead of failing + // on it. A refusal because a context ended is never recorded: that step fails the + // Handle instead. + Refused bool `json:"refused,omitempty"` } // DeliverToActor routes event into the running actor identified by ref, runs the @@ -101,7 +106,8 @@ type actorMessagePayload struct { // actor (already settled, stopped, or never spawned), or false and an error when no // palette is wired, the Handle has failed, or ctx ended before the delivery. Once the // actor ran it returns true with any error. A failed Append, a result that won't encode, -// or a ctx that ended during the delivery returns ErrHandleFailed and records nothing: on +// or a ctx (or one derived from it) that ended during the delivery returns +// ErrHandleFailed and records nothing: on // a recovered Handle an InvokeActor actor restarts from its initial state, and a Spawn // actor doesn't return. If another goroutine failed the Handle while this step was // recording, it returns true and ErrHandleFailed saying the step was recorded. A failed @@ -120,13 +126,17 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef } before := len(h.inst.History()) + h.clearActorFireErrs() delivered := h.actors.Deliver(h.stepContext(ctx), ref, event) if !delivered { + h.clearActorFireErrs() return false, nil } - // A context that ended during the delivery can stop a parent Fire partway, and a - // refused Fire leaves a Trace replay can't re-fire. Record nothing. - if err := ctx.Err(); err != nil { + // A context that ended during the delivery can make the kernel refuse a parent + // Fire it drove. The refused Fire rolls back, so live never applied it, but + // journaling the delivery would replay it under a live context, where it applies. + // Record nothing. + if err := h.stepCanceled(ctx); err != nil { return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) } @@ -211,6 +221,7 @@ func recordActorTransitions(id string, history []state.Trace, before int, output for i, tr := range traces { var mp actorMessagePayload mp.Event = append(json.RawMessage(nil), tr.EventPayload...) + mp.Refused = tr.Outcome != state.OutcomeSuccess // Attribute the actor outcome to the settling fire — the last parent Trace — // so the onDone / onError transition replays with the recorded done-data / // error, while a message-driven fire that preceded it replays plainly. @@ -266,8 +277,16 @@ func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *s } else { res = inst.Fire(ctx, event) } - if res.Err != nil { + refused := res.Err != nil || res.Trace.Outcome != state.OutcomeSuccess + switch { + case refused && mp.Refused: + return nil // the live run was refused the same way + case refused && res.Err != nil: return fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, res.Err) + case refused: + return fmt.Errorf("durable: replaying actor %q transition: %s, but the live run's applied", entry.CorrelationID, res.Trace.Outcome) + case mp.Refused: + return fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) } return nil } diff --git a/durable/actor_test.go b/durable/actor_test.go index ef3cd6f5..35bd209a 100644 --- a/durable/actor_test.go +++ b/durable/actor_test.go @@ -739,10 +739,109 @@ func TestDeliverToActor_ContextEndedPartway_RecordsNothing(t *testing.T) { if !ok { t.Fatal("no actor ref for spawned child") } + before := tailLen(t, store, id) if _, err = h.DeliverToActor(turn, ref, "finish"); !errors.Is(err, durable.ErrHandleFailed) { t.Fatalf("DeliverToActor = %v, want ErrHandleFailed", err) } - if _, err = durable.Recover(ctx, m, store, id, opts...); err != nil { + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "supervising" { + t.Fatalf("recovered state %q, want supervising: the canceled delivery was committed", got) + } +} + +// supervisorUsing is supervisorMachine with mw installed and, if refuseDone, a +// childDone transition whose guard always fails. +func supervisorUsing(mw state.Middleware[string, string, actorCtx], refuseDone bool) *state.Machine[string, string, actorCtx] { + b := state.ForgeFor[actorCtx]("supervisor"). + Guard("never", func(state.GuardCtx[actorCtx]) bool { return false }). + Actor("spawnChild"). + State("supervising").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone"), state.WithInvokeOnError("childFail")). + State("complete").Final(). + State("failed").Final(). + Initial("supervising") + if mw != nil { + b = b.Use(mw) + } + t := b.Transition("supervising").On("childDone").GoTo("complete") + if refuseDone { + t = t.When("never") + } + return t.Transition("supervising").On("childFail").GoTo("failed").Quench() +} + +// TestDeliverToActor_RefusedByADerivedContext_RecordsNothing proves a delivery whose +// parent Fire is refused because a context middleware derived from the caller's ended, +// while the caller's is still live, fails the Handle and records nothing. +func TestDeliverToActor_RefusedByADerivedContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + cancelOnDone := func(next state.FireFunc[string, string, actorCtx]) state.FireFunc[string, string, actorCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + if event == "childDone" { + derived, cancel := context.WithCancel(ctx) + cancel() + return next(derived, event) + } + return next(ctx, event) + } + } + m := supervisorUsing(cancelOnDone, false) + store := durable.NewMemStore() + id := durable.InstanceID("sup-derived") + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for spawned child") + } + before := tailLen(t, store, id) + if _, err = h.DeliverToActor(ctx, ref, "finish"); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("DeliverToActor = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } +} + +// TestDeliverToActor_DeterministicRefusal_Recovers proves a parent Fire refused for a +// reason replay meets again (a guard that fails) is journaled, and Recover replays it +// to the live state instead of failing on the refusal. +func TestDeliverToActor_DeterministicRefusal_Recovers(t *testing.T) { + ctx := context.Background() + m := supervisorUsing(nil, true) + store := durable.NewMemStore() + id := durable.InstanceID("sup-refused") + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for spawned child") + } + before := tailLen(t, store, id) + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + if after := tailLen(t, store, id); after != before+1 { + t.Fatalf("journal grew from %d to %d records, want one", before, after) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { t.Fatalf("Recover: %v", err) } + if live, got := h.Instance().Current(), recovered.Instance().Current(); got != live || live != "supervising" { + t.Fatalf("recovered %q, live %q, want both supervising", got, live) + } } diff --git a/durable/errors.go b/durable/errors.go index 4342dd1e..9e58e30d 100644 --- a/durable/errors.go +++ b/durable/errors.go @@ -56,11 +56,15 @@ var ( ErrRecordTooLarge = errors.New(errorPrefix + errorRecordTooLarge) // ErrHandleFailed is reported by a Handle's Fire, Tick, RunService, DeliverToActor - // and View once a step applied to the live instance but may not have been recorded, - // a Tick, RunService or DeliverToActor's context ended partway, or an effect handler - // failed, on that call and every later one. It wraps the cause. Call Handle.Drain, - // then Recover a new Handle with the same options to continue, unless the cause is - // ErrFenced: then a newer owner holds the instance, so stop. + // and View, on the call that failed the Handle and every later one. It wraps the + // cause, which is one of: + // - a step applied to the live instance but may not have been recorded; + // - a Tick, RunService or DeliverToActor ran while its context ended, so a Fire it + // drove may have been refused: it had already consumed the timer, service or + // delivery, so it can't simply refuse the way Fire does; + // - an effect handler failed. + // Call Handle.Drain, then Recover a new Handle with the same options to continue, + // unless the cause is ErrFenced: then a newer owner holds the instance, so stop. ErrHandleFailed = errors.New(errorPrefix + errorHandleFailed) // ErrReentrantStep is reported by a Handle's Fire, Tick, RunService, DeliverToActor diff --git a/durable/runner.go b/durable/runner.go index 141f4367..b76ab469 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -103,8 +103,8 @@ func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st // Handle, so it isn't serialized with this one. // // A step that applied to the kernel but may not have been recorded, or a Tick, RunService -// or DeliverToActor whose context ended partway, leaves the Handle out of step with the -// journal. That call and every later one return ErrHandleFailed, wrapping the cause, +// or DeliverToActor whose context, or one derived from it, ended during the step, +// leaves the Handle out of step with the journal. That call and every later one return ErrHandleFailed, wrapping the cause, // which can be a context that ended during the Store write. Before recovering, call // Drain: a step on another goroutine may still be recording, which a recovered Handle // wouldn't load, or sending an effect, which it would send again. Recovering a healthy @@ -741,10 +741,12 @@ func (h *Handle[S, E, C]) dispatchGuarded(ctx context.Context, step int, des []d // recorded instants. It returns the FireResults of the timers it fired, in order. A // failed checkpoint returns them with that error, and the Handle carries on. If another // goroutine failed the Handle while this step was recording, it returns them with -// ErrHandleFailed saying the step was recorded. If ctx ends partway, so the kernel -// refuses a due timer's Fire, it fails the Handle with ErrHandleFailed and records -// nothing: 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. +// ErrHandleFailed saying the step was recorded. If ctx ends during the Tick, or a +// context derived from it (by middleware, say) refuses a timer's Fire, it fails the +// Handle with ErrHandleFailed and records nothing, even for timers that applied: the +// results it returns weren't recorded, so don't act on their effects; a recovered +// Handle re-arms those timers and fires them again. A timer's Fire refused for another +// reason, such as a failing guard, is recorded, and replay meets the same refusal. func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], error) { if err := h.acquire(ctx); err != nil { return nil, err @@ -753,16 +755,13 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro if err := h.refuse(ctx); err != nil { return nil, err } + h.clearActorFireErrs() results := h.sched.Tick(h.stepContext(ctx)) - // A context that ended partway makes 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 timer. - if err := ctx.Err(); err != nil { - for i := range results { - if results[i].Err != nil { - return results, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, err)) - } - } + // 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. + if err := h.stepCanceled(ctx, resultErrs(results)...); err != nil { + return results, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, err)) } step := h.nextStep @@ -980,84 +979,34 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } rec := &tail[i] - switch { - case hasActorEntry(rec): - // Re-fire each recorded parent transition the live delivery drove, in - // recorded (fire) order, carrying the recorded actor done-data / error so - // the kernel re-derives the identical onDone / onError (or message) parent - // transition — running no actor behavior. - for _, entry := range actorEntries(rec) { - if err := replayActor(ctx, inst, r.cfg.eventCodec, entry); err != nil { - return nil, fmt.Errorf("durable: at step %d for %q: %w", rec.Step, id, err) - } - } - case hasServiceEntry(rec): - // Re-settle each recorded invoked-service outcome through the same settle - // seam the live run drove, in recorded (settle) order, so the kernel - // re-fires the identical onDone / onError event with the identical data — - // running no service. The settle absorbs its own follow-on StartService - // effects, so a chained invoke arms its successor for the next entry. - for _, entry := range serviceEntries(rec) { - if err := replayService(ctx, svc, entry); err != nil { - return nil, fmt.Errorf("durable: at step %d for %q: %w", rec.Step, id, err) - } - } - case rec.Tick: - // Re-derive the timers the live tick fired: ticking the replay clock - // returns the recorded readings, so the same deadlines come due and the - // same timers fire, at their recorded instants. Mirror the tick into the - // armed table — drop the timers it fired, arm any a chained transition - // re-scheduled — so the deadline table tracks the still-pending set. - tickRes := sched.Tick(ctx) - if now, ok := tickInstant(rec.Entries); ok { - for id, pt := range armed { - if !pt.due.After(now) { - delete(armed, id) - } - } - for ri := range tickRes { - mirrorArmed(armed, tickRes[ri].Effects, now) + did, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec) + if err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } + now, haveNow := tickInstant(rec.Entries) + // Mirror the step into the armed table so it tracks the still-pending set, with + // deadlines drawn from the step's recorded clock read, not the live wall clock: + // a tick drops the timers it fired and arms any a chained transition scheduled, + // and a plain event arms the timers its Fire armed. + if rec.Tick && haveNow { + for id, pt := range armed { + if !pt.due.After(now) { + delete(armed, id) } } - case len(rec.Event) == 0: - continue // a checkpoint-only Record drives no event - default: - event, err := r.cfg.eventCodec.Decode(rec.Event) - if err != nil { - return nil, fmt.Errorf("durable: decoding recorded event at step %d for %q: %w", rec.Step, id, err) + for ri := range did.tick { + mirrorArmed(armed, did.tick[ri].Effects, now) } - fireOpts, err := replayFireOptions(rec, event, r.cfg.eventDataDecoder) - if err != nil { - return nil, fmt.Errorf("durable: decoding recorded event data at step %d for %q: %w", rec.Step, id, err) - } - res := inst.Fire(ctx, event, fireOpts...) - if res.Err != nil { - return nil, fmt.Errorf("durable: replaying step %d for %q: %w", rec.Step, id, res.Err) - } - // Re-arm/cancel this step's timers exactly as the live Fire did, so the - // scheduler's pending set is reconstructed with the recorded deadlines. - // Mirror the same arming into the armed table, drawing the deadline from - // the recorded clock read the Absorb consumed (captured at the recorded - // step rather than the live wall clock). - if hasTimerEffect(res.Effects) { - sched.Absorb(ctx, res.Effects) - // The step's recorded clock read (the one the live Absorb consumed) is - // the instant to derive each re-armed deadline from, so the mirror uses - // recorded time, not the live wall clock. - if now, ok := tickInstant(rec.Entries); ok { - mirrorArmed(armed, res.Effects, now) - } - } - // Arm this step's services so a service it entered is in flight for the - // recorded settlement that follows, mirroring the live Fire path. - if svc != nil { - svc.Absorb(ctx, res.Effects) + } + if did.fired != nil { + if haveNow && hasTimerEffect(did.fired.Effects) { + mirrorArmed(armed, did.fired.Effects, now) } - // Re-dispatch this step's domain effects, deduped by the Store's - // dispatched set: an effect already marked (it landed before the crash) - // is skipped; one recorded-but-un-marked (the crash fell between append - // and dispatch) is applied now — exactly-once across the crash boundary. - if err := r.dispatchReplayEffects(ctx, id, rec.Step, res.Effects); err != nil { + // 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, did.fired.Effects); err != nil { return nil, err } } @@ -1324,3 +1273,114 @@ func (jsonEventCodec[E]) Decode(payload []byte) (E, error) { func isContextErr(err error) bool { return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) } + +// stepCanceled reports why a Tick, RunService or DeliverToActor must record nothing: +// a context ended, so a Fire the step drove may have been refused, and live may not +// have applied what the step would journal. That's the caller's ctx having ended, or +// a Fire refused with a context's error (one middleware derived from ctx included), +// among errs or among the parent Fires the actor system drove. A refusal with any +// other cause, such as a failing guard, is deterministic: the step is journaled, and +// replay meets the same refusal. It drains the actor system's record of parent Fire +// errors either way. +func (h *Handle[S, E, C]) stepCanceled(ctx context.Context, errs ...error) error { + if h.actors != nil { + errs = append(errs, h.actors.TakeParentFireErrors()...) + } + if err := ctx.Err(); err != nil { + return err + } + for _, err := range errs { + if err != nil && isContextErr(err) { + return err + } + } + return nil +} + +// clearActorFireErrs drops parent Fire errors recorded before a step began, so +// stepCanceled sees only the step's own. +func (h *Handle[S, E, C]) clearActorFireErrs() { + if h.actors != nil { + h.actors.TakeParentFireErrors() + } +} + +// resultErrs returns each result's error, nil ones included. +func resultErrs[S comparable](results []state.FireResult[S]) []error { + errs := make([]error, len(results)) + for i := range results { + errs[i] = results[i].Err + } + return errs +} + +// replayed is what replayRecord fired, for a caller that tracks more than the +// instance: a tick barrier's timer fires, or a plain event's Fire. +type replayed[S comparable] struct { + tick []state.FireResult[S] + fired *state.FireResult[S] +} + +// 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 and effect re-dispatch on top. +// +// - An actor delivery re-fires each parent transition the delivery drove, in fire +// order, with the recorded done-data or error, so the kernel re-derives the same +// onDone / onError (or message) transition. +// - A service settlement re-settles each recorded outcome through the same settle +// seam, in settle order; the settle absorbs its own follow-on StartService +// effects, so a chained invoke arms its successor for the next entry. +// - A tick barrier ticks the replay clock, which returns the recorded readings, so +// the same deadlines come due and the same timers fire at their recorded instants. +// - A plain event re-fires it with its recorded event data, then re-arms its timers +// and services as the live Fire did. +// - A checkpoint-only Record drives nothing. +func replayRecord[S comparable, E comparable, C any]( + ctx context.Context, + inst *state.Instance[S, E, C], + cfg *runnerConfig[S, E, C], + sched *state.Scheduler[S, E, C], + svc *state.ServiceRunner[S, E, C], + rec *Record, +) (replayed[S], error) { + var out replayed[S] + switch { + case hasActorEntry(rec): + for _, entry := range actorEntries(rec) { + if err := replayActor(ctx, inst, cfg.eventCodec, entry); err != nil { + return out, fmt.Errorf("at step %d: %w", rec.Step, err) + } + } + case hasServiceEntry(rec): + for _, entry := range serviceEntries(rec) { + if err := replayService(ctx, svc, entry); err != nil { + return out, fmt.Errorf("at step %d: %w", rec.Step, err) + } + } + case rec.Tick: + out.tick = sched.Tick(ctx) + case len(rec.Event) == 0: + default: + event, err := cfg.eventCodec.Decode(rec.Event) + if err != nil { + return out, fmt.Errorf("decoding recorded event at step %d: %w", rec.Step, err) + } + fireOpts, err := replayFireOptions(rec, event, cfg.eventDataDecoder) + if err != nil { + return out, fmt.Errorf("decoding recorded event data at step %d: %w", rec.Step, err) + } + res := inst.Fire(ctx, event, fireOpts...) + if res.Err != nil { + return out, fmt.Errorf("replaying step %d: %w", rec.Step, res.Err) + } + if hasTimerEffect(res.Effects) { + sched.Absorb(ctx, res.Effects) + } + if svc != nil { + svc.Absorb(ctx, res.Effects) + } + out.fired = &res + } + return out, nil +} diff --git a/durable/service.go b/durable/service.go index 2a7d9020..9a4bc1ee 100644 --- a/durable/service.go +++ b/durable/service.go @@ -90,9 +90,9 @@ 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 failed Append, a result -// that won't encode, or a ctx that ended during the service or while its settle's -// effects were absorbed (even after a clean settle) returns ErrHandleFailed and -// records nothing: a recovered Handle has the service in flight again, and RunService +// that won't encode, or a ctx (or one derived from it) that ended during the service or +// while its settle's effects were absorbed (even after a clean settle) returns +// ErrHandleFailed and records nothing: a recovered Handle has the service in flight again, and RunService // runs it a second time. If another goroutine failed the Handle while this step was // recording, it returns the result, true and ErrHandleFailed saying the step was // recorded. That error also matches the cause, so test ErrHandleFailed first: it alone @@ -113,6 +113,7 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire return state.FireResult[S]{}, false, nil } + h.clearActorFireErrs() results := h.svc.Tick(h.stepContext(ctx), id) if len(results) == 0 { return state.FireResult[S]{}, false, nil @@ -130,7 +131,7 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire // 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. - if err := ctx.Err(); err != nil { + if err := h.stepCanceled(ctx, res.Err); err != nil { return res, true, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, err)) } diff --git a/durable/service_test.go b/durable/service_test.go index 4df880a8..45e3be3b 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -535,8 +535,12 @@ func TestService_CanceledTurn_RecoverRerunsTheService(t *testing.T) { t.Fatalf("Fire(start): %v", err) } invoke := state.InvokeID("fetch", "loading", 0) - if _, _, err = h.RunService(turnCtx, invoke); !errors.Is(err, context.Canceled) { - t.Fatalf("RunService = %v, want context.Canceled", err) + before := tailLen(t, store, id) + if _, _, err = h.RunService(turnCtx, invoke); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("RunService = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want the canceled result unrecorded", before, after) } if _, err = h.Fire(ctx, "start"); !errors.Is(err, durable.ErrHandleFailed) { t.Fatalf("Fire after the cancel = %v, want ErrHandleFailed", err) @@ -717,3 +721,114 @@ func TestService_ContextEndedDuringAbsorb_RecordsNothing(t *testing.T) { t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) } } + +// countingClock counts clock reads and runs onRead on each. +type countingClock struct { + state.Clock + n int + onRead func(n int) +} + +func (c *countingClock) Now() time.Time { + c.n++ + if c.onRead != nil { + c.onRead(c.n) + } + return c.Clock.Now() +} + +// TestTick_ContextEndedAfterTheTimersApplied_RecordsNothing proves a Tick whose context +// ends after its due timer's Fire applied still fails the Handle and records nothing, +// as RunService and DeliverToActor do, and Recover fires the timer again. +func TestTick_ContextEndedAfterTheTimersApplied_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := chainedTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("chain-1") + fc := state.NewFakeClock(epoch) + clk := &countingClock{Clock: fc} + opts := []durable.Option[string, string, *timerCtx]{durable.WithRunnerClock[string, string, *timerCtx](clk)} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + before := tailLen(t, store, id) + fc.Advance(4 * time.Second) + turn, cancel := context.WithCancel(ctx) + defer cancel() + base := clk.n + clk.onRead = func(n int) { + if n == base+3 { // the scheduler's last read, after the first timer applied + cancel() + } + } + results, err := h.Tick(turn) + clk.onRead = nil + if turn.Err() == nil { + t.Fatal("the test didn't end the context") + } + if len(results) != 1 || results[0].Err != nil { + t.Fatalf("Tick results %v, want one applied timer", results) + } + if !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("Tick = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "first" { + t.Fatalf("recovered state %q, want first: the unrecorded tick must fire again", got) + } +} + +// TestService_RefusedByADerivedContext_RecordsNothing proves a settle refused because a +// context middleware derived from the caller's ended, while the caller's is still live, +// fails the Handle and records nothing. +func TestService_RefusedByADerivedContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + fn := counterService(new(int64)) + cancelOnOK := func(next state.FireFunc[string, string, svcCtx]) state.FireFunc[string, string, svcCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + if event == "ok" { + derived, cancel := context.WithCancel(ctx) + cancel() + return next(derived, event) + } + return next(ctx, event) + } + } + m := state.ForgeFor[svcCtx]("derived"). + Use(cancelOnOK). + Service("fetch", fn). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("ready").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("loading"). + Transition("loading").On("ok").GoTo("ready"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("derived-1") + h, err := durable.NewRunner(m, store, durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))). + Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + before := tailLen(t, store, id) + if _, _, err = h.RunService(ctx, state.InvokeID("derived", "loading", 0)); !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("RunService = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if after := tailLen(t, store, id); after != before { + t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) + } +} diff --git a/durable/timetravel.go b/durable/timetravel.go index 3f2ed864..662ee38f 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -247,45 +247,10 @@ func replayThrough[S comparable, E comparable, C any]( if err := ctx.Err(); err != nil { return err } - rec := &bounded[i] - switch { - case hasActorEntry(rec): - for _, entry := range actorEntries(rec) { - if err := replayActor(ctx, inst, cfg.eventCodec, entry); err != nil { - return fmt.Errorf("at step %d: %w", rec.Step, err) - } - } - case hasServiceEntry(rec): - for _, entry := range serviceEntries(rec) { - if err := replayService(ctx, svc, entry); err != nil { - return fmt.Errorf("at step %d: %w", rec.Step, err) - } - } - case rec.Tick: - sched.Tick(ctx) - case len(rec.Event) == 0: - continue // a checkpoint-only Record drives no event - default: - event, err := cfg.eventCodec.Decode(rec.Event) - if err != nil { - return fmt.Errorf("decoding recorded event at step %d: %w", rec.Step, err) - } - fireOpts, err := replayFireOptions(rec, event, cfg.eventDataDecoder) - if err != nil { - return fmt.Errorf("decoding recorded event data at step %d: %w", rec.Step, err) - } - res := inst.Fire(ctx, event, fireOpts...) - if res.Err != nil { - return fmt.Errorf("replaying step %d: %w", rec.Step, res.Err) - } - if hasTimerEffect(res.Effects) { - sched.Absorb(ctx, res.Effects) - } - if svc != nil { - svc.Absorb(ctx, res.Effects) - } - // A domain effect is intentionally NOT dispatched here: a time-travel read - // applies no side effect. + // A domain effect is never dispatched here: a time-travel read applies no + // side effect. + if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i]); err != nil { + return err } } // A canceled context can stop a replayed settle or tick without an error reaching From dd652452d26c7bad2196e33b8a243f74125a82d8 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 12:26:44 -0700 Subject: [PATCH 06/38] fix(durable): Fire follows the cancel rule, and outcomes replay where they landed Fire joins the rule for a step a context's ending refused: when an actor its state spawned fails to start and an ended context refuses the onError, Fire fails the Handle and records nothing, so Recover can't apply an onError live never applied. A Fire that drove nothing refused records even if its context ends once the kernel has applied the event. state.ActorSystem.WithParentFireObserver replaces TakeParentFireErrors, which no release shipped. It reports each parent Fire with whether it settled an actor, and the outcome. durable uses it for the rule, and to record an actor's output with the Fire that carried it, not the last one, which replay used to give to the wrong transition. Start's and Recover's own spawns' Fires belong to no step and are dropped, replacing the per-step clears. A panic in host code during a step fails the Handle, since the instance may be ahead of its journal. replayActor reads a refusal from the error alone. The docs put Fire under the rule, say a Spawn actor doesn't return after Recover, and that a failed Append may have landed. Signed-off-by: Ray Karnes --- docs/src/content/docs/durable/overview.md | 11 +- durable/CHANGELOG.md | 37 +- durable/README.md | 11 +- durable/actor.go | 87 ++--- durable/doc.go | 5 +- durable/errors.go | 4 + durable/runner.go | 183 +++++++--- durable/service.go | 22 +- durable/step_rule_test.go | 419 ++++++++++++++++++++++ state/CHANGELOG.md | 9 +- state/actor_parent_fire_observer_test.go | 51 +++ state/actor_system.go | 61 ++-- 12 files changed, 734 insertions(+), 166 deletions(-) create mode 100644 durable/step_rule_test.go create mode 100644 state/actor_parent_fire_observer_test.go diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index b501131e..9811e5b9 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -72,8 +72,8 @@ the first time, and replayed verbatim on recovery: | Seam | Wire with | Recorded as | | --- | --- | --- | | **Clock** (timers) | `WithRunnerClock` | `JournalClockRead`, replayed so timers fire at the same recorded instants, wall-clock-independent; armed deadlines survive checkpoint compaction | -| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; 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 failed `Append`, a crash) runs again when the host calls `RunService` | -| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled actor doesn't re-run, and a running one restarts from its initial state on any `Recover` | +| **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 actor doesn't re-run; a running `InvokeActor` actor restarts from its initial state on any `Recover`, and a `Spawn` actor doesn't return | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written: a @@ -140,9 +140,10 @@ context not derived from the step's. A step waiting for the lock stops when its ends. Read the instance with `View`, which takes the lock; `Instance()` is outside it. -A step that may not have been recorded, or a `Tick`, `RunService` or `DeliverToActor` whose -context, or one derived from it, ended during the step, fails the Handle with -`ErrHandleFailed`. So does an effect handler +A step that may not have been recorded fails the Handle with `ErrHandleFailed`. So does a +`Tick`, `RunService` or `DeliverToActor` whose context ended during the step, and any of +the four, `Fire` included, that drove a Fire refused because a context ended, the caller's +or one middleware derived from it. So does an effect handler that returns an error or panics. Before `Recover`, call `Handle.Drain`, which waits until no step of the failed Handle is still recording and no effect is still being sent, so the recovered Handle loads every recorded step and can't send an effect twice. Give `Drain` a diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 847bb337..67c38358 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -48,6 +48,9 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Changed +- **A journal this version writes isn't for an older one.** An actor entry can now say + its parent Fire was refused, which an older `durable` fails `Recover` on. Don't + downgrade a Store this version has written to. - Requires Go 1.27.4. - **A Handle's steps are serialized across goroutines.** `Fire`, `Tick`, `RunService` and `DeliverToActor` hold a lock while they apply to the kernel and record the step, so a @@ -119,15 +122,32 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **A step whose context ended partway isn't journaled.** A canceled `RunService`, `Tick` or `DeliverToActor` used to record a result the live instance never applied, which recovery then committed, or for an actor, failed on. Each now returns `ErrHandleFailed` - wrapping the error and records nothing. One rule covers all three: a step records - nothing once its context ended by the end of the step, or a Fire it drove was refused - with a context's error, which catches a context middleware derived from the caller's. + wrapping the error and records nothing. One rule covers them: a step records nothing + once its context ended by the end of the step, or a Fire it drove was refused with a + context's error, which catches a context middleware derived from the caller's. A + callback that returns its own context error, such as an HTTP client's timeout, counts + as a context ending too. A Fire refused for another reason, such as a failing guard, is still recorded, and replay now meets the same refusal instead of failing Recover on it. After `Recover` - the service stays in flight and - must tolerate running again, the timer is re-armed, and the actor restarts. `Recover` - and `StateAt` now fail on a canceled context, rather than returning state short of the - journal. + the service stays in flight and must tolerate running again, the timer is re-armed, an + `InvokeActor` actor restarts from its initial state, and a `Spawn` actor doesn't + return. `Recover` and `StateAt` now fail on a canceled context, rather than returning + state short of the journal. +- **`Fire` follows the same rule for the actors it spawns.** When an actor a Fire's + state spawned failed to start and a context's ending refused its onError, the Fire was + recorded, and `Recover` then applied the onError live never applied. Now `Fire` returns + `ErrHandleFailed` and records nothing, though its event applied: fire it again on the + recovered Handle. A Fire that drove nothing refused still records, even when its + context ends once the kernel has applied the event. +- **An actor's output replays with the Fire that carried it.** When one delivery drove + several parent Fires, such as an onDone entering a state whose actor then failed to + start, the output was recorded with the last Fire, so replay gave it to the wrong + transition. It's recorded with the settling Fire, which `state`'s new + `ActorSystem.WithParentFireObserver` identifies. +- **A panic during a step fails the Handle.** A panic in host code under the step lock, + such as an actor behavior a Fire's absorb started, left the Handle healthy but ahead of + its journal, so the next step recorded on top of state the journal never held and + `Recover` failed. The Handle now fails first, and the panic goes on to the caller. - **The next step survives a checkpoint that compacts tick barriers.** A checkpoint now records the step that follows it, in a `nextStep` field of its envelope. Recovery used the Trace count, which runs low past a tick barrier, so the next Fire could reuse a @@ -136,7 +156,8 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. with `ErrStepConflict`, and an identical one is acknowledged without a new Record. - **`WithEventData` survives recovery.** `Handle.Fire` records the payload in the new `Record.EventData` and `Record.EventDataError`, and `Recover` and `StateAt` supply it - on replay. This needs `state.FireEventData`, so `durable` requires `state` v1.1.0 or + on replay. This needs `state.FireEventData` (and the observer above needs + `state.ActorSystem.WithParentFireObserver`), so `durable` requires `state` v1.1.0 or later, and its `require` must move there before a `durable` tag. - **Recording-clock buffer race.** Closing a step's `Record` (draining the recording clock) and the clock-read index reads used to mirror timer deadlines diff --git a/durable/README.md b/durable/README.md index 75cde198..b33c5da4 100644 --- a/durable/README.md +++ b/durable/README.md @@ -82,8 +82,8 @@ the first time, and replayed verbatim on recovery: | Seam | Wire with | Recorded as | | --- | --- | --- | | **Clock** (timers) | `WithRunnerClock` | `JournalClockRead`, replayed so timers fire at the same recorded instants, wall-clock-independent; armed deadlines survive checkpoint compaction | -| **Invoked services** | `WithServiceRegistry` + `Handle.RunService` | `JournalServiceResult`; 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 failed `Append`, a crash) runs again when the host calls `RunService` | -| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled actor doesn't re-run, and a running one restarts from its initial state on any `Recover` | +| **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 actor doesn't re-run; a running `InvokeActor` actor restarts from its initial state on any `Recover`, and a `Spawn` actor doesn't return | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written (a @@ -151,9 +151,10 @@ context not derived from the step's. A step waiting for the lock stops when its ends. Read the instance with `View`, which takes the lock; `Instance()` is outside it. -A step that may not have been recorded, or a `Tick`, `RunService` or `DeliverToActor` whose -context, or one derived from it, ended during the step, fails the Handle with -`ErrHandleFailed`. So does an effect handler +A step that may not have been recorded fails the Handle with `ErrHandleFailed`. So does a +`Tick`, `RunService` or `DeliverToActor` whose context ended during the step, and any of +the four, `Fire` included, that drove a Fire refused because a context ended, the caller's +or one middleware derived from it. So does an effect handler that returns an error or panics. Before `Recover`, call `Handle.Drain`, which waits until no step of the failed Handle is still recording and no effect is still being sent, so the recovered Handle loads every recorded step and can't send an effect twice. Give `Drain` a diff --git a/durable/actor.go b/durable/actor.go index 7f5691a3..114a4d44 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -23,8 +23,9 @@ import ( // parent is recorded; on recovery the recorded result is replayed back through the SAME // parent transition the live run drove, so a settled actor never re-runs. This is the // standard durable-execution guarantee: recovery is a pure replay against the parent -// kernel rather than a re-execution of the actor tree. An actor still running at recovery -// restarts from its initial state, because its own state isn't journaled. +// kernel rather than a re-execution of the actor tree. An InvokeActor actor still running +// at recovery restarts from its initial state, because its own state isn't journaled, and +// a Spawn actor doesn't return. // // The Runner wraps the kernel's reusable host driver, state.ActorSystem, which // turns SpawnActor / StopActor effects into running child actors, owns each actor's @@ -105,11 +106,12 @@ type actorMessagePayload struct { // It returns whether the actor was found running: false for a ref that names no live // actor (already settled, stopped, or never spawned), or false and an error when no // palette is wired, the Handle has failed, or ctx ended before the delivery. Once the -// actor ran it returns true with any error. A failed Append, a result that won't encode, -// or a ctx (or one derived from it) that ended during the delivery returns -// ErrHandleFailed and records nothing: on -// a recovered Handle an InvokeActor actor restarts from its initial state, and a Spawn -// actor doesn't return. If another goroutine failed the Handle while this step was +// actor ran it returns true with any error. A result that won't encode, a ctx that ended +// during the delivery, or a parent Fire refused because a context ended (ctx, or one +// middleware derived from it) returns ErrHandleFailed and records nothing: on a +// recovered Handle an InvokeActor actor restarts from its initial state, and a Spawn +// actor doesn't return. A failed Append also returns ErrHandleFailed, but the write may +// have landed anyway, and Recover finds out which. If another goroutine failed the Handle while this step was // recording, it returns true and ErrHandleFailed saying the step was recorded. A failed // Checkpoint returns the plain error, and the delivery is recorded. Resending a recorded // delivery repeats any message it sends the parent. @@ -118,6 +120,7 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef return false, err } defer h.release() + defer h.failOnPanic() if err := h.refuse(ctx); err != nil { return false, err } @@ -126,22 +129,20 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef } before := len(h.inst.History()) - h.clearActorFireErrs() delivered := h.actors.Deliver(h.stepContext(ctx), ref, event) + fires := h.actorFires.take() if !delivered { - h.clearActorFireErrs() return false, nil } // A context that ended during the delivery can make the kernel refuse a parent // Fire it drove. The refused Fire rolls back, so live never applied it, but // journaling the delivery would replay it under a live context, where it applies. // Record nothing. - if err := h.stepCanceled(ctx); err != nil { + if err := h.stepCanceled(ctx, parentFireErrs(fires)...); err != nil { return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) } - output, settled, settleErr := h.actorOutcome() - entries, err := recordActorTransitions(ref.ID, h.inst.History(), before, output, settled, settleErr) + entries, err := recordActorTransitions(ref.ID, h.inst.History()[before:], fires) if err != nil { return true, h.fail(fmt.Errorf("durable: recording actor %q result for %q: %w", ref.ID, h.id, err)) } @@ -174,23 +175,6 @@ func (h *Handle[S, E, C]) ActorRef(id string) (state.ActorRef, bool) { return h.actors.Ref(id) } -// actorOutcome reads the most recently settled actor's output / error from the -// underlying ActorSystem, the outcome the settling parent fire carried. It reports -// whether a settlement occurred at all (so a delivery that only sent a message and -// did not complete the actor records no settle data). -func (h *Handle[S, E, C]) actorOutcome() (output any, settled bool, settleErr error) { - if h.actors == nil { - return nil, false, nil - } - if err := h.actors.LastError(); err != nil { - return nil, true, err - } - if out, ok := h.actors.LastOutput(); ok { - return out, true, nil - } - return nil, false, nil -} - // drainActors returns and clears the actor transitions recorded since the last // drain, so each persisted step carries exactly the transitions that resolved // during it, in fire order. @@ -204,34 +188,30 @@ func (h *Handle[S, E, C]) drainActors() []state.JournalEntry { return out } -// recordActorTransitions builds the JournalActorMessage entries for the parent -// Traces the just-completed delivery appended (those at index before..len). Each -// new Trace is one parent transition the actor system drove; the entry carries that -// transition's event payload. When the actor settled (output or error present), the -// settling onDone / onError fire is the LAST of those Traces — a SendParent message -// fires the parent before the actor drains and completes — so the outcome is -// attributed to the last entry, which records HasData; earlier entries are -// message-driven and carry no separate payload. -func recordActorTransitions(id string, history []state.Trace, before int, output any, settled bool, settleErr error) ([]state.JournalEntry, error) { - if before >= len(history) { - return nil, nil +// recordActorTransitions builds the JournalActorMessage entries for the parent Traces +// a delivery appended, one per parent transition the actor system drove, in fire +// order. Each carries its transition's event payload, and whether the live Fire was +// refused. A Fire that settled an actor also carries the actor's outcome, which it +// passed as event data, so replay re-fires the same onDone or onError with it. fires +// are the actor system's own record of those Fires, matching the traces one for one. +func recordActorTransitions[S comparable](id string, traces []state.Trace, fires []state.ParentFire[S]) ([]state.JournalEntry, error) { + if len(fires) != len(traces) { + return nil, fmt.Errorf("the actor system drove %d parent Fires, but the parent recorded %d", len(fires), len(traces)) } - traces := history[before:] entries := make([]state.JournalEntry, 0, len(traces)) for i, tr := range traces { var mp actorMessagePayload mp.Event = append(json.RawMessage(nil), tr.EventPayload...) mp.Refused = tr.Outcome != state.OutcomeSuccess - // Attribute the actor outcome to the settling fire — the last parent Trace — - // so the onDone / onError transition replays with the recorded done-data / - // error, while a message-driven fire that preceded it replays plainly. - if settled && i == len(traces)-1 { + if fires[i].Settle { mp.HasData = true - if settleErr != nil { - msg := settleErr.Error() + switch out := fires[i].Outcome.(type) { + case error: + msg := out.Error() mp.Error = &msg - } else if output != nil { - raw, err := json.Marshal(output) + case nil: + default: + raw, err := json.Marshal(out) if err != nil { return nil, fmt.Errorf("marshaling actor output: %w", err) } @@ -277,14 +257,13 @@ func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *s } else { res = inst.Fire(ctx, event) } - refused := res.Err != nil || res.Trace.Outcome != state.OutcomeSuccess + // The kernel reports every refusal with an error, so the error alone says whether + // replay was refused. switch { - case refused && mp.Refused: + case res.Err != nil && mp.Refused: return nil // the live run was refused the same way - case refused && res.Err != nil: + case res.Err != nil: return fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, res.Err) - case refused: - return fmt.Errorf("durable: replaying actor %q transition: %s, but the live run's applied", entry.CorrelationID, res.Trace.Outcome) case mp.Refused: return fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) } diff --git a/durable/doc.go b/durable/doc.go index 1d98c5bf..02c49292 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -109,8 +109,9 @@ // Child-machine actors (WithActorPalette): an actor's behavior runs on the live path; // each parent transition the delivery drives is journaled as a JournalActorMessage. On // recovery the recorded transition is re-fired directly through the parent with the -// recorded done-data, so a settled actor never re-runs. An actor still running at -// recovery restarts from its initial state, because its own state isn't journaled. +// recorded done-data, so a settled actor never re-runs. An InvokeActor actor still +// running at recovery restarts from its initial state, because its own state isn't +// journaled, and a Spawn actor doesn't return. // // # Idempotent effect dispatch // diff --git a/durable/errors.go b/durable/errors.go index 9e58e30d..f24f15e3 100644 --- a/durable/errors.go +++ b/durable/errors.go @@ -62,6 +62,10 @@ var ( // - a Tick, RunService or DeliverToActor ran while its context ended, so a Fire it // drove may have been refused: it had already consumed the timer, service or // delivery, so it can't simply refuse the way Fire does; + // - a step, Fire included, drove a Fire that a context's ending refused, such as a + // spawned actor's onError: Recover restores the state from before the step, so a + // Fire's event must be fired again; + // - host code panicked during a step; // - an effect handler failed. // Call Handle.Drain, then Recover a new Handle with the same options to continue, // unless the cause is ErrFenced: then a newer owner holds the instance, so stop. diff --git a/durable/runner.go b/durable/runner.go index b76ab469..ae481ee1 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -102,9 +102,10 @@ func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st // lock; Instance returns it outside the lock. A stateless Runner.Fire builds its own // Handle, so it isn't serialized with this one. // -// A step that applied to the kernel but may not have been recorded, or a Tick, RunService -// or DeliverToActor whose context, or one derived from it, ended during the step, -// leaves the Handle out of step with the journal. That call and every later one return ErrHandleFailed, wrapping the cause, +// A step that applied to the kernel but may not have been recorded leaves the Handle out +// of step with the journal. So does a Tick, RunService or DeliverToActor whose context +// ended during the step, and any step, Fire included, that drove a Fire refused because +// a context ended, the caller's or one middleware derived from it. That call and every later one return ErrHandleFailed, wrapping the cause, // which can be a context that ended during the Store write. Before recovering, call // Drain: a step on another goroutine may still be recording, which a recovered Handle // wouldn't load, or sending an effect, which it would send again. Recovering a healthy @@ -131,8 +132,9 @@ type Handle[S comparable, E comparable, C any] struct { svc *state.ServiceRunner[S, E, C] // host driver for invoked services, nil when none wired svcBuf *[]state.JournalEntry // recording service-result accumulator, flushed per step - actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired - actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step + actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired + actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step + actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step out outbox // what a step leaves behind once it releases the step lock } @@ -532,25 +534,29 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // transition a delivery drives for replay. A machine with no actor palette wired // spawns no actor and records no actor entries. actorBuf := make([]state.JournalEntry, 0) - actors := r.newActorSystem(inst) + actors, actorFires := r.newActorSystem(inst) if actors != nil { actors.Absorb(ctx, inst.StartEffects()) + // A parent Fire a starting actor drove (a failed spawn's onError) belongs to no + // recorded step, so it mustn't reach the first step's check. + actorFires.take() } return &Handle[S, E, C]{ - runner: r, - id: id, - inst: inst, - nextStep: 0, - sched: state.NewScheduler(inst), - recClock: recClock, - timers: map[string]pendingTimer{}, - svc: svc, - svcBuf: &svcBuf, - actors: actors, - actorBuf: &actorBuf, - lock: make(chan struct{}, 1), - out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, + runner: r, + id: id, + inst: inst, + nextStep: 0, + sched: state.NewScheduler(inst), + recClock: recClock, + timers: map[string]pendingTimer{}, + svc: svc, + svcBuf: &svcBuf, + actors: actors, + actorBuf: &actorBuf, + actorFires: actorFires, + lock: make(chan struct{}, 1), + out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, }, nil } @@ -565,17 +571,54 @@ func (r *Runner[S, E, C]) newServiceRunner(inst *state.Instance[S, E, C]) *state } // newActorSystem builds the kernel host driver for child-machine actors bound to -// inst, registering each behavior in the configured palette, or nil when no actor -// palette was wired (a machine that spawns no actor needs none). -func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) *state.ActorSystem[S, E, C] { +// inst, registering each behavior in the configured palette, and the collector of the +// parent Fires it drives. Both are nil when no actor palette was wired (a machine +// that spawns no actor needs none). +func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) (*state.ActorSystem[S, E, C], *parentFires[S]) { if len(r.cfg.actorPalette) == 0 { - return nil + return nil, nil } - sys := state.NewActorSystem(inst) + fires := &parentFires[S]{} + sys := state.NewActorSystem(inst).WithParentFireObserver(fires.note) for src, behavior := range r.cfg.actorPalette { sys.Register(src, behavior) } - return sys + return sys, fires +} + +// parentFires collects the parent Fires an actor system drives, so the step that drove +// them can check and record them. +type parentFires[S comparable] struct { + mu sync.Mutex + fires []state.ParentFire[S] +} + +func (p *parentFires[S]) note(pf state.ParentFire[S]) { + p.mu.Lock() + p.fires = append(p.fires, pf) + p.mu.Unlock() +} + +// take returns the Fires noted since the last take, in fire order, and forgets them. +// It's safe on a nil collector, which has none. +func (p *parentFires[S]) take() []state.ParentFire[S] { + if p == nil { + return nil + } + p.mu.Lock() + defer p.mu.Unlock() + fires := p.fires + p.fires = nil + return fires +} + +// parentFireErrs returns each parent Fire's error, nil ones included. +func parentFireErrs[S comparable](fires []state.ParentFire[S]) []error { + errs := make([]error, len(fires)) + for i := range fires { + errs[i] = fires[i].Result.Err + } + return errs } // Fire drives one event through a durable instance identified by id, loading and @@ -605,6 +648,14 @@ func (r *Runner[S, E, C]) Fire(ctx context.Context, id InstanceID, event E, opts // goroutine failed the Handle while this step was recording, Fire returns // ErrHandleFailed saying the step was recorded; Recover sends its effects. // +// A Fire the kernel refuses, because ctx ended or for any other reason, returns that +// error, records nothing and leaves the Handle usable. When the event applies, an actor +// the step spawned can fail and route its onError through the instance; if a context +// ending, ctx or one derived from it, refuses that onError, Fire fails the Handle with +// ErrHandleFailed and records nothing, though the event applied. Recover restores the +// state from before the event, so fire it again on the recovered Handle. A Fire that +// drove nothing refused records even if ctx ends once the kernel has applied it. +// // A state.WithEventData payload reaches the transition's Assign as the Runner's // EventDataDecoder rebuilds it from the payload's JSON form, live and on replay alike, so // both see the same value. Decode it as the type the caller passed: a payload that @@ -632,10 +683,11 @@ func (h *Handle[S, E, C]) Fire(ctx context.Context, event E, opts ...state.FireO return res, h.finishStep(ctx, rec, des) } -// lockedFireStep runs fireStep and releases the step lock however it returns, a panic -// in host code included. +// lockedFireStep runs fireStep and releases the step lock however it returns. A panic +// in host code fails the Handle first, since the kernel may have applied the event. func (h *Handle[S, E, C]) lockedFireStep(ctx context.Context, event E, opts []state.FireOption) (state.FireResult[S], *Record, []dispatchableEffect, error) { defer h.release() + defer h.failOnPanic() return h.fireStep(h.stepContext(ctx), event, opts) } @@ -664,6 +716,15 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi // timer, and each driver must see its effects. h.absorbDrivers(ctx, res.Effects) + // An actor the absorb spawned can fail and route its onError through the parent. + // A context that ended can refuse that Fire, so live never applied it, and + // journaling this step would let Recover re-spawn the actor under a live context, + // where the onError applies. Record nothing. A Fire that drove nothing refused + // applied whole, so it records even when ctx ended afterward. + if err := refusedByContext(parentFireErrs(h.actorFires.take())...); err != nil { + return res, nil, nil, h.fail(fmt.Errorf("durable: firing %q: %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 @@ -752,15 +813,15 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro return nil, err } defer h.release() + defer h.failOnPanic() if err := h.refuse(ctx); err != nil { return nil, err } - h.clearActorFireErrs() results := h.sched.Tick(h.stepContext(ctx)) // A context that ended partway can make the kernel refuse a due timer's Fire after // the scheduler consumed it. Journaling that would commit on recovery what live never // applied, so record nothing: Recover re-arms the timers. - if err := h.stepCanceled(ctx, resultErrs(results)...); err != nil { + if err := h.stepCanceled(ctx, append(resultErrs(results), parentFireErrs(h.actorFires.take())...)...); err != nil { return results, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, err)) } @@ -964,7 +1025,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // settled. The live actors at the resume point are armed once, after replay, // from the final configuration's StartEffects. actorBuf := make([]state.JournalEntry, 0) - actors := r.newActorSystem(inst) + actors, actorFires := r.newActorSystem(inst) // armed mirrors the scheduler's pending timers re-established by tail replay, // with their recorded deadlines, so a persisted-but-compacted timer is re-armed @@ -1025,6 +1086,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // parent rather than re-running behavior. if actors != nil { actors.Absorb(ctx, inst.StartEffects()) + // A parent Fire a re-spawned actor drove (a failed spawn's onError) belongs to no + // recorded step, so it mustn't reach the next step's check. + actorFires.take() } // Re-arm any timer that was pending at the checkpoint but whose arming @@ -1080,19 +1144,20 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } return &Handle[S, E, C]{ - runner: r, - id: id, - inst: inst, - nextStep: next, - sched: sched, - recClock: recClock, - timers: armed, - svc: svc, - svcBuf: &svcBuf, - actors: actors, - actorBuf: &actorBuf, - lock: make(chan struct{}, 1), - out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, + runner: r, + id: id, + inst: inst, + nextStep: next, + sched: sched, + recClock: recClock, + timers: armed, + svc: svc, + svcBuf: &svcBuf, + actors: actors, + actorBuf: &actorBuf, + actorFires: actorFires, + lock: make(chan struct{}, 1), + out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, }, nil } @@ -1277,18 +1342,22 @@ func isContextErr(err error) bool { // 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 or among the parent Fires the actor system drove. A refusal with any -// other cause, such as a failing guard, is deterministic: the step is journaled, and -// replay meets the same refusal. It drains the actor system's record of parent Fire -// errors either way. +// a Fire refused with a context's error (one middleware derived from ctx included) +// among errs, which hold the errors of the Fires the step drove, the parent Fires its +// actors drove among them. These steps check ctx itself because a service or timer +// they consumed can end on it without any Fire reporting it. A refusal with any other +// cause, such as a failing guard, is deterministic: the step is journaled, and replay +// meets the same refusal. func (h *Handle[S, E, C]) stepCanceled(ctx context.Context, errs ...error) error { - if h.actors != nil { - errs = append(errs, h.actors.TakeParentFireErrors()...) - } if err := ctx.Err(); err != nil { return err } + return refusedByContext(errs...) +} + +// refusedByContext returns the first of errs that is a context's error: a Fire refused +// because the context it ran under ended. +func refusedByContext(errs ...error) error { for _, err := range errs { if err != nil && isContextErr(err) { return err @@ -1297,11 +1366,13 @@ func (h *Handle[S, E, C]) stepCanceled(ctx context.Context, errs ...error) error return nil } -// clearActorFireErrs drops parent Fire errors recorded before a step began, so -// stepCanceled sees only the step's own. -func (h *Handle[S, E, C]) clearActorFireErrs() { - if h.actors != nil { - h.actors.TakeParentFireErrors() +// failOnPanic fails the Handle when host code panicked during a step, since the kernel +// may have applied what the step never recorded, then lets the panic go on. A step +// defers it after release, so it runs first, under the step lock. +func (h *Handle[S, E, C]) failOnPanic() { + if p := recover(); p != nil { + _ = h.fail(fmt.Errorf("durable: a step of %q panicked: %v", h.id, p)) + panic(p) } } diff --git a/durable/service.go b/durable/service.go index 9a4bc1ee..c9326df6 100644 --- a/durable/service.go +++ b/durable/service.go @@ -22,9 +22,9 @@ import ( // recorded result is replayed back through the same settle seam, and that service is // NEVER re-invoked. This is the standard durable-execution guarantee: recovery is a pure // replay against the kernel rather than a re-execution of the host's services. A result -// that wasn't recorded, after a context canceled during the service, a failed Append or a -// crash, has nothing to replay, so it stays in flight, runs again when the host calls -// RunService, and must tolerate a second run. +// that wasn't recorded, after a context canceled during the service, a crash, or a failed +// Append whose write didn't land, has nothing to replay, so it stays in flight, runs again +// when the host calls RunService, and must tolerate a second run. // // The Runner wraps the kernel's reusable host driver, state.ServiceRunner, which // turns StartService / StopService effects into real ServiceFn executions and @@ -89,11 +89,13 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { // false and an error when no registry is wired, the Handle has failed, or ctx ended // before the service started. // -// Once the service has run, it returns true with any error. A failed Append, a result -// that won't encode, or a ctx (or one derived from it) that ended during the service or -// while its settle's effects were absorbed (even after a clean settle) returns -// ErrHandleFailed and records nothing: a recovered Handle has the service in flight again, and RunService -// runs it a second time. If another goroutine failed the Handle while this step was +// Once the service has run, it returns true with any error. A result that won't encode, +// a ctx that ended during the service or while its settle's effects were absorbed (even +// after a clean settle), or a Fire the settle drove refused because a context ended (ctx, +// or one middleware derived from it) returns ErrHandleFailed and records nothing: a +// recovered Handle has the service in flight again, and RunService runs it a second time. +// A failed Append also returns ErrHandleFailed, but the write may have landed anyway: +// Recover finds out, and the service runs again only if the result isn't in the journal. If another goroutine failed the Handle while this step was // recording, it returns the result, true and ErrHandleFailed saying the step was // recorded. That error also matches the cause, so test ErrHandleFailed first: it alone // means Recover is needed. A failed Checkpoint returns the plain error, and the result @@ -103,6 +105,7 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire return state.FireResult[S]{}, false, err } defer h.release() + defer h.failOnPanic() if err := h.refuse(ctx); err != nil { return state.FireResult[S]{}, false, err } @@ -113,7 +116,6 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire return state.FireResult[S]{}, false, nil } - h.clearActorFireErrs() results := h.svc.Tick(h.stepContext(ctx), id) if len(results) == 0 { return state.FireResult[S]{}, false, nil @@ -131,7 +133,7 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire // 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. - if err := h.stepCanceled(ctx, res.Err); err != nil { + if err := h.stepCanceled(ctx, append([]error{res.Err}, parentFireErrs(h.actorFires.take())...)...); err != nil { return res, true, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, err)) } diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go new file mode 100644 index 00000000..e3571446 --- /dev/null +++ b/durable/step_rule_test.go @@ -0,0 +1,419 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// stepCtx is the JSON-marshalable context for the step-rule fixtures. +type stepCtx struct { + Notes []string `json:"notes"` +} + +type stepMachine = *state.Machine[string, string, stepCtx] + +type stepOption = durable.Option[string, string, stepCtx] + +// cancelOn is a context middleware that fires event under a context derived from the +// caller's and already ended, while the caller's stays live. +func cancelOn(event string) state.Middleware[string, string, stepCtx] { + return func(next state.FireFunc[string, string, stepCtx]) state.FireFunc[string, string, stepCtx] { + return func(ctx context.Context, ev string) state.FireResult[string] { + if ev == event { + derived, cancel := context.WithCancel(ctx) + cancel() + return next(derived, ev) + } + return next(ctx, ev) + } + } +} + +// failingSpawn is an actor behavior that never starts: it runs hook, if any, then +// fails, so the parent's onError routes. +func failingSpawn(hook func()) state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + if hook != nil { + hook() + } + return nil, errors.New("the child can't start") + } +} + +// finishingChild is an actor that completes when delivered "finish". +func finishingChild() state.ActorBehavior { + var runs int64 + return counterChild(&runs) +} + +func wantFailedWithCancel(t *testing.T, what string, err error) { + t.Helper() + if !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("%s = %v, want ErrHandleFailed wrapping context.Canceled", what, err) + } +} + +func wantTail(t *testing.T, store durable.Store, id durable.InstanceID, want int) { + t.Helper() + if got := tailLen(t, store, id); got != want { + t.Fatalf("journal has %d records, want %d", got, want) + } +} + +// spawnOnStartMachine is idle -start-> spawning, a state whose actor can't start, so +// the absorb of Fire's own effects routes spawnFailed through the parent. +func spawnOnStartMachine(mw state.Middleware[string, string, stepCtx]) stepMachine { + b := state.ForgeFor[stepCtx]("spawner"). + Actor("spawnFail"). + State("idle"). + State("spawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle") + if mw != nil { + b = b.Use(mw) + } + return b.Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed"). + Quench() +} + +// TestFire_SpawnRefusedByAnEndedContext_RecordsNothing proves Fire follows the one +// rule: when the onError of an actor its absorb spawned is refused because a context +// ended, whether the caller's or one derived from it, Fire fails the Handle and +// records nothing, so Recover can't apply the onError live never applied. +func TestFire_SpawnRefusedByAnEndedContext_RecordsNothing(t *testing.T) { + for _, tc := range []struct { + name string + derived bool + }{{"the caller's context", false}, {"a derived context", true}} { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + turn, cancel := context.WithCancel(ctx) + defer cancel() + var mw state.Middleware[string, string, stepCtx] + hook := cancel + if tc.derived { + mw, hook = cancelOn("spawnFailed"), nil + } + m := spawnOnStartMachine(mw) + store := durable.NewMemStore() + id := durable.InstanceID("spawn-on-start") + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(hook)})} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + before := tailLen(t, store, id) + _, err = h.Fire(turn, "start") + wantFailedWithCancel(t, "Fire", err) + wantTail(t, store, id, before) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "idle" { + t.Fatalf("recovered state = %q, want idle, since nothing was recorded", got) + } + }) + } +} + +// messengerUsing is messengerMachine with mw installed. +func messengerUsing(mw state.Middleware[string, string, stepCtx]) stepMachine { + return state.ForgeFor[stepCtx]("messenger"). + Actor("spawnPinger"). + State("listening").InvokeActor("spawnPinger", state.WithInvokeOnDone("pingerDone")). + State("heard"). + Initial("listening"). + Use(mw). + Transition("listening").On("pong").GoTo("heard"). + Transition("heard").On("pingerDone").GoTo("heard"). + Quench() +} + +// TestDeliverToActor_MessageRefusedByADerivedContext_RecordsNothing proves a delivery +// whose child's message to the parent (SendParent) is refused by a context derived +// from the caller's, while the caller's is live, fails the Handle and records nothing. +func TestDeliverToActor_MessageRefusedByADerivedContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := messengerUsing(cancelOn("pong")) + store := durable.NewMemStore() + id := durable.InstanceID("msg-derived") + var msgs int64 + palette := map[string]state.ActorBehavior{"spawnPinger": pingerChild(&msgs)} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, stepCtx](palette)). + Start(ctx, id, stepCtx{}, state.WithInitialState("listening")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("messenger", "listening", 0)) + if !ok { + t.Fatal("no actor ref for the pinger") + } + before := tailLen(t, store, id) + _, err = h.DeliverToActor(ctx, ref, "ping") + wantFailedWithCancel(t, "DeliverToActor", err) + wantTail(t, store, id, before) +} + +// TestDeliverToActor_SpawnRefusedByADerivedContext_RecordsNothing proves a delivery +// whose parent transition enters a state with an actor that can't start, and whose +// onError a derived context refuses, fails the Handle and records nothing. +func TestDeliverToActor_SpawnRefusedByADerivedContext_RecordsNothing(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("relay"). + Actor("spawnChild"). + Actor("spawnFail"). + State("supervising").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("respawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("supervising"). + Use(cancelOn("spawnFailed")). + Transition("supervising").On("childDone").GoTo("respawning"). + Transition("respawning").On("spawnFailed").GoTo("failed"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("respawn-derived") + palette := map[string]state.ActorBehavior{"spawnChild": finishingChild(), "spawnFail": failingSpawn(nil)} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, stepCtx](palette)). + Start(ctx, id, stepCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("relay", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for the child") + } + before := tailLen(t, store, id) + _, err = h.DeliverToActor(ctx, ref, "finish") + wantFailedWithCancel(t, "DeliverToActor", err) + wantTail(t, store, id, before) +} + +// expiringMachine is idle -arm-> waiting -(after 1s: expire)-> next, with mw +// installed and next's declarations added by decl. +func expiringMachine(mw state.Middleware[string, string, stepCtx], decl func(*state.Builder[string, string, stepCtx]) *state.Builder[string, string, stepCtx]) stepMachine { + b := state.ForgeFor[stepCtx]("expiring"). + State("idle"). + State("waiting") + b = decl(b) + b = b.Initial("idle") + if mw != nil { + b = b.Use(mw) + } + return b.Transition("idle").On("arm").GoTo("waiting"). + Transition("waiting").After(time.Second).On("expire").GoTo("next"). + Quench() +} + +func doneNext(b *state.Builder[string, string, stepCtx]) *state.Builder[string, string, stepCtx] { + return b.State("next").Final() +} + +// startArmed starts m with opts, a fake clock, and fires arm, so a 1s timer is armed. +func startArmed(t *testing.T, m stepMachine, store durable.Store, id durable.InstanceID, opts ...stepOption) (*durable.Handle[string, string, stepCtx], *state.FakeClock, []stepOption) { + t.Helper() + fc := state.NewFakeClock(epoch) + opts = append(opts, durable.WithRunnerClock[string, string, stepCtx](fc)) + h, err := durable.NewRunner(m, store, opts...).Start(context.Background(), id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(context.Background(), "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + return h, fc, opts +} + +// TestTick_RefusedByADerivedContext_RecordsNothing proves a Tick whose timer's Fire a +// derived context refuses, while the caller's is live, fails the Handle and records +// nothing. +func TestTick_RefusedByADerivedContext_RecordsNothing(t *testing.T) { + m := expiringMachine(cancelOn("expire"), doneNext) + store := durable.NewMemStore() + id := durable.InstanceID("tick-derived") + h, fc, _ := startArmed(t, m, store, id) + before := tailLen(t, store, id) + fc.Advance(time.Second) + _, err := h.Tick(context.Background()) + wantFailedWithCancel(t, "Tick", err) + wantTail(t, store, id, before) +} + +// spawnAtStartMachine starts in spawning, whose actor can't start and whose onError a +// derived context refuses, so Start's and Recover's own spawn drive a refused parent +// Fire that belongs to no step. +func spawnAtStartMachine() stepMachine { + return state.ForgeFor[stepCtx]("spawn-at-start"). + Actor("spawnFail"). + State("spawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("poked"). + State("failed").Final(). + Initial("spawning"). + Use(cancelOn("spawnFailed")). + Transition("spawning").On("spawnFailed").GoTo("failed"). + Transition("spawning").On("poke").GoTo("poked"). + Quench() +} + +// TestStartAndRecover_SpawnRefusal_DoesNotFailTheNextStep proves a parent Fire +// refused while Start or Recover spawned the resume point's actors isn't charged to +// the next step, which records normally. +func TestStartAndRecover_SpawnRefusal_DoesNotFailTheNextStep(t *testing.T) { + ctx := context.Background() + m := spawnAtStartMachine() + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(nil)})} + t.Run("after Start", func(t *testing.T) { + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store, opts...).Start(ctx, "started", stepCtx{}, state.WithInitialState("spawning")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + }) + t.Run("after Recover", func(t *testing.T) { + store := durable.NewMemStore() + if _, err := durable.NewRunner(m, store, opts...).Start(ctx, "recovered", stepCtx{}, state.WithInitialState("spawning")); err != nil { + t.Fatalf("Start: %v", err) + } + h, err := durable.Recover(ctx, m, store, "recovered", opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + }) +} + +// TestFire_ContextEndedAfterACleanApply_Records proves a Fire that drove nothing +// refused applied whole, so it records and returns no error even when its context +// ended after the kernel applied the event, here while the step armed its timer. +func TestFire_ContextEndedAfterACleanApply_Records(t *testing.T) { + ctx := context.Background() + turn, cancel := context.WithCancel(ctx) + defer cancel() + m := expiringMachine(nil, doneNext) + store := durable.NewMemStore() + id := durable.InstanceID("clean-apply") + clk := &countingClock{Clock: state.NewFakeClock(epoch)} + h, err := durable.NewRunner(m, store, durable.WithRunnerClock[string, string, stepCtx](clk)). + Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + before := tailLen(t, store, id) + clk.onRead = func(int) { cancel() } // arming the timer, after the kernel returned + _, err = h.Fire(turn, "arm") + clk.onRead = nil + if turn.Err() == nil { + t.Fatal("the test didn't end the context") + } + if err != nil { + t.Fatalf("Fire = %v, want the clean step recorded", err) + } + wantTail(t, store, id, before+1) + if got := h.Instance().Current(); got != "waiting" { + t.Fatalf("state = %q, want waiting", got) + } +} + +// noteMachine records each event its transitions take, with the data a settle +// carried, so a recovered context shows which Fire got the actor's output. +func noteMachine() stepMachine { + note := func(prefix string) func(state.AssignCtx[stepCtx]) stepCtx { + return func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, fmt.Sprintf("%s:%v", prefix, in.Event)) + return c + } + } + return state.ForgeFor[stepCtx]("noter"). + Reducer("noteDone", note("done")). + Reducer("noteFail", note("fail")). + Actor("spawnChild"). + Actor("spawnFail"). + State("supervising").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("respawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("supervising"). + Transition("supervising").On("childDone").GoTo("respawning").Assign("noteDone"). + Transition("respawning").On("spawnFailed").GoTo("failed").Assign("noteFail"). + Quench() +} + +// TestDeliverToActor_OutcomeGoesToTheSettlingFire proves that when one delivery drives +// several parent Fires, the actor's output is recorded with the Fire that settled it, +// not the last one, so Recover reaches the live context. +func TestDeliverToActor_OutcomeGoesToTheSettlingFire(t *testing.T) { + ctx := context.Background() + m := noteMachine() + store := durable.NewMemStore() + id := durable.InstanceID("outcome") + var runs int64 + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "spawnChild": counterChild(&runs), + "spawnFail": failingSpawn(nil), + })} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("noter", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for the child") + } + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + live := h.Instance().Entity().Notes + if len(live) != 2 || live[0] != "done:out-1" || live[1] != "fail:spawnFailed" { + t.Fatalf("live notes = %v, want the output on childDone, then the plain spawnFailed", live) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Entity().Notes; fmt.Sprint(got) != fmt.Sprint(live) { + t.Fatalf("recovered notes = %v, want the live %v", got, live) + } +} + +// TestFire_PanicInHostCode_FailsTheHandle proves a panic in host code during a step, +// here an actor behavior the step's absorb spawned after the kernel applied the event, +// fails the Handle, since the instance is ahead of the journal, and a later step can't +// record on top of it. +func TestFire_PanicInHostCode_FailsTheHandle(t *testing.T) { + ctx := context.Background() + m := spawnOnStartMachine(nil) + store := durable.NewMemStore() + id := durable.InstanceID("panics") + panicking := func(map[string]any) (state.ActorInstance, error) { panic("the child exploded") } + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": panicking})). + Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + before := tailLen(t, store, id) + func() { + defer func() { + if recover() == nil { + t.Fatal("Fire didn't panic") + } + }() + _, _ = h.Fire(ctx, "start") + }() + wantTail(t, store, id, before) + if _, err = h.Fire(ctx, "spawnFailed"); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("Fire after the panic = %v, want ErrHandleFailed", err) + } + wantTail(t, store, id, before) +} diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 16f19426..0a3c86b7 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -13,10 +13,11 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Added -- **`ActorSystem.TakeParentFireErrors`** returns the errors of the parent Fires the - system drove since the last call, and clears them, so a host that records a delivery - or spawn can tell a parent transition refused because its context ended from one - that applied. +- **`ActorSystem.WithParentFireObserver`** calls a function with each parent Fire the + system drives (a `ParentFire`: its result, refused ones included, and whether it + settled an actor, with the actor's outcome), so a host that records a delivery or spawn + can tell a parent transition refused because its context ended from one that applied, + and which Fire carried the actor's output. - **`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. diff --git a/state/actor_parent_fire_observer_test.go b/state/actor_parent_fire_observer_test.go new file mode 100644 index 00000000..2cd99ce9 --- /dev/null +++ b/state/actor_parent_fire_observer_test.go @@ -0,0 +1,51 @@ +package state_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestActorSystem_WithParentFireObserver_SeesEachParentFire proves the observer gets +// every parent Fire the system drives, in fire order, a refused one included with its +// error, and marks the Fire that settled the actor: here a child's message to the +// parent, then its onDone, which a guard refuses. +func TestActorSystem_WithParentFireObserver_SeesEachParentFire(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("watcher"). + Guard("never", func(state.GuardCtx[*trec]) bool { return false }). + Actor("relay"). + State("watching").InvokeActor("relay", state.WithInvokeOnDone("relayDone")). + State("finished").Final(). + Initial("watching"). + Transition("watching").On("pong").GoTo("watching"). + Transition("watching").On("relayDone").GoTo("finished").When("never"). + Quench() + parent := m.Cast(&trec{}, state.WithInitialState("watching")) + var seen []state.ParentFire[string] + sys := state.NewActorSystem(parent). + Register("relay", relayBehavior()). + WithParentFireObserver(func(pf state.ParentFire[string]) { seen = append(seen, pf) }) + sys.Absorb(ctx, parent.StartEffects()) + ref, ok := sys.Ref(state.ActorID("watcher", "watching", 0)) + if !ok { + t.Fatal("the relay child didn't spawn") + } + + sys.Deliver(ctx, ref, "ping") // the child sends the parent "pong" + sys.Deliver(ctx, ref, "finish") + + if len(seen) != 2 { + t.Fatalf("observed %d parent Fires, want 2 (the message, then the onDone)", len(seen)) + } + if r := seen[0].Result; r.Err != nil || r.Trace.Event != "pong" || seen[0].Settle { + t.Fatalf("first = %q, err %v, settle %v, want the applied pong message", r.Trace.Event, r.Err, seen[0].Settle) + } + if seen[1].Result.Err == nil || !seen[1].Settle { + t.Fatalf("second = err %v, settle %v, want the guard-refused onDone, settling", seen[1].Result.Err, seen[1].Settle) + } + if got := parent.Current(); got != "watching" { + t.Fatalf("parent = %q, want watching after the refused onDone", got) + } +} diff --git a/state/actor_system.go b/state/actor_system.go index 09060a82..1556484e 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -155,10 +155,9 @@ type ActorSystem[S comparable, E comparable, C any] struct { // never silently swallowed. Read through LastEscalation. lastEscalation *ActorEscalation - // parentFireErrs holds the errors of the parent Fires the system drove since the - // last TakeParentFireErrors, so a host can tell a parent transition refused - // because its context ended from one that applied. Guarded by mu. - parentFireErrs []error + // parentFireObserver, when set, is called with each parent Fire the system + // drives. Set with WithParentFireObserver; guarded by mu. + parentFireObserver func(ParentFire[S]) // escalationHandler is the optional host policy invoked for each escalation. It // is nil by default — the default escalation behavior (record + inspect) needs no @@ -392,7 +391,7 @@ func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err return } res := s.parent.Fire(ctx, ev) - s.noteParentFire(res) + s.noteParentFire(ParentFire[S]{Result: res}) s.Absorb(ctx, res.Effects) } @@ -674,7 +673,7 @@ func (s *ActorSystem[S, E, C]) fireParentFrom(ctx context.Context, event any, se s.mu.Unlock() res := s.parent.Fire(ctx, ev) - s.noteParentFire(res) + s.noteParentFire(ParentFire[S]{Result: res}) s.Absorb(ctx, res.Effects) s.mu.Lock() @@ -736,7 +735,7 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any payload = output } res := s.parent.Fire(ctx, ev, WithEventData(payload)) - s.noteParentFire(res) + s.noteParentFire(ParentFire[S]{Result: res, Settle: true, Outcome: payload}) s.Absorb(ctx, res.Effects) return res, true } @@ -797,24 +796,42 @@ func (s *ActorSystem[S, E, C]) LastError() error { return s.lastOutcome.err } -// noteParentFire records a parent Fire's error for TakeParentFireErrors. -func (s *ActorSystem[S, E, C]) noteParentFire(res FireResult[S]) { - if res.Err == nil { - return - } +// ParentFire is one parent Fire an ActorSystem drove, as WithParentFireObserver +// reports it. +type ParentFire[S comparable] struct { + // Result is the parent Fire's result. A refused Fire carries its error. + Result FireResult[S] + // Settle reports that the Fire routed a settled actor's onDone or onError, which + // carried Outcome as its event data (WithEventData). A message the actor sent the + // parent, or a failed spawn's onError, carries none. + Settle bool + // Outcome is the settled actor's output, or its error, when Settle is set. + Outcome any +} + +// WithParentFireObserver calls observe with each parent Fire the system drives (an +// actor's onDone or onError, a message it sends the parent, a failed spawn's +// onError), in fire order, refused ones included, after the Fire returns and before +// its effects are absorbed. A host that records what a delivery or spawn drove uses +// it: a parent Fire refused because the context it ran under ended reports that +// context's error, so the host can tell a refusal it can't replay from one it can, +// and Settle and Outcome say which Fire carried an actor's outcome, and what it was. +// observe runs on the goroutine that drove the Fire, with no lock of the system's +// held, so it may read the system but must not drive it. Setting it returns the +// system for chaining. +func (s *ActorSystem[S, E, C]) WithParentFireObserver(observe func(ParentFire[S])) *ActorSystem[S, E, C] { s.mu.Lock() - s.parentFireErrs = append(s.parentFireErrs, res.Err) + s.parentFireObserver = observe s.mu.Unlock() + return s } -// TakeParentFireErrors returns the errors of the parent Fires the system has driven -// since the last call, in order, and clears them. A parent Fire refused because the -// context it ran under ended reports that context's error, so a host that records -// what a delivery or spawn drove can tell a refusal it can't replay from one it can. -func (s *ActorSystem[S, E, C]) TakeParentFireErrors() []error { +// noteParentFire hands a parent Fire to the observer, if one is set. +func (s *ActorSystem[S, E, C]) noteParentFire(pf ParentFire[S]) { s.mu.Lock() - defer s.mu.Unlock() - errs := s.parentFireErrs - s.parentFireErrs = nil - return errs + observe := s.parentFireObserver + s.mu.Unlock() + if observe != nil { + observe(pf) + } } From 654f6509c52a815a62f9ee37180dfb5fd6872317 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 12:42:36 -0700 Subject: [PATCH 07/38] fix(durable): replay actor refusals as live ran them A settle the parent refused leaves the actor settled, but Recover spawned it again from the parent's state. Replay now tracks those actors, forgets one a later step stops or spawns again, and Recover doesn't re-spawn the rest. An actor entry's refusal comes from the parent Fire's error, which is what replay checks, so a Fire that middleware denied before the kernel saw it is recorded as refused and replays the same way instead of failing Recover. A Tick that fired no timer, or a delivery that drove no parent Fire, consumed nothing, so its context ending no longer fails the Handle. state.ParentFire reports a settled actor's Output and Err separately, so an output that happens to implement error isn't journaled as a failure. The docs say an older journal replays as it did, and what an older durable does with one this version writes. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 18 +++++-- durable/actor.go | 62 ++++++++++++++-------- durable/runner.go | 87 +++++++++++++++++++++++++++---- durable/service.go | 11 ++-- durable/step_rule_test.go | 107 ++++++++++++++++++++++++++++++++++++++ state/CHANGELOG.md | 5 +- state/actor_system.go | 22 ++++---- 7 files changed, 259 insertions(+), 53 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 67c38358..968b5f6d 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -49,8 +49,13 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Changed - **A journal this version writes isn't for an older one.** An actor entry can now say - its parent Fire was refused, which an older `durable` fails `Recover` on. Don't - downgrade a Store this version has written to. + its parent Fire was refused, which an older `durable` fails `Recover` on, or, for an + entry with no event, replays as the zero event. Don't downgrade a Store this version + has written to. +- **A journal an older version wrote replays as it did.** Its actor entries carry no + refusal, so `Recover` still fails on one whose parent Fire was refused, and an output + recorded with a delivery's last Fire still replays into that transition. Only steps + this version records get the fixes below. - Requires Go 1.27.4. - **A Handle's steps are serialized across goroutines.** `Fire`, `Tick`, `RunService` and `DeliverToActor` hold a lock while they apply to the kernel and record the step, so a @@ -119,7 +124,7 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. the step that tried it. A retry the Store refuses as not advancing means the first write landed, and counts as written. Any other checkpoint failure is returned, and after that only the next step the policy makes due tries again. -- **A step whose context ended partway isn't journaled.** A canceled `RunService`, `Tick` +- **A Tick, RunService or DeliverToActor whose context ended partway isn't journaled.** A canceled `RunService`, `Tick` or `DeliverToActor` used to record a result the live instance never applied, which recovery then committed, or for an actor, failed on. Each now returns `ErrHandleFailed` wrapping the error and records nothing. One rule covers them: a step records nothing @@ -137,13 +142,18 @@ 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 nothing refused still records, even when its + recovered Handle. A Fire that drove no Fire a context refused still records, even when its context ends once the kernel has applied the event. - **An actor's output replays with the Fire that carried it.** When one delivery drove several parent Fires, such as an onDone entering a state whose actor then failed to start, the output was recorded with the last Fire, so replay gave it to the wrong transition. It's recorded with the settling Fire, which `state`'s new `ActorSystem.WithParentFireObserver` identifies. +- **A refused settle stays settled after `Recover`.** When the parent refused an actor's + onDone or onError, the live actor was settled, but `Recover` spawned it again from the + parent's state. It isn't re-spawned now, unless a later step stops or spawns it again. + A parent Fire that middleware denied before the kernel saw it is recorded as refused, + and replay meets the same refusal instead of failing `Recover`. - **A panic during a step fails the Handle.** A panic in host code under the step lock, such as an actor behavior a Fire's absorb started, left the Handle healthy but ahead of its journal, so the next step recorded on top of state the journal never held and diff --git a/durable/actor.go b/durable/actor.go index 114a4d44..976ccb0d 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -138,7 +138,9 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef // Fire it drove. The refused Fire rolls back, so live never applied it, but // journaling the delivery would replay it under a live context, where it applies. // Record nothing. - if err := h.stepCanceled(ctx, parentFireErrs(fires)...); err != nil { + // A delivery that drove no parent Fire changed nothing the journal holds, so an ended + // ctx can't have cost it anything. + if err := h.consumedCanceled(ctx, len(fires) > 0, parentFireErrs(fires)...); err != nil { return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) } @@ -202,16 +204,15 @@ func recordActorTransitions[S comparable](id string, traces []state.Trace, fires for i, tr := range traces { var mp actorMessagePayload mp.Event = append(json.RawMessage(nil), tr.EventPayload...) - mp.Refused = tr.Outcome != state.OutcomeSuccess + mp.Refused = fires[i].Result.Err != nil if fires[i].Settle { mp.HasData = true - switch out := fires[i].Outcome.(type) { - case error: - msg := out.Error() + switch { + case fires[i].Err != nil: + msg := fires[i].Err.Error() mp.Error = &msg - case nil: - default: - raw, err := json.Marshal(out) + case fires[i].Output != nil: + raw, err := json.Marshal(fires[i].Output) if err != nil { return nil, fmt.Errorf("marshaling actor output: %w", err) } @@ -238,36 +239,53 @@ func recordActorTransitions[S comparable](id string, traces []state.Trace, fires // kernel re-derives the same parent transition with the same data, running no actor // behavior. It reports an error only when the recorded entry cannot be decoded or // the re-fired transition fails (a corrupt or mis-ordered journal). -func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry state.JournalEntry) error { +func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry state.JournalEntry) (replayedActor[S], error) { var mp actorMessagePayload if err := json.Unmarshal(entry.Payload, &mp); err != nil { - return fmt.Errorf("durable: decoding recorded actor %q transition: %w", entry.CorrelationID, err) + return replayedActor[S]{}, fmt.Errorf("durable: decoding recorded actor %q transition: %w", entry.CorrelationID, err) + } + // A refused settle leaves the actor settled while the parent stays where it was, so + // Recover mustn't re-spawn it from the parent's state. + out := replayedActor[S]{} + if mp.Refused && mp.HasData { + out.settled = entry.CorrelationID + } + // A Fire refused before the kernel saw it (middleware that denied it) has no event + // to re-fire; replay is refused the same way. + if mp.Refused && len(mp.Event) == 0 { + return out, nil } event, err := codec.Decode(mp.Event) if err != nil { - return fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.CorrelationID, err) + return out, fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.CorrelationID, err) } - var res state.FireResult[S] if mp.HasData { data, derr := replayActorData(mp) if derr != nil { - return fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.CorrelationID, derr) + return out, fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.CorrelationID, derr) } - res = inst.Fire(ctx, event, state.WithEventData(data)) + out.res = inst.Fire(ctx, event, state.WithEventData(data)) } else { - res = inst.Fire(ctx, event) + out.res = inst.Fire(ctx, event) } // The kernel reports every refusal with an error, so the error alone says whether - // replay was refused. + // replay was refused, as it said for the live Fire. switch { - case res.Err != nil && mp.Refused: - return nil // the live run was refused the same way - case res.Err != nil: - return fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, res.Err) + case out.res.Err != nil && mp.Refused: + return out, nil // the live run was refused the same way + case out.res.Err != nil: + return out, fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, out.res.Err) case mp.Refused: - return fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) + return out, fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) } - return nil + return out, nil +} + +// replayedActor is one replayed actor entry: the parent Fire's result, and the id of +// the actor it settled when the live settle was refused. +type replayedActor[S comparable] struct { + res state.FireResult[S] + settled string } // replayActorData reconstructs the actor outcome a settling fire carried into the diff --git a/durable/runner.go b/durable/runner.go index ae481ee1..b1cb78fc 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -103,7 +103,8 @@ func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st // Handle, so it isn't serialized with this one. // // A step that applied to the kernel but may not have been recorded leaves the Handle out -// of step with the journal. So does a Tick, RunService or DeliverToActor whose context +// of step with the journal, and so does one that panicked in host code; the panic +// reaches the caller after the Handle fails. So does a Tick, RunService or DeliverToActor whose context // ended during the step, and any step, Fire included, that drove a Fire refused because // a context ended, the caller's or one middleware derived from it. That call and every later one return ErrHandleFailed, wrapping the cause, // which can be a context that ended during the Store write. Before recovering, call @@ -653,8 +654,11 @@ func (r *Runner[S, E, C]) Fire(ctx context.Context, id InstanceID, event E, opts // the step spawned can fail and route its onError through the instance; if a context // ending, ctx or one derived from it, refuses that onError, Fire fails the Handle with // ErrHandleFailed and records nothing, though the event applied. Recover restores the -// state from before the event, so fire it again on the recovered Handle. A Fire that -// drove nothing refused records even if ctx ends once the kernel has applied it. +// state from before the event, so fire it again on the recovered Handle, and don't act +// on the result Fire returned with that error. A Fire that drove no Fire a context +// refused records, even if ctx ends after the kernel applied it. A panic in host code +// during the step fails the Handle, then reaches the caller: recover it, then Drain +// and Recover as for ErrHandleFailed. // // A state.WithEventData payload reaches the transition's Assign as the Runner's // EventDataDecoder rebuilds it from the payload's JSON form, live and on replay alike, so @@ -719,7 +723,7 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi // 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 nothing refused + // 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. if err := refusedByContext(parentFireErrs(h.actorFires.take())...); err != nil { return res, nil, nil, h.fail(fmt.Errorf("durable: firing %q: %w", h.id, err)) @@ -821,7 +825,9 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro // 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. - if err := h.stepCanceled(ctx, append(resultErrs(results), parentFireErrs(h.actorFires.take())...)...); err != nil { + // A tick that fired no timer consumed nothing, so an ended ctx can't have cost it + // anything: it records as usual. + if err := h.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)) } @@ -1033,6 +1039,10 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // with every still-pending timer's deadline for the next checkpoint. armed := map[string]pendingTimer{} + // settled holds the actors the walk found settled under a parent that refused their + // settle, so the parent still declares them but the live run has none running. + settled := map[string]bool{} + for i := range tail { // A canceled context can stop a replayed settle or tick with no error, leaving // state short of the journal, so check it before each Record. @@ -1044,6 +1054,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S if err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } + trackSettled(settled, did) now, haveNow := tickInstant(rec.Entries) // Mirror the step into the armed table so it tracks the still-pending set, with // deadlines drawn from the step's recorded clock read, not the live wall clock: @@ -1085,7 +1096,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // the recorded run already settled, which replay reconstructed by re-firing the // parent rather than re-running behavior. if actors != nil { - actors.Absorb(ctx, inst.StartEffects()) + actors.Absorb(ctx, withoutSettled(inst.StartEffects(), settled)) // A parent Fire a re-spawned actor drove (a failed spawn's onError) belongs to no // recorded step, so it mustn't reach the next step's check. actorFires.take() @@ -1355,6 +1366,16 @@ func (h *Handle[S, E, C]) stepCanceled(ctx context.Context, errs ...error) error return refusedByContext(errs...) } +// consumedCanceled is stepCanceled for a step that consumed something (a timer it +// fired, a delivery that drove the parent), and refusedByContext for one that didn't, +// which has nothing an ended ctx could have cost it. +func (h *Handle[S, E, C]) consumedCanceled(ctx context.Context, consumed bool, errs ...error) error { + if consumed { + return h.stepCanceled(ctx, errs...) + } + return refusedByContext(errs...) +} + // refusedByContext returns the first of errs that is a context's error: a Fire refused // because the context it ran under ended. func refusedByContext(errs ...error) error { @@ -1386,10 +1407,51 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { } // replayed is what replayRecord fired, for a caller that tracks more than the -// instance: a tick barrier's timer fires, or a plain event's Fire. +// instance: a tick barrier's timer fires, a plain event's Fire, or the parent Fires an +// actor delivery re-drove, and the actors whose settle the parent refused. type replayed[S comparable] struct { - tick []state.FireResult[S] - fired *state.FireResult[S] + tick []state.FireResult[S] + fired *state.FireResult[S] + driven []state.FireResult[S] + settled []string +} + +// trackSettled keeps settled, the actors replay found settled under a parent that +// refused their onDone or onError, current after a replayed Record: an actor the +// parent later stops or spawns again is no longer one to keep from re-spawning. +func trackSettled[S comparable](settled map[string]bool, did replayed[S]) { + results := append(append([]state.FireResult[S](nil), did.tick...), did.driven...) + if did.fired != nil { + results = append(results, *did.fired) + } + for _, res := range results { + for _, eff := range res.Effects { + switch e := eff.(type) { + case state.SpawnActor: + delete(settled, e.ID) + case state.StopActor: + delete(settled, e.ID) + } + } + } + for _, id := range did.settled { + settled[id] = true + } +} + +// withoutSettled returns effects without the spawns of the actors in settled. +func withoutSettled(effects []state.Effect, settled map[string]bool) []state.Effect { + if len(settled) == 0 { + return effects + } + out := make([]state.Effect, 0, len(effects)) + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok && settled[sp.ID] { + continue + } + out = append(out, eff) + } + return out } // replayRecord re-applies one journaled Record to inst the way the live step applied @@ -1419,9 +1481,14 @@ func replayRecord[S comparable, E comparable, C any]( switch { case hasActorEntry(rec): for _, entry := range actorEntries(rec) { - if err := replayActor(ctx, inst, cfg.eventCodec, entry); err != nil { + ra, err := replayActor(ctx, inst, cfg.eventCodec, entry) + if err != nil { return out, fmt.Errorf("at step %d: %w", rec.Step, err) } + out.driven = append(out.driven, ra.res) + if ra.settled != "" { + out.settled = append(out.settled, ra.settled) + } } case hasServiceEntry(rec): for _, entry := range serviceEntries(rec) { diff --git a/durable/service.go b/durable/service.go index c9326df6..80467fe4 100644 --- a/durable/service.go +++ b/durable/service.go @@ -95,11 +95,12 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { // or one middleware derived from it) returns ErrHandleFailed and records nothing: a // recovered Handle has the service in flight again, and RunService runs it a second time. // A failed Append also returns ErrHandleFailed, but the write may have landed anyway: -// Recover finds out, and the service runs again only if the result isn't in the journal. If another goroutine failed the Handle while this step was -// recording, it returns the result, true and ErrHandleFailed saying the step was -// recorded. That error also matches the cause, so test ErrHandleFailed first: it alone -// means Recover is needed. A failed Checkpoint returns the plain error, and the result -// is recorded. +// Recover finds out, and the service runs again only if the result isn't in the +// journal. If another goroutine failed the Handle while this step was recording, it +// returns the result, true and ErrHandleFailed saying the step was recorded. Every +// ErrHandleFailed also matches its cause, so test for ErrHandleFailed first, then +// ErrFenced, as the Handle doc says. A failed Checkpoint returns the plain error, and +// the result is recorded. func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.FireResult[S], bool, error) { if err := h.acquire(ctx); err != nil { return state.FireResult[S]{}, false, err diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index e3571446..541191c6 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -417,3 +417,110 @@ func TestFire_PanicInHostCode_FailsTheHandle(t *testing.T) { } wantTail(t, store, id, before) } + +// TestDeliverToActor_RefusedSettle_StaysSettledAfterRecover proves an actor whose onDone +// the parent refused, a deterministic refusal the journal records, isn't running again +// on a recovered Handle: live it settled, and the parent stays where it was. +func TestDeliverToActor_RefusedSettle_StaysSettledAfterRecover(t *testing.T) { + ctx := context.Background() + m := supervisorUsing(nil, true) + store := durable.NewMemStore() + id := durable.InstanceID("refused-settle") + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for the child") + } + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + if found, _ := h.DeliverToActor(ctx, ref, "finish"); found { + t.Fatal("live: the settled actor is still running") + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if found, _ := recovered.DeliverToActor(ctx, ref, "finish"); found { + t.Fatalf("recovered: the actor whose settle was refused is running again (it ran %d times)", runs) + } + if got := recovered.Instance().Current(); got != "supervising" { + t.Fatalf("recovered state = %q, want supervising", got) + } +} + +// TestDeliverToActor_MiddlewareDeniedParentFire_Recovers proves a parent Fire that +// middleware denied before the kernel saw it is journaled as refused, and Recover +// meets the same refusal instead of failing on the event it has none of. +func TestDeliverToActor_MiddlewareDeniedParentFire_Recovers(t *testing.T) { + ctx := context.Background() + deny := func(next state.FireFunc[string, string, actorCtx]) state.FireFunc[string, string, actorCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + if event == "childDone" { + return state.FireResult[string]{Err: errors.New("denied by policy")} + } + return next(ctx, event) + } + } + m := supervisorUsing(deny, false) + store := durable.NewMemStore() + id := durable.InstanceID("denied") + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) + if !ok { + t.Fatal("no actor ref for the child") + } + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != h.Instance().Current() { + t.Fatalf("recovered state = %q, want the live %q", got, h.Instance().Current()) + } +} + +// TestTick_FiresNothing_ContextEnded_StaysHealthy proves a Tick that fired no timer +// keeps the Handle healthy even when its context ends during the call, since it +// consumed nothing an ended context could have cost it. +func TestTick_FiresNothing_ContextEnded_StaysHealthy(t *testing.T) { + ctx := context.Background() + m := expiringMachine(nil, doneNext) + store := durable.NewMemStore() + id := durable.InstanceID("idle-tick") + clk := &countingClock{Clock: state.NewFakeClock(epoch)} + h, err := durable.NewRunner(m, store, durable.WithRunnerClock[string, string, stepCtx](clk)). + Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + turn, cancel := context.WithCancel(ctx) + defer cancel() + clk.onRead = func(int) { cancel() } // the timer isn't due yet + results, err := h.Tick(turn) + clk.onRead = nil + if turn.Err() == nil { + t.Fatal("the test didn't end the context") + } + if err != nil || len(results) != 0 { + t.Fatalf("Tick = %d results, %v; want none and no error", len(results), err) + } + if _, err = h.Fire(ctx, "arm"); errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("the Handle failed: %v", err) + } +} diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 0a3c86b7..253f54de 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -15,10 +15,9 @@ counts as an additive (minor) versus breaking (major) change. Use the - **`ActorSystem.WithParentFireObserver`** calls a function with each parent Fire the system drives (a `ParentFire`: its result, refused ones included, and whether it - settled an actor, with the actor's outcome), so a host that records a delivery or spawn + settled an actor, with the actor's output or error), so a host that records a delivery or spawn can tell a parent transition refused because its context ended from one that applied, - and which Fire carried the actor's output. - + and which Fire carried the actor's output. It's additive, within v1.1.0. - **`FireEventData`** reports the payload a `WithEventData` option carries, so a host that records a Fire can persist it. It's additive, so the next release is v1.1.0. - **Callbacks get the step's context.** `GuardCtx`, `ActionCtx` and `AssignCtx` have a new diff --git a/state/actor_system.go b/state/actor_system.go index 1556484e..c9f07b50 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -735,7 +735,7 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any payload = output } res := s.parent.Fire(ctx, ev, WithEventData(payload)) - s.noteParentFire(ParentFire[S]{Result: res, Settle: true, Outcome: payload}) + s.noteParentFire(ParentFire[S]{Result: res, Settle: true, Output: output, Err: err}) s.Absorb(ctx, res.Effects) return res, true } @@ -802,11 +802,14 @@ type ParentFire[S comparable] struct { // Result is the parent Fire's result. A refused Fire carries its error. Result FireResult[S] // Settle reports that the Fire routed a settled actor's onDone or onError, which - // carried Outcome as its event data (WithEventData). A message the actor sent the - // parent, or a failed spawn's onError, carries none. + // carried the actor's outcome as its event data (WithEventData): Err for an onError, + // Output for an onDone. A message the actor sent the parent, or the onError of a + // spawn that couldn't start, carries none. Settle bool - // Outcome is the settled actor's output, or its error, when Settle is set. - Outcome any + // Output is the settled actor's output, when Settle is set and Err is nil. + Output any + // Err is the settled actor's failure, when Settle is set and it failed. + Err error } // WithParentFireObserver calls observe with each parent Fire the system drives (an @@ -815,10 +818,11 @@ type ParentFire[S comparable] struct { // its effects are absorbed. A host that records what a delivery or spawn drove uses // it: a parent Fire refused because the context it ran under ended reports that // context's error, so the host can tell a refusal it can't replay from one it can, -// and Settle and Outcome say which Fire carried an actor's outcome, and what it was. -// observe runs on the goroutine that drove the Fire, with no lock of the system's -// held, so it may read the system but must not drive it. Setting it returns the -// system for chaining. +// and Settle, Output and Err say which Fire carried an actor's outcome, and what it +// was. observe runs on the goroutine that drove the Fire, with no lock of the system's +// held, so it may read the system but must not drive it. Calls from Fires driven on +// different goroutines can overlap, so observe must be safe for concurrent use. +// Setting it returns the system for chaining. func (s *ActorSystem[S, E, C]) WithParentFireObserver(observe func(ParentFire[S])) *ActorSystem[S, E, C] { s.mu.Lock() s.parentFireObserver = observe From 5b7fb1641533d603dc7e5da6df6e10cb37d1b057 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 12:58:40 -0700 Subject: [PATCH 08/38] fix(durable): journal which actors are running, so Recover spawns only those Recover spawned every actor the recovered state declared, so an actor that had settled or been stopped while its parent stayed in that state ran again: a settle the parent refused, one that applied without leaving the state, or an explicit stop. Tracking refused settles through the replay walk missed the other cases and lost the mark at the next checkpoint. Each step now records the set of running actors when it changes, in the new Record.Actors, and a checkpoint envelope keeps the set. Recover takes the latest recorded set and spawns the declared actors it holds. A journal from before this records none, and Recover spawns every declared actor, as before. Signed-off-by: Ray Karnes --- docs/src/content/docs/durable/overview.md | 2 +- durable/CHANGELOG.md | 18 +++- durable/README.md | 2 +- durable/actor.go | 40 +++----- durable/checkpoint.go | 14 ++- durable/checkpoint_internal_test.go | 24 +++-- durable/doc.go | 7 +- durable/memstore.go | 3 + durable/runner.go | 118 +++++++++++----------- durable/step_rule_test.go | 118 ++++++++++++++++------ durable/store.go | 14 +++ durable/timetravel.go | 3 +- 12 files changed, 224 insertions(+), 139 deletions(-) diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index 9811e5b9..8a0c6af0 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -73,7 +73,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 actor doesn't re-run; a running `InvokeActor` actor restarts from its initial state on any `Recover`, and a `Spawn` actor doesn't return | +| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled or stopped actor doesn't re-run; a running `InvokeActor` actor restarts from its initial state on any `Recover`, and a `Spawn` actor doesn't return | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written: a diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 968b5f6d..7071a528 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -9,6 +9,10 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Added +- **`Record.Actors` and `RunningActors`** record the child-machine actors running after + a step, when it changed them, so `Recover` spawns only those. A Store persists the field + like the others. + - **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. @@ -149,11 +153,15 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. start, the output was recorded with the last Fire, so replay gave it to the wrong transition. It's recorded with the settling Fire, which `state`'s new `ActorSystem.WithParentFireObserver` identifies. -- **A refused settle stays settled after `Recover`.** When the parent refused an actor's - onDone or onError, the live actor was settled, but `Recover` spawned it again from the - parent's state. It isn't re-spawned now, unless a later step stops or spawns it again. - A parent Fire that middleware denied before the kernel saw it is recorded as refused, - and replay meets the same refusal instead of failing `Recover`. +- **`Recover` spawns only the actors the live run had running.** It spawned every actor + the recovered state declared, so an actor that had settled or been stopped while its + parent stayed in that state ran again: a settle the parent refused, one that applied + without leaving the state, or an explicit stop. Each step now records the set of + running actors when it changes, in the new `Record.Actors`, and a checkpoint keeps it, + so `Recover` spawns the declared actors that set holds. A journal from before this + records no set, and `Recover` spawns every declared actor, as before. +- **A parent Fire that middleware denied replays.** Denied before the kernel saw it, it + is recorded as refused, and replay meets the same refusal instead of failing `Recover`. - **A panic during a step fails the Handle.** A panic in host code under the step lock, such as an actor behavior a Fire's absorb started, left the Handle healthy but ahead of its journal, so the next step recorded on top of state the journal never held and diff --git a/durable/README.md b/durable/README.md index b33c5da4..643d40cc 100644 --- a/durable/README.md +++ b/durable/README.md @@ -83,7 +83,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 actor doesn't re-run; a running `InvokeActor` actor restarts from its initial state on any `Recover`, and a `Spawn` actor doesn't return | +| **Child-machine actors** | `WithActorPalette` + `Handle.DeliverToActor` | `JournalActorMessage`; recovery re-fires a recorded parent transition; a settled or stopped actor doesn't re-run; a running `InvokeActor` actor restarts from its initial state on any `Recover`, and a `Spawn` actor doesn't return | | **Domain effects** | `WithEffectHandler` | dispatch set, applied exactly once via deterministic `EffectID` dedup | Use `WithCheckpointEvery(n)` to tune how often a full snapshot is written (a diff --git a/durable/actor.go b/durable/actor.go index 976ccb0d..6fc8c121 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -239,53 +239,41 @@ func recordActorTransitions[S comparable](id string, traces []state.Trace, fires // kernel re-derives the same parent transition with the same data, running no actor // behavior. It reports an error only when the recorded entry cannot be decoded or // the re-fired transition fails (a corrupt or mis-ordered journal). -func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry state.JournalEntry) (replayedActor[S], error) { +func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry state.JournalEntry) error { var mp actorMessagePayload if err := json.Unmarshal(entry.Payload, &mp); err != nil { - return replayedActor[S]{}, fmt.Errorf("durable: decoding recorded actor %q transition: %w", entry.CorrelationID, err) - } - // A refused settle leaves the actor settled while the parent stays where it was, so - // Recover mustn't re-spawn it from the parent's state. - out := replayedActor[S]{} - if mp.Refused && mp.HasData { - out.settled = entry.CorrelationID + return fmt.Errorf("durable: decoding recorded actor %q transition: %w", entry.CorrelationID, err) } // A Fire refused before the kernel saw it (middleware that denied it) has no event // to re-fire; replay is refused the same way. if mp.Refused && len(mp.Event) == 0 { - return out, nil + return nil } event, err := codec.Decode(mp.Event) if err != nil { - return out, fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.CorrelationID, err) + return fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.CorrelationID, err) } + var res state.FireResult[S] if mp.HasData { data, derr := replayActorData(mp) if derr != nil { - return out, fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.CorrelationID, derr) + return fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.CorrelationID, derr) } - out.res = inst.Fire(ctx, event, state.WithEventData(data)) + res = inst.Fire(ctx, event, state.WithEventData(data)) } else { - out.res = inst.Fire(ctx, event) + res = inst.Fire(ctx, event) } // The kernel reports every refusal with an error, so the error alone says whether // replay was refused, as it said for the live Fire. switch { - case out.res.Err != nil && mp.Refused: - return out, nil // the live run was refused the same way - case out.res.Err != nil: - return out, fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, out.res.Err) + case res.Err != nil && mp.Refused: + return nil // the live run was refused the same way + case res.Err != nil: + return fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, res.Err) case mp.Refused: - return out, fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) + return fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) } - return out, nil -} - -// replayedActor is one replayed actor entry: the parent Fire's result, and the id of -// the actor it settled when the live settle was refused. -type replayedActor[S comparable] struct { - res state.FireResult[S] - settled string + return nil } // replayActorData reconstructs the actor outcome a settling fire carried into the diff --git a/durable/checkpoint.go b/durable/checkpoint.go index c65eb830..98b13ff2 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -84,14 +84,18 @@ type checkpointEnvelope struct { // Zero means none was recorded: a Start baseline, or a checkpoint from before this // field. NextStep int `json:"nextStep,omitempty"` + // Actors is the set of child-machine actors running at the checkpoint, so a + // recovery whose compacted tail no longer records it spawns only those. Nil means + // none was recorded: no actor palette, a Start baseline, or an older checkpoint. + Actors *RunningActors `json:"actors,omitempty"` } // marshalCheckpoint wraps the marshaled kernel snapshot and the armed pending // timers into a checkpoint envelope's bytes. Timers are emitted in scheduleID // order so the persisted form is deterministic regardless of the map iteration // order they were collected in. nextStep is the ordinal that follows the checkpoint. -func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int) ([]byte, error) { - env := checkpointEnvelope{Snapshot: snap, NextStep: nextStep} +func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int, actors *RunningActors) ([]byte, error) { + env := checkpointEnvelope{Snapshot: snap, NextStep: nextStep, Actors: actors} if len(timers) > 0 { ids := make([]string, 0, len(timers)) for id := range timers { @@ -125,14 +129,14 @@ func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int // are returned as the snapshot with no timers and a zero ordinal, so an older // checkpoint still restores. A checkpoint envelope is distinguished by carrying a // non-empty "snapshot" member. -func unmarshalCheckpoint(b []byte) ([]byte, []pendingTimerWire, int, error) { +func unmarshalCheckpoint(b []byte) (checkpointEnvelope, error) { var env checkpointEnvelope if err := json.Unmarshal(b, &env); err != nil || len(env.Snapshot) == 0 { // Not an envelope (or an envelope without the wrapped snapshot member): treat // the bytes as a bare kernel snapshot, the pre-timer-survival checkpoint form. - return b, nil, 0, nil + return checkpointEnvelope{Snapshot: b}, nil } - return env.Snapshot, env.Timers, env.NextStep, nil + return env, nil } // decodeTimerEvent decodes a persisted timer event wire back into the machine's diff --git a/durable/checkpoint_internal_test.go b/durable/checkpoint_internal_test.go index 5ae66b4f..d5ac857e 100644 --- a/durable/checkpoint_internal_test.go +++ b/durable/checkpoint_internal_test.go @@ -17,11 +17,11 @@ func TestMarshalCheckpoint_RoundTrip(t *testing.T) { timers := map[string]pendingTimer{ "m:a:after:0": {id: "m:a:after:0", due: due, event: "elapsed"}, } - b, err := marshalCheckpoint(snap, timers, 0) + b, err := marshalCheckpoint(snap, timers, 0, nil) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } - gotSnap, gotWires, _, err := unmarshalCheckpoint(b) + gotSnap, gotWires, _, err := unmarshalCheckpointParts(b) if err != nil { t.Fatalf("unmarshalCheckpoint: %v", err) } @@ -45,7 +45,7 @@ func TestMarshalCheckpoint_RoundTrip(t *testing.T) { // armed, so an event-driven checkpoint's envelope stays minimal. func TestMarshalCheckpoint_NoTimers(t *testing.T) { snap := []byte(`{"machine":"m"}`) - b, err := marshalCheckpoint(snap, nil, 0) + b, err := marshalCheckpoint(snap, nil, 0, nil) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } @@ -64,7 +64,7 @@ func TestMarshalCheckpoint_NoTimers(t *testing.T) { // checkpoint still restores. func TestUnmarshalCheckpoint_BareSnapshotFallback(t *testing.T) { bare := []byte(`{"machine":"m","current":"a","configuration":["a"]}`) - snap, wires, _, err := unmarshalCheckpoint(bare) + snap, wires, _, err := unmarshalCheckpointParts(bare) if err != nil { t.Fatalf("unmarshalCheckpoint: %v", err) } @@ -81,7 +81,7 @@ func TestUnmarshalCheckpoint_BareSnapshotFallback(t *testing.T) { // any real decode failure when it unmarshals the kernel snapshot). func TestUnmarshalCheckpoint_Garbage(t *testing.T) { garbage := []byte(`not json`) - snap, wires, _, err := unmarshalCheckpoint(garbage) + snap, wires, _, err := unmarshalCheckpointParts(garbage) if err != nil { t.Fatalf("unmarshalCheckpoint should tolerate garbage: %v", err) } @@ -155,7 +155,7 @@ func TestMarshalCheckpoint_BadEventErrors(t *testing.T) { timers := map[string]pendingTimer{ "bad": {id: "bad", due: time.Unix(0, 1), event: make(chan int)}, } - if _, err := marshalCheckpoint([]byte(`{}`), timers, 0); err == nil { + if _, err := marshalCheckpoint([]byte(`{}`), timers, 0, nil); err == nil { t.Fatal("want encode error for unmarshalable timer event, got nil") } } @@ -178,14 +178,20 @@ func TestTickInstant(t *testing.T) { // TestCheckpoint_NextStepRoundTrips proves the envelope carries the ordinal after // the checkpoint, and that a checkpoint without one reports zero, the old form. func TestCheckpoint_NextStepRoundTrips(t *testing.T) { - b, err := marshalCheckpoint([]byte(`{"v":1}`), nil, 9) + b, err := marshalCheckpoint([]byte(`{"v":1}`), nil, 9, nil) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } - if _, _, next, err := unmarshalCheckpoint(b); err != nil || next != 9 { + if _, _, next, err := unmarshalCheckpointParts(b); err != nil || next != 9 { t.Fatalf("unmarshalCheckpoint = (%d, %v), want (9, nil)", next, err) } - if _, _, next, err := unmarshalCheckpoint([]byte(`{"snapshot":{"v":1}}`)); err != nil || next != 0 { + if _, _, next, err := unmarshalCheckpointParts([]byte(`{"snapshot":{"v":1}}`)); err != nil || next != 0 { t.Fatalf("old envelope = (%d, %v), want (0, nil)", next, err) } } + +// unmarshalCheckpointParts is unmarshalCheckpoint split into the parts these tests check. +func unmarshalCheckpointParts(b []byte) ([]byte, []pendingTimerWire, int, error) { + env, err := unmarshalCheckpoint(b) + return env.Snapshot, env.Timers, env.NextStep, err +} diff --git a/durable/doc.go b/durable/doc.go index 02c49292..8386c0ba 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -109,9 +109,10 @@ // Child-machine actors (WithActorPalette): an actor's behavior runs on the live path; // each parent transition the delivery drives is journaled as a JournalActorMessage. On // recovery the recorded transition is re-fired directly through the parent with the -// recorded done-data, so a settled actor never re-runs. An InvokeActor actor still -// running at recovery restarts from its initial state, because its own state isn't -// journaled, and a Spawn actor doesn't return. +// recorded done-data, so a settled actor never re-runs. Each step records the set of +// actors running when it changes, and Recover spawns only the declared actors that set +// holds: an InvokeActor actor still running at recovery restarts from its initial +// state, because its own state isn't journaled, and a Spawn actor doesn't return. // // # Idempotent effect dispatch // diff --git a/durable/memstore.go b/durable/memstore.go index fd2105ac..51441aea 100644 --- a/durable/memstore.go +++ b/durable/memstore.go @@ -406,5 +406,8 @@ func cloneRecord(rec Record) Record { if rec.Snapshot != nil { out.Snapshot = append([]byte(nil), rec.Snapshot...) } + if rec.Actors != nil { + out.Actors = &RunningActors{IDs: append([]string{}, rec.Actors.IDs...)} + } return out } diff --git a/durable/runner.go b/durable/runner.go index b1cb78fc..f430195d 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "reflect" + "slices" "sync" "time" @@ -134,6 +135,8 @@ type Handle[S comparable, E comparable, C any] struct { svcBuf *[]state.JournalEntry // recording service-result accumulator, flushed per step actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired + actorsAt []string // the running actors the journal last recorded + actorsSet bool // whether actorsAt holds a recorded set actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step @@ -510,7 +513,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt } // Wrap the baseline snapshot in a checkpoint envelope (no timers armed yet) so // every checkpoint a recover loads carries the same durable envelope shape. - baseEnv, err := marshalCheckpoint(snap, nil, 0) + baseEnv, err := marshalCheckpoint(snap, nil, 0, nil) if err != nil { return nil, fmt.Errorf("durable: marshaling start checkpoint envelope for %q: %w", id, err) } @@ -952,18 +955,51 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // Wrap the kernel snapshot with the absolute deadlines of the timers armed at // this checkpoint, so a recovery whose compacted tail no longer carries their // arming ScheduleAfter can re-arm them at their recorded instants. - env, err := marshalCheckpoint(snap, h.timers, rec.followingStep()) + env, err := marshalCheckpoint(snap, h.timers, rec.followingStep(), h.runningActors()) if err != nil { return fmt.Errorf("durable: marshaling checkpoint envelope at step %d for %q: %w", step, h.id, err) } rec.Snapshot = env } + now := h.runningActors() + if now != nil && (!h.actorsSet || !slices.Equal(now.IDs, h.actorsAt)) { + rec.Actors = now + } if _, err := h.runner.store.Append(ctx, h.id, *rec, WithFence(h.runner.cfg.fence)); err != nil { return fmt.Errorf("durable: recording step %d for %q: %w", step, h.id, err) } + if now != nil { + h.actorsAt, h.actorsSet = now.IDs, true + } return nil } +// runningActors returns the set of actors running now, or nil with no actor palette. +func (h *Handle[S, E, C]) runningActors() *RunningActors { + if h.actors == nil { + return nil + } + return &RunningActors{IDs: h.actors.IDs()} +} + +// spawnsRunning returns effects without the actor spawns running doesn't hold, so +// Recover spawns only the declared actors the live run had running. With no recorded +// set it returns effects unchanged, spawning every declared actor, as Recover did +// before the set was recorded. +func spawnsRunning(effects []state.Effect, running *RunningActors) []state.Effect { + if running == nil { + return effects + } + out := make([]state.Effect, 0, len(effects)) + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok && !slices.Contains(running.IDs, sp.ID) { + continue + } + out = append(out, eff) + } + return out +} + // Recover reconstructs a durable instance purely from the Store: it loads the // latest checkpoint Snapshot and the journal/effect tail after it, Restores the // snapshot (firing nothing, no IO), and replays the tail's recorded driving @@ -991,7 +1027,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // Unwrap the durable checkpoint envelope: the kernel snapshot bytes, the absolute // deadlines of the timers armed at the checkpoint, and the next step ordinal. A bare // (pre-envelope) checkpoint yields the snapshot with no persisted timers. - kernelSnap, persistedTimers, checkpointNext, err := unmarshalCheckpoint(snapBytes) + env, err := unmarshalCheckpoint(snapBytes) + kernelSnap, persistedTimers, checkpointNext := env.Snapshot, env.Timers, env.NextStep if err != nil { return nil, fmt.Errorf("durable: unmarshaling checkpoint envelope for %q: %w", id, err) } @@ -1039,9 +1076,10 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // with every still-pending timer's deadline for the next checkpoint. armed := map[string]pendingTimer{} - // settled holds the actors the walk found settled under a parent that refused their - // settle, so the parent still declares them but the live run has none running. - settled := map[string]bool{} + // running is the latest recorded set of the actors the live run had running: the + // checkpoint's, then each tail Record's that records one. Nil means none was + // recorded, so Recover spawns every actor the configuration declares. + running := env.Actors for i := range tail { // A canceled context can stop a replayed settle or tick with no error, leaving @@ -1054,7 +1092,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S if err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } - trackSettled(settled, did) + if rec.Actors != nil { + running = rec.Actors + } now, haveNow := tickInstant(rec.Entries) // Mirror the step into the armed table so it tracks the still-pending set, with // deadlines drawn from the step's recorded clock read, not the live wall clock: @@ -1096,11 +1136,17 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // the recorded run already settled, which replay reconstructed by re-firing the // parent rather than re-running behavior. if actors != nil { - actors.Absorb(ctx, withoutSettled(inst.StartEffects(), settled)) + actors.Absorb(ctx, spawnsRunning(inst.StartEffects(), running)) // A parent Fire a re-spawned actor drove (a failed spawn's onError) belongs to no // recorded step, so it mustn't reach the next step's check. actorFires.take() } + // The actors now running are the ones the journal records, so the next step records + // a set only when it changes them. + var recoveredActors []string + if actors != nil { + recoveredActors = actors.IDs() + } // Re-arm any timer that was pending at the checkpoint but whose arming // ScheduleAfter was compacted out of the tail, so it survives compaction: the @@ -1167,6 +1213,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S actors: actors, actorBuf: &actorBuf, actorFires: actorFires, + actorsAt: recoveredActors, + actorsSet: actors != nil, lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, }, nil @@ -1407,51 +1455,10 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { } // replayed is what replayRecord fired, for a caller that tracks more than the -// instance: a tick barrier's timer fires, a plain event's Fire, or the parent Fires an -// actor delivery re-drove, and the actors whose settle the parent refused. +// instance: a tick barrier's timer fires, or a plain event's Fire. type replayed[S comparable] struct { - tick []state.FireResult[S] - fired *state.FireResult[S] - driven []state.FireResult[S] - settled []string -} - -// trackSettled keeps settled, the actors replay found settled under a parent that -// refused their onDone or onError, current after a replayed Record: an actor the -// parent later stops or spawns again is no longer one to keep from re-spawning. -func trackSettled[S comparable](settled map[string]bool, did replayed[S]) { - results := append(append([]state.FireResult[S](nil), did.tick...), did.driven...) - if did.fired != nil { - results = append(results, *did.fired) - } - for _, res := range results { - for _, eff := range res.Effects { - switch e := eff.(type) { - case state.SpawnActor: - delete(settled, e.ID) - case state.StopActor: - delete(settled, e.ID) - } - } - } - for _, id := range did.settled { - settled[id] = true - } -} - -// withoutSettled returns effects without the spawns of the actors in settled. -func withoutSettled(effects []state.Effect, settled map[string]bool) []state.Effect { - if len(settled) == 0 { - return effects - } - out := make([]state.Effect, 0, len(effects)) - for _, eff := range effects { - if sp, ok := eff.(state.SpawnActor); ok && settled[sp.ID] { - continue - } - out = append(out, eff) - } - return out + tick []state.FireResult[S] + fired *state.FireResult[S] } // replayRecord re-applies one journaled Record to inst the way the live step applied @@ -1481,14 +1488,9 @@ func replayRecord[S comparable, E comparable, C any]( switch { case hasActorEntry(rec): for _, entry := range actorEntries(rec) { - ra, err := replayActor(ctx, inst, cfg.eventCodec, entry) - if err != nil { + if err := replayActor(ctx, inst, cfg.eventCodec, entry); err != nil { return out, fmt.Errorf("at step %d: %w", rec.Step, err) } - out.driven = append(out.driven, ra.res) - if ra.settled != "" { - out.settled = append(out.settled, ra.settled) - } } case hasServiceEntry(rec): for _, entry := range serviceEntries(rec) { diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index 541191c6..eb59f49e 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -418,40 +418,98 @@ func TestFire_PanicInHostCode_FailsTheHandle(t *testing.T) { wantTail(t, store, id, before) } -// TestDeliverToActor_RefusedSettle_StaysSettledAfterRecover proves an actor whose onDone -// the parent refused, a deterministic refusal the journal records, isn't running again -// on a recovered Handle: live it settled, and the parent stays where it was. -func TestDeliverToActor_RefusedSettle_StaysSettledAfterRecover(t *testing.T) { - ctx := context.Background() - m := supervisorUsing(nil, true) - store := durable.NewMemStore() - id := durable.InstanceID("refused-settle") +// watcherMachine invokes the counter child on supervising; childDone and the other +// events stay in supervising, so the parent keeps declaring the child after it settles. +// how decides what childDone does: "refuse" (a guard fails), "stay" (applies without +// leaving), or "stop" (applies and stops the child explicitly). svcDone, from a service +// the state also invokes, re-enters supervising. +func watcherMachine(how string, withService bool) (*state.Machine[string, string, actorCtx], []durable.Option[string, string, actorCtx]) { var runs int64 + svc := func(context.Context, state.ServiceCtx[actorCtx]) (any, error) { return "ok", nil } + b := state.ForgeFor[actorCtx]("watcher"). + Guard("never", func(state.GuardCtx[actorCtx]) bool { return false }). + Service("svc", svc). + Actor("spawnChild"). + State("supervising").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")) + if withService { + b = b.Invoke("svc", state.WithInvokeOnDone("svcDone")) + } + b = b.State("complete").Final().Initial("supervising") + switch how { + case "refuse": + b = b.Transition("supervising").On("childDone").GoTo("complete").When("never") + case "stay": + b = b.Transition("supervising").On("childDone").GoTo("supervising") + case "stop": + b = b.Transition("supervising").On("childDone").GoTo("supervising").StopActor(state.ActorID("watcher", "supervising", 0)) + } + m := b.Transition("supervising").On("svcDone").GoTo("supervising").Reenter().Quench() opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} - h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) - if err != nil { - t.Fatalf("Start: %v", err) + if withService { + opts = append(opts, durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("svc", svc))) } - ref, ok := h.ActorRef(state.ActorID("supervisor", "supervising", 0)) - if !ok { - t.Fatal("no actor ref for the child") - } - if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { - t.Fatalf("DeliverToActor: %v", err) - } - if found, _ := h.DeliverToActor(ctx, ref, "finish"); found { - t.Fatal("live: the settled actor is still running") - } - recovered, err := durable.Recover(ctx, m, store, id, opts...) - if err != nil { - t.Fatalf("Recover: %v", err) - } - if found, _ := recovered.DeliverToActor(ctx, ref, "finish"); found { - t.Fatalf("recovered: the actor whose settle was refused is running again (it ran %d times)", runs) - } - if got := recovered.Instance().Current(); got != "supervising" { - t.Fatalf("recovered state = %q, want supervising", got) + return m, opts +} + +// TestRecover_SpawnsTheActorsLiveHadRunning proves Recover spawns only the declared +// actors the live run still had running, as the journal records them: an actor that +// settled while its parent stayed in the declaring state, whether its onDone was +// refused, applied without leaving, or stopped it, isn't spawned again, with or +// without a checkpoint compacting the step; one a later step spawned again is. +func TestRecover_SpawnsTheActorsLiveHadRunning(t *testing.T) { + ctx := context.Background() + childID := state.ActorID("watcher", "supervising", 0) + for _, how := range []string{"refuse", "stay", "stop"} { + for _, every := range []int{0, 1, 2} { + t.Run(fmt.Sprintf("%s/checkpoint every %d", how, every), func(t *testing.T) { + m, opts := watcherMachine(how, false) + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, actorCtx](every)) + } + store := durable.NewMemStore() + id := durable.InstanceID("watch") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, ok := h.ActorRef(childID) + if !ok { + t.Fatal("no actor ref for the child") + } + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if found, _ := recovered.DeliverToActor(ctx, ref, "finish"); found { + t.Fatal("recovered: the actor that settled live is running again") + } + }) + } } + t.Run("a service re-entering spawns it again", func(t *testing.T) { + m, opts := watcherMachine("refuse", true) + store := durable.NewMemStore() + id := durable.InstanceID("watch-svc") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("supervising")) + if err != nil { + t.Fatalf("Start: %v", err) + } + ref, _ := h.ActorRef(childID) + if _, err = h.DeliverToActor(ctx, ref, "finish"); err != nil { + t.Fatalf("DeliverToActor: %v", err) + } + mustRunService(t, h, state.InvokeID("watcher", "supervising", 1)) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if found, _ := recovered.DeliverToActor(ctx, ref, "finish"); !found { + t.Fatal("recovered: the actor the service's re-entry spawned again isn't running") + } + }) } // TestDeliverToActor_MiddlewareDeniedParentFire_Recovers proves a parent Fire that diff --git a/durable/store.go b/durable/store.go index afaf4fd7..74f55aad 100644 --- a/durable/store.go +++ b/durable/store.go @@ -83,6 +83,20 @@ type Record struct { // (zero for a tick that found nothing due). It lets replay advance its step // accounting across a re-derived tick without a recorded Event per timer. TickSteps int + + // Actors, when set, holds the child-machine actors running once this step ended, + // recorded when the step changed them. Recover spawns the instance's declared + // actors that the latest recorded set holds, so an actor that settled or was + // stopped live isn't spawned again. It is nil when the step left them unchanged, for + // a machine with no actor palette, and on a Record from before this field. + Actors *RunningActors `json:",omitempty"` +} + +// RunningActors is the set of child-machine actors running at a point in a durable +// instance's journal. +type RunningActors struct { + // IDs are the running actors' ids, sorted. + IDs []string `json:"ids"` } // followingStep returns the step ordinal after r. A tick barrier consumes one diff --git a/durable/timetravel.go b/durable/timetravel.go index 662ee38f..5525f0b5 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -203,7 +203,8 @@ func restoreBaseline[S comparable, E comparable, C any]( baseline []byte, repClock state.Clock, ) (*state.Instance[S, E, C], error) { - kernelSnap, _, _, err := unmarshalCheckpoint(baseline) + env, err := unmarshalCheckpoint(baseline) + kernelSnap := env.Snapshot if err != nil { return nil, fmt.Errorf("unmarshaling baseline envelope: %w", err) } From b4f95bd53fbeccae7ad49f8eaf43c756144c6dab Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 13:23:40 -0700 Subject: [PATCH 09/38] fix(durable): record the actors that ended, so a failed spawn is retried Recording the running actors made Recover skip an actor whose spawn had failed, since it never ran: base retried it on every Recover, and a fixed palette or a transient error then recovered the instance. Each step now records the declared actors that ran and ended, settled (the actor system keeps a settled actor) or stopped (the Handle saw it running), in Record.EndedActors. Recover spawns the declared actors not in it, so a failed spawn is tried again, as before. Recover seeds what it saw from the journal's set, so a step after it doesn't forget the ended actors. The Store contract says an empty EndedActors is not nil, and the downgrade note covers the set. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 20 ++++--- durable/checkpoint.go | 13 +++-- durable/doc.go | 8 +-- durable/memstore.go | 4 +- durable/runner.go | 113 ++++++++++++++++++++++++++++---------- durable/step_rule_test.go | 49 ++++++++++++++++- durable/store.go | 25 +++++---- 7 files changed, 170 insertions(+), 62 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 7071a528..0be54c02 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -9,9 +9,9 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Added -- **`Record.Actors` and `RunningActors`** record the child-machine actors running after - a step, when it changed them, so `Recover` spawns only those. A Store persists the field - like the others. +- **`Record.EndedActors` and `ActorSet`** record the declared child-machine actors that + ran and have ended, settled or stopped, so `Recover` doesn't spawn them again. A Store + must keep an empty set distinct from nil. - **Fencing.** `WithFence` on `Store.Append` and `WithCheckpointFence` on `Store.Checkpoint` carry a caller-issued token, and a Store refuses a token lower @@ -54,8 +54,9 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **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. Don't downgrade a Store this version - has written to. + entry with no event, replays as the zero event. An older `durable` also ignores the + recorded ended actors and spawns them again. Don't downgrade a Store this version has + written to. - **A journal an older version wrote replays as it did.** Its actor entries carry no refusal, so `Recover` still fails on one whose parent Fire was refused, and an output recorded with a delivery's last Fire still replays into that transition. Only steps @@ -153,12 +154,13 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. start, the output was recorded with the last Fire, so replay gave it to the wrong transition. It's recorded with the settling Fire, which `state`'s new `ActorSystem.WithParentFireObserver` identifies. -- **`Recover` spawns only the actors the live run had running.** It spawned every actor +- **`Recover` doesn't spawn an actor the live run had ended.** It spawned every actor the recovered state declared, so an actor that had settled or been stopped while its parent stayed in that state ran again: a settle the parent refused, one that applied - without leaving the state, or an explicit stop. Each step now records the set of - running actors when it changes, in the new `Record.Actors`, and a checkpoint keeps it, - so `Recover` spawns the declared actors that set holds. A journal from before this + without leaving the state, or an explicit stop. Each step now records the declared + actors that ran and ended, in the new `Record.EndedActors`, and a checkpoint keeps the + set, so `Recover` spawns the declared actors that aren't in it. An actor whose spawn + failed never ran, so `Recover` tries it again, as before. A journal from before this records no set, and `Recover` spawns every declared actor, as before. - **A parent Fire that middleware denied replays.** Denied before the kernel saw it, it is recorded as refused, and replay meets the same refusal instead of failing `Recover`. diff --git a/durable/checkpoint.go b/durable/checkpoint.go index 98b13ff2..254401c5 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -84,18 +84,19 @@ type checkpointEnvelope struct { // Zero means none was recorded: a Start baseline, or a checkpoint from before this // field. NextStep int `json:"nextStep,omitempty"` - // Actors is the set of child-machine actors running at the checkpoint, so a - // recovery whose compacted tail no longer records it spawns only those. Nil means - // none was recorded: no actor palette, a Start baseline, or an older checkpoint. - Actors *RunningActors `json:"actors,omitempty"` + // EndedActors is the set of declared actors that had ended at the checkpoint (see + // Record.EndedActors), so a recovery whose compacted tail no longer records it still + // doesn't spawn them. Nil means none was recorded: no actor palette, a Start + // baseline, or an older checkpoint. + EndedActors *ActorSet `json:"endedActors,omitempty"` } // marshalCheckpoint wraps the marshaled kernel snapshot and the armed pending // timers into a checkpoint envelope's bytes. Timers are emitted in scheduleID // order so the persisted form is deterministic regardless of the map iteration // order they were collected in. nextStep is the ordinal that follows the checkpoint. -func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int, actors *RunningActors) ([]byte, error) { - env := checkpointEnvelope{Snapshot: snap, NextStep: nextStep, Actors: actors} +func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int, ended *ActorSet) ([]byte, error) { + env := checkpointEnvelope{Snapshot: snap, NextStep: nextStep, EndedActors: ended} if len(timers) > 0 { ids := make([]string, 0, len(timers)) for id := range timers { diff --git a/durable/doc.go b/durable/doc.go index 8386c0ba..559ca3b4 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -109,10 +109,10 @@ // Child-machine actors (WithActorPalette): an actor's behavior runs on the live path; // each parent transition the delivery drives is journaled as a JournalActorMessage. On // recovery the recorded transition is re-fired directly through the parent with the -// recorded done-data, so a settled actor never re-runs. Each step records the set of -// actors running when it changes, and Recover spawns only the declared actors that set -// holds: an InvokeActor actor still running at recovery restarts from its initial -// state, because its own state isn't journaled, and a Spawn actor doesn't return. +// recorded done-data, so a settled actor never re-runs. Each step records the declared +// actors that ran and ended, settled or stopped, and Recover doesn't spawn those. An +// InvokeActor actor still running at recovery restarts from its initial state, because +// its own state isn't journaled, and a Spawn actor doesn't return. // // # Idempotent effect dispatch // diff --git a/durable/memstore.go b/durable/memstore.go index 51441aea..327989e8 100644 --- a/durable/memstore.go +++ b/durable/memstore.go @@ -406,8 +406,8 @@ func cloneRecord(rec Record) Record { if rec.Snapshot != nil { out.Snapshot = append([]byte(nil), rec.Snapshot...) } - if rec.Actors != nil { - out.Actors = &RunningActors{IDs: append([]string{}, rec.Actors.IDs...)} + if rec.EndedActors != nil { + out.EndedActors = &ActorSet{IDs: append([]string{}, rec.EndedActors.IDs...)} } return out } diff --git a/durable/runner.go b/durable/runner.go index f430195d..175e5a19 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -135,8 +135,9 @@ type Handle[S comparable, E comparable, C any] struct { svcBuf *[]state.JournalEntry // recording service-result accumulator, flushed per step actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired - actorsAt []string // the running actors the journal last recorded - actorsSet bool // whether actorsAt holds a recorded set + endedAt []string // the ended actors the journal last recorded + endedSet bool // whether endedAt holds a recorded set + seen map[string]bool // declared actors seen running, so a stopped one counts as ended actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step @@ -545,6 +546,13 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // recorded step, so it mustn't reach the first step's check. actorFires.take() } + // The actors that started are seen running, so one later stopped counts as ended. + seen := map[string]bool{} + if actors != nil { + for _, id := range actors.IDs() { + seen[id] = true + } + } return &Handle[S, E, C]{ runner: r, @@ -559,6 +567,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt actors: actors, actorBuf: &actorBuf, actorFires: actorFires, + seen: seen, lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, }, nil @@ -955,44 +964,80 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // Wrap the kernel snapshot with the absolute deadlines of the timers armed at // this checkpoint, so a recovery whose compacted tail no longer carries their // arming ScheduleAfter can re-arm them at their recorded instants. - env, err := marshalCheckpoint(snap, h.timers, rec.followingStep(), h.runningActors()) + env, err := marshalCheckpoint(snap, h.timers, rec.followingStep(), h.endedActors()) if err != nil { return fmt.Errorf("durable: marshaling checkpoint envelope at step %d for %q: %w", step, h.id, err) } rec.Snapshot = env } - now := h.runningActors() - if now != nil && (!h.actorsSet || !slices.Equal(now.IDs, h.actorsAt)) { - rec.Actors = now + now := h.endedActors() + if now != nil && (!h.endedSet || !slices.Equal(now.IDs, h.endedAt)) { + rec.EndedActors = now } if _, err := h.runner.store.Append(ctx, h.id, *rec, WithFence(h.runner.cfg.fence)); err != nil { return fmt.Errorf("durable: recording step %d for %q: %w", step, h.id, err) } if now != nil { - h.actorsAt, h.actorsSet = now.IDs, true + h.endedAt, h.endedSet = now.IDs, true } return nil } -// runningActors returns the set of actors running now, or nil with no actor palette. -func (h *Handle[S, E, C]) runningActors() *RunningActors { +// endedActors returns the actors the instance's state declares that ran and have +// ended: not running now, and either settled (the actor system keeps a settled actor) +// or seen running at an earlier step (a stopped actor is gone from the system). An +// actor whose spawn failed was never either, so it isn't one, and Recover spawns it +// again. It forgets what it saw of actors the state no longer declares. It is nil with +// no actor palette. +func (h *Handle[S, E, C]) endedActors() *ActorSet { if h.actors == nil { return nil } - return &RunningActors{IDs: h.actors.IDs()} + running := h.actors.IDs() + declared := declaredActors(h.inst.StartEffects()) + for _, id := range running { + h.seen[id] = true + } + for id := range h.seen { + if !slices.Contains(declared, id) { + delete(h.seen, id) + } + } + ended := []string{} + for _, id := range declared { + if slices.Contains(running, id) { + continue + } + if _, settled := h.actors.Ref(id); settled || h.seen[id] { + ended = append(ended, id) + } + } + slices.Sort(ended) + return &ActorSet{IDs: ended} } -// spawnsRunning returns effects without the actor spawns running doesn't hold, so -// Recover spawns only the declared actors the live run had running. With no recorded -// set it returns effects unchanged, spawning every declared actor, as Recover did -// before the set was recorded. -func spawnsRunning(effects []state.Effect, running *RunningActors) []state.Effect { - if running == nil { +// declaredActors returns the ids of the actors effects spawn. +func declaredActors(effects []state.Effect) []string { + var ids []string + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok { + ids = append(ids, sp.ID) + } + } + return ids +} + +// spawnsExcept returns effects without the spawns of the actors ended holds, so +// Recover doesn't spawn an actor the live run had ended. With no recorded set it +// returns effects unchanged, spawning every declared actor, as Recover did before the +// set was recorded. +func spawnsExcept(effects []state.Effect, ended *ActorSet) []state.Effect { + if ended == nil { return effects } out := make([]state.Effect, 0, len(effects)) for _, eff := range effects { - if sp, ok := eff.(state.SpawnActor); ok && !slices.Contains(running.IDs, sp.ID) { + if sp, ok := eff.(state.SpawnActor); ok && slices.Contains(ended.IDs, sp.ID) { continue } out = append(out, eff) @@ -1076,10 +1121,10 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // with every still-pending timer's deadline for the next checkpoint. armed := map[string]pendingTimer{} - // running is the latest recorded set of the actors the live run had running: the - // checkpoint's, then each tail Record's that records one. Nil means none was + // ended is the latest recorded set of the declared actors the live run had ended: + // the checkpoint's, then each tail Record's that records one. Nil means none was // recorded, so Recover spawns every actor the configuration declares. - running := env.Actors + ended := env.EndedActors for i := range tail { // A canceled context can stop a replayed settle or tick with no error, leaving @@ -1092,8 +1137,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S if err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } - if rec.Actors != nil { - running = rec.Actors + if rec.EndedActors != nil { + ended = rec.EndedActors } now, haveNow := tickInstant(rec.Entries) // Mirror the step into the armed table so it tracks the still-pending set, with @@ -1136,16 +1181,25 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // the recorded run already settled, which replay reconstructed by re-firing the // parent rather than re-running behavior. if actors != nil { - actors.Absorb(ctx, spawnsRunning(inst.StartEffects(), running)) + actors.Absorb(ctx, spawnsExcept(inst.StartEffects(), ended)) // A parent Fire a re-spawned actor drove (a failed spawn's onError) belongs to no // recorded step, so it mustn't reach the next step's check. actorFires.take() } - // The actors now running are the ones the journal records, so the next step records - // a set only when it changes them. - var recoveredActors []string + // The journal's ended actors stay ended, and seen, so the next step records a set + // only when it changes them. + seen := map[string]bool{} + var endedAt []string if actors != nil { - recoveredActors = actors.IDs() + for _, id := range actors.IDs() { + seen[id] = true + } + if ended != nil { + endedAt = ended.IDs + for _, id := range ended.IDs { + seen[id] = true + } + } } // Re-arm any timer that was pending at the checkpoint but whose arming @@ -1213,8 +1267,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S actors: actors, actorBuf: &actorBuf, actorFires: actorFires, - actorsAt: recoveredActors, - actorsSet: actors != nil, + endedAt: endedAt, + endedSet: actors != nil && ended != nil, + seen: seen, lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, }, nil diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index eb59f49e..4c49fda4 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -443,7 +443,9 @@ func watcherMachine(how string, withService bool) (*state.Machine[string, string case "stop": b = b.Transition("supervising").On("childDone").GoTo("supervising").StopActor(state.ActorID("watcher", "supervising", 0)) } - m := b.Transition("supervising").On("svcDone").GoTo("supervising").Reenter().Quench() + m := b.Transition("supervising").On("svcDone").GoTo("supervising").Reenter(). + Transition("supervising").On("poke").GoTo("supervising"). + Quench() opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} if withService { opts = append(opts, durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("svc", svc))) @@ -486,6 +488,17 @@ func TestRecover_SpawnsTheActorsLiveHadRunning(t *testing.T) { if found, _ := recovered.DeliverToActor(ctx, ref, "finish"); found { t.Fatal("recovered: the actor that settled live is running again") } + // A step on the recovered Handle, then a second Recover, keeps it ended. + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + again, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if found, _ := again.DeliverToActor(ctx, ref, "finish"); found { + t.Fatal("second Recover: the actor that settled live is running again") + } }) } } @@ -582,3 +595,37 @@ func TestTick_FiresNothing_ContextEnded_StaysHealthy(t *testing.T) { t.Fatalf("the Handle failed: %v", err) } } + +// TestRecover_RetriesAFailedSpawn proves an actor whose spawn failed live, which never +// ran, isn't counted as ended: Recover spawns it again, as it did before the journal +// recorded ended actors. +func TestRecover_RetriesAFailedSpawn(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[actorCtx]("retry"). + Actor("spawnChild"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("done").Final(). + Initial("working"). + Transition("working").On("next").GoTo("working"). + Transition("working").On("childDone").GoTo("done"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("retry") + failing := map[string]state.ActorBehavior{"spawnChild": failingSpawn(nil)} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, actorCtx](failing)). + Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "next"); err != nil { + t.Fatalf("Fire: %v", err) + } + var runs int64 + recovered, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ok := recovered.ActorRef(state.ActorID("retry", "working", 0)); !ok { + t.Fatal("Recover didn't spawn the actor whose live spawn failed") + } +} diff --git a/durable/store.go b/durable/store.go index 74f55aad..7e385053 100644 --- a/durable/store.go +++ b/durable/store.go @@ -84,18 +84,20 @@ type Record struct { // accounting across a re-derived tick without a recorded Event per timer. TickSteps int - // Actors, when set, holds the child-machine actors running once this step ended, - // recorded when the step changed them. Recover spawns the instance's declared - // actors that the latest recorded set holds, so an actor that settled or was - // stopped live isn't spawned again. It is nil when the step left them unchanged, for - // a machine with no actor palette, and on a Record from before this field. - Actors *RunningActors `json:",omitempty"` + // EndedActors, when set, holds the child-machine actors the instance's state + // declared once this step ended that ran and have ended, settled or stopped, so + // Recover doesn't spawn them again. An actor whose spawn failed never ran, so it + // isn't one, and Recover tries it again. The first step after Start records the + // set, and later steps record it when they change it. It is nil otherwise, for a + // machine with no actor palette, and on a Record from before this field. An empty + // set is not nil: a Store must keep it, though it treats other empty fields as nil. + EndedActors *ActorSet `json:",omitempty"` } -// RunningActors is the set of child-machine actors running at a point in a durable -// instance's journal. -type RunningActors struct { - // IDs are the running actors' ids, sorted. +// ActorSet is a set of child-machine actor ids at a point in a durable instance's +// journal. +type ActorSet struct { + // IDs are the actors' ids, sorted. IDs []string `json:"ids"` } @@ -132,7 +134,8 @@ func (r *Record) followingStep() int { // already-checkpointed Step is still recognized rather than rejected as out of // order, and a different Record there is still a conflict. Two Records are the // same when every field matches, with a nil and an empty field counting as equal, -// except EventDataError, where nil means no error and an empty message is an error. +// except EventDataError, where nil means no error and an empty message is an error, +// and EndedActors, where nil means none recorded and an empty set means none ended. // An Append carrying WithIdempotencyKey (a backend reads it with // AppendIdempotencyKey) dedups on that key alone, so the caller vouches for the // Record: no comparison is made. Keys starting "step:" are reserved for the Store's From bc66ce0e6a3fdf618d2af3bedef6737ed5308b31 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 13:34:00 -0700 Subject: [PATCH 10/38] fix(durable): judge an ended actor from its spawns, not step boundaries An actor spawned and stopped within one step was never running at a step's end, so it didn't count as ended and Recover spawned it again. And an actor seen running, then re-entered with a spawn that failed, counted as ended, so Recover didn't retry it, as base did. durable now notes the spawns the actor system starts (its inspector reports one only once the actor started) and the spawns it's asked for (the effects durable absorbs into it, and each parent Fire's). At a step's end, a declared actor that isn't running has ended if it settled, or if the step asked for it and a spawn this step started it, or, if the step didn't ask, if it was running or ended at the previous step. Signed-off-by: Ray Karnes --- durable/actor_lifecycle_test.go | 273 ++++++++++++++++++++++++++++++++ durable/runner.go | 95 ++++++++--- 2 files changed, 348 insertions(+), 20 deletions(-) create mode 100644 durable/actor_lifecycle_test.go diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go new file mode 100644 index 00000000..8a453236 --- /dev/null +++ b/durable/actor_lifecycle_test.go @@ -0,0 +1,273 @@ +package durable_test + +// The Recover tests for actors whose lifecycle a step journals: an actor spawned and +// stopped within one step, and failed spawns on re-entry, by a Fire, a settle, or a +// recovered Handle, which Recover retries as it always has. + +import ( + "context" + "errors" + "fmt" + "sync/atomic" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// driverChild: on "go" it sends the parent "toZ" then "kill" in one step. +func driverChild() state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + child := state.ForgeFor[actorCtx]("driver"). + State("ready"). + Initial("ready"). + Transition("ready").On("go").GoTo("ready").SendParent("toZ").SendParent("kill"). + Quench() + return state.NewActor(child.Cast(actorCtx{}, state.WithInitialState[string]("ready")), nil), nil + } +} + +func flipMachine() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("flip"). + Actor("spawnDriver"). + Actor("spawnChild"). + State("y").InvokeActor("spawnDriver"). + State("z").InvokeActor("spawnChild"). + Initial("y"). + Transition("y").On("toZ").GoTo("z"). + Transition("z").On("kill").GoTo("z").StopActor(state.ActorID("flip", "z", 0)). + Transition("z").On("poke").GoTo("z"). + Quench() +} + +// An actor spawned and stopped within one delivery is never seen at a step boundary, +// so the ended set misses it and Recover spawns it though live has it stopped. +func TestRecover_ActorSpawnedAndStoppedInOneStep_StaysEnded(t *testing.T) { + ctx := context.Background() + childID := state.ActorID("flip", "z", 0) + driverID := state.ActorID("flip", "y", 0) + for _, every := range []int{0, 1, 2, 3} { + t.Run(fmt.Sprintf("checkpoint every %d", every), func(t *testing.T) { + var runs int64 + pal := map[string]state.ActorBehavior{"spawnDriver": driverChild(), "spawnChild": counterChild(&runs)} + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](pal)} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, actorCtx](every)) + } + m := flipMachine() + store := durable.NewMemStore() + id := durable.InstanceID(fmt.Sprintf("flip-%d", every)) + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("y")) + if err != nil { + t.Fatal(err) + } + ref, ok := h.ActorRef(driverID) + if !ok { + t.Fatal("no driver") + } + if _, err := h.DeliverToActor(ctx, ref, "go"); err != nil { + t.Fatal(err) + } + if got := h.Instance().Current(); got != "z" { + t.Fatalf("live state %v", got) + } + if _, ok := h.ActorRef(childID); ok { + t.Fatal("live: child should be stopped") + } + rec, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatal(err) + } + if _, ok := rec.ActorRef(childID); ok { + t.Error("Recover: child is running, live had it stopped") + } + // A step on the recovered Handle, then a second Recover. + if _, err := rec.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + again, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatal(err) + } + if _, ok := again.ActorRef(childID); ok { + t.Error("second Recover: child is running, live had it stopped") + } + }) + } +} + +type probeCtx struct { + Notes []string `json:"notes"` +} + +func probeChild() state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + child := state.ForgeFor[probeCtx]("child"). + State("working").State("done").Final().Initial("working"). + Transition("working").On("finish").GoTo("done").Quench() + inst := child.Cast(probeCtx{}, state.WithInitialState[string]("working")) + return state.NewActor(inst, func(*state.Instance[string, string, probeCtx]) any { return "out" }), nil + } +} + +func probeMachine() *state.Machine[string, string, probeCtx] { + return state.ForgeFor[probeCtx]("probe"). + Actor("spawnChild"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone"), state.WithInvokeOnError("childErr")). + State("done").Final(). + Initial("working"). + Transition("working").On("re").GoTo("working").Reenter(). + Transition("working").On("poke").GoTo("working"). + Transition("working").On("childErr").GoTo("working"). + Transition("working").On("childDone").GoTo("done"). + Quench() +} + +// First spawn succeeds, later ones fail. +func TestRecover_RetriesAFailedReentrySpawn(t *testing.T) { + ctx := context.Background() + m := probeMachine() + store := durable.NewMemStore() + id := durable.InstanceID("p1") + var n int64 + pal := map[string]state.ActorBehavior{"spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 1 { + return nil, errors.New("can't start") + } + return probeChild()(in) + }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, probeCtx](pal)). + Start(ctx, id, probeCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + if _, err := h.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + if _, err := h.Fire(ctx, "re"); err != nil { + t.Fatal(err) + } + aid := state.ActorID("probe", "working", 0) + if _, ok := h.ActorRef(aid); ok { + t.Fatal("setup: respawn should have failed") + } + good := map[string]state.ActorBehavior{"spawnChild": probeChild()} + rec, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := rec.ActorRef(aid); !ok { + t.Fatal("Recover didn't retry the actor whose re-entry spawn failed live") + } +} + +// Live: running at crash. Recover #1 spawn fails; a step; Recover #2 succeeds. +func TestRecover_RetriesASpawnThatFailedAtRecover(t *testing.T) { + ctx := context.Background() + m := probeMachine() + store := durable.NewMemStore() + id := durable.InstanceID("p2") + good := map[string]state.ActorBehavior{"spawnChild": probeChild()} + bad := map[string]state.ActorBehavior{"spawnChild": func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("x") }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, probeCtx](good)). + Start(ctx, id, probeCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + if _, err := h.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + r1, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](bad)) + if err != nil { + t.Fatal(err) + } + if _, err := r1.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + r2, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := r2.ActorRef(state.ActorID("probe", "working", 0)); !ok { + t.Fatal("second Recover didn't retry") + } +} + +// Running at crash, recovered handle re-enters and its respawn fails, then Recover. +func TestRecover_RetriesAFailedReentrySpawnOnARecoveredHandle(t *testing.T) { + ctx := context.Background() + m := probeMachine() + store := durable.NewMemStore() + id := durable.InstanceID("p3") + good := map[string]state.ActorBehavior{"spawnChild": probeChild()} + var n int64 + once := map[string]state.ActorBehavior{"spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 1 { + return nil, errors.New("can't start") + } + return probeChild()(in) + }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, probeCtx](good)). + Start(ctx, id, probeCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + if _, err := h.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + r1, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](once)) + if err != nil { + t.Fatal(err) + } + if _, err := r1.Fire(ctx, "re"); err != nil { + t.Fatal(err) + } + r2, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := r2.ActorRef(state.ActorID("probe", "working", 0)); !ok { + t.Fatal("Recover didn't retry") + } +} + +func TestRecover_RetriesASpawnThatFailedWhenASettleReentered(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[probeCtx]("probe2"). + Actor("spawnChild"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone"), state.WithInvokeOnError("childErr")). + Initial("working"). + Transition("working").On("childDone").GoTo("working").Reenter(). + Transition("working").On("childErr").GoTo("working"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("p4") + var n int64 + pal := map[string]state.ActorBehavior{"spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 1 { + return nil, errors.New("can't start") + } + return probeChild()(in) + }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, probeCtx](pal)). + Start(ctx, id, probeCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + aid := state.ActorID("probe2", "working", 0) + ref, _ := h.ActorRef(aid) + if found, err := h.DeliverToActor(ctx, ref, "finish"); !found || err != nil { + t.Fatalf("deliver: %v %v", found, err) + } + if _, ok := h.ActorRef(aid); ok { + t.Fatal("setup: respawn should have failed") + } + good := map[string]state.ActorBehavior{"spawnChild": probeChild()} + rec, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := rec.ActorRef(aid); !ok { + t.Fatal("Recover didn't retry the actor whose re-entry spawn (via settle) failed live") + } +} diff --git a/durable/runner.go b/durable/runner.go index 175e5a19..ab1cfa46 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -352,6 +352,7 @@ func (h *Handle[S, E, C]) absorbDrivers(ctx context.Context, effects []state.Eff h.svc.Absorb(ctx, effects) } if h.actors != nil { + h.actorFires.attempt(effects) h.actors.Absorb(ctx, effects) } } @@ -545,6 +546,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // A parent Fire a starting actor drove (a failed spawn's onError) belongs to no // recorded step, so it mustn't reach the first step's check. actorFires.take() + actorFires.takeLifecycle() } // The actors that started are seen running, so one later stopped counts as ended. seen := map[string]bool{} @@ -592,7 +594,8 @@ func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) (*state. return nil, nil } fires := &parentFires[S]{} - sys := state.NewActorSystem(inst).WithParentFireObserver(fires.note) + sys := state.NewActorSystem(inst).WithParentFireObserver(fires.note). + WithActorInspector(state.InspectorFunc(fires.inspect)) for src, behavior := range r.cfg.actorPalette { sys.Register(src, behavior) } @@ -600,16 +603,62 @@ func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) (*state. } // parentFires collects the parent Fires an actor system drives, so the step that drove -// them can check and record them. +// them can check and record them, and the actors it spawned, so an actor spawned and +// stopped inside one step still counts as having run. type parentFires[S comparable] struct { - mu sync.Mutex - fires []state.ParentFire[S] + mu sync.Mutex + fires []state.ParentFire[S] + spawned []string // actors that started + attempted map[string]bool // actors the system was asked to spawn +} + +// attempt notes the actors effects ask the system to spawn. +func (p *parentFires[S]) attempt(effects []state.Effect) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok { + if p.attempted == nil { + p.attempted = map[string]bool{} + } + p.attempted[sp.ID] = true + } + } +} + +// takeLifecycle returns the actors spawned and the actors asked to spawn since the +// last call, and forgets them. It's safe on a nil collector, which has none. +func (p *parentFires[S]) takeLifecycle() (spawned []string, attempted map[string]bool) { + if p == nil { + return nil, nil + } + p.mu.Lock() + defer p.mu.Unlock() + spawned, attempted = p.spawned, p.attempted + p.spawned, p.attempted = nil, nil + return spawned, attempted +} + +// inspect notes each actor the system spawned. The system reports a spawn only once +// the actor started, so a spawn that failed isn't noted. +func (p *parentFires[S]) inspect(ev state.InspectionEvent) { + if ev.Kind != state.InspectActor || ev.ActorPhase != state.ActorSpawned { + return + } + p.mu.Lock() + p.spawned = append(p.spawned, ev.ActorID) + p.mu.Unlock() } func (p *parentFires[S]) note(pf state.ParentFire[S]) { p.mu.Lock() p.fires = append(p.fires, pf) p.mu.Unlock() + // The system absorbs a parent Fire's effects next, which spawns what they declare. + p.attempt(pf.Result.Effects) } // take returns the Fires noted since the last take, in fire order, and forgets them. @@ -984,35 +1033,40 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) } // endedActors returns the actors the instance's state declares that ran and have -// ended: not running now, and either settled (the actor system keeps a settled actor) -// or seen running at an earlier step (a stopped actor is gone from the system). An -// actor whose spawn failed was never either, so it isn't one, and Recover spawns it -// again. It forgets what it saw of actors the state no longer declares. It is nil with -// no actor palette. +// ended, and remembers them for the next step. A declared actor that isn't running +// has ended when it settled (the actor system keeps a settled actor), or when this +// step asked the system to spawn it and a spawn this step started it (then something +// stopped it), or, when this step didn't try to spawn it, when it was running or ended +// at the previous step. So an actor whose spawn failed, at entry or on a re-entry, +// hasn't ended, and Recover tries it again. It is nil with no actor palette. func (h *Handle[S, E, C]) endedActors() *ActorSet { if h.actors == nil { return nil } + spawned, attempted := h.actorFires.takeLifecycle() running := h.actors.IDs() - declared := declaredActors(h.inst.StartEffects()) - for _, id := range running { - h.seen[id] = true - } - for id := range h.seen { - if !slices.Contains(declared, id) { - delete(h.seen, id) - } - } ended := []string{} - for _, id := range declared { + for _, id := range declaredActors(h.inst.StartEffects()) { if slices.Contains(running, id) { continue } - if _, settled := h.actors.Ref(id); settled || h.seen[id] { + _, ran := h.actors.Ref(id) + switch { + case ran: + case attempted[id]: + ran = slices.Contains(spawned, id) + default: + ran = h.seen[id] + } + if ran { ended = append(ended, id) } } slices.Sort(ended) + h.seen = map[string]bool{} + for _, id := range append(running, ended...) { + h.seen[id] = true + } return &ActorSet{IDs: ended} } @@ -1185,6 +1239,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // A parent Fire a re-spawned actor drove (a failed spawn's onError) belongs to no // recorded step, so it mustn't reach the next step's check. actorFires.take() + actorFires.takeLifecycle() } // The journal's ended actors stay ended, and seen, so the next step records a set // only when it changes them. From 655032dbed0109c8941c80104312434f2df0110a Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 13:50:29 -0700 Subject: [PATCH 11/38] fix(durable): the latest spawn attempt decides whether an actor ran When one step tried to spawn an actor twice, the first spawn starting and the second failing, the first success counted, so the actor was recorded as ended and Recover didn't retry it. An attempt now clears any earlier success for that actor in the step, so only a spawn that starts after the latest attempt counts. A checkpoint step computes the ended actors once, for both the checkpoint and the Record. Signed-off-by: Ray Karnes --- durable/actor_lifecycle_test.go | 126 ++++++++++++++++++++++++++++++++ durable/runner.go | 25 ++++--- 2 files changed, 141 insertions(+), 10 deletions(-) diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go index 8a453236..33aada5e 100644 --- a/durable/actor_lifecycle_test.go +++ b/durable/actor_lifecycle_test.go @@ -271,3 +271,129 @@ func TestRecover_RetriesASpawnThatFailedWhenASettleReentered(t *testing.T) { t.Fatal("Recover didn't retry the actor whose re-entry spawn (via settle) failed live") } } + +type rsCtx struct { + N int `json:"n"` +} + +func rsChild() state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + c := state.ForgeFor[rsCtx]("rschild"). + State("w").Initial("w"). + Transition("w").On("go").GoTo("w").SendParent("re").SendParent("re"). + Quench() + return state.NewActor(c.Cast(rsCtx{}, state.WithInitialState[string]("w")), nil), nil + } +} + +func rsMachine() *state.Machine[string, string, rsCtx] { + return state.ForgeFor[rsCtx]("rs"). + Actor("spawnChild"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnError("childErr")). + Initial("working"). + Transition("working").On("re").GoTo("working").Reenter(). + Transition("working").On("childErr").GoTo("working"). + Transition("working").On("poke").GoTo("working"). + Quench() +} + +// In one delivery the state is re-entered twice: the first respawn starts, the +// second fails. Live ends with no actor; Recover should retry it. +func TestRecover_RetriesAnActorWhoseSecondReentrySpawnFailed(t *testing.T) { + for _, poke := range []bool{false, true} { + ctx := context.Background() + m := rsMachine() + store := durable.NewMemStore() + id := durable.InstanceID("rs") + var n int64 + pal := map[string]state.ActorBehavior{"spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 2 { + return nil, errors.New("can't start") + } + return rsChild()(in) + }} + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, rsCtx](pal)). + Start(ctx, id, rsCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatal(err) + } + aid := state.ActorID("rs", "working", 0) + ref, ok := h.ActorRef(aid) + if !ok { + t.Fatal("no child") + } + if _, err := h.DeliverToActor(ctx, ref, "go"); err != nil { + t.Fatal(err) + } + if got := atomic.LoadInt64(&n); got != 3 { + t.Fatalf("setup: spawns %d, want 3", got) + } + if _, ok := h.ActorRef(aid); ok { + t.Fatal("setup: last respawn should have failed") + } + if poke { + if _, err := h.Fire(ctx, "poke"); err != nil { + t.Fatal(err) + } + } + good := map[string]state.ActorBehavior{"spawnChild": rsChild()} + rec, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, rsCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, ok := rec.ActorRef(aid); !ok { + t.Errorf("poke=%v: Recover didn't retry the actor whose last respawn failed", poke) + } + } +} + +func driver3() state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + child := state.ForgeFor[actorCtx]("driver").State("ready").Initial("ready"). + Transition("ready").On("go").GoTo("ready").SendParent("toZ").SendParent("kill").SendParent("re"). + Quench() + return state.NewActor(child.Cast(actorCtx{}, state.WithInitialState[string]("ready")), nil), nil + } +} + +// Non-blocker probe: in one delivery the z child spawns, is stopped, and its re-entry +// spawn fails. Live: not running. Is it retried by Recover (the stated rule for a failed +// spawn), or recorded as ended? +func TestRecover_RetriesAnActorWhoseLatestSpawnInAStepFailed(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[actorCtx]("flip"). + Actor("spawnDriver").Actor("spawnChild"). + State("y").InvokeActor("spawnDriver"). + State("z").InvokeActor("spawnChild", state.WithInvokeOnError("childErr")). + Initial("y"). + Transition("y").On("toZ").GoTo("z"). + Transition("z").On("kill").GoTo("z").StopActor(state.ActorID("flip", "z", 0)). + Transition("z").On("re").GoTo("z").Reenter(). + Transition("z").On("childErr").GoTo("z"). + Quench() + var n, runs int64 + pal := map[string]state.ActorBehavior{"spawnDriver": driver3(), "spawnChild": func(in map[string]any) (state.ActorInstance, error) { + if atomic.AddInt64(&n, 1) > 1 { + return nil, errors.New("no") + } + return counterChild(&runs)(in) + }} + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store, durable.WithActorPalette[string, string, actorCtx](pal)).Start(ctx, "x", actorCtx{}, state.WithInitialState("y")) + if err != nil { + t.Fatal(err) + } + ref, _ := h.ActorRef(state.ActorID("flip", "y", 0)) + if _, err := h.DeliverToActor(ctx, ref, "go"); err != nil { + t.Fatal(err) + } + cid := state.ActorID("flip", "z", 0) + good := map[string]state.ActorBehavior{"spawnDriver": driver3(), "spawnChild": counterChild(&runs)} + rec, err := durable.Recover(ctx, m, store, "x", durable.WithActorPalette[string, string, actorCtx](good)) + if err != nil { + t.Fatal(err) + } + if _, rr := rec.ActorRef(cid); !rr { + t.Fatal("Recover didn't retry the actor whose latest spawn failed") + } +} diff --git a/durable/runner.go b/durable/runner.go index ab1cfa46..ac62dba5 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -608,8 +608,8 @@ func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) (*state. type parentFires[S comparable] struct { mu sync.Mutex fires []state.ParentFire[S] - spawned []string // actors that started - attempted map[string]bool // actors the system was asked to spawn + spawned map[string]bool // actors whose latest spawn this step started + attempted map[string]bool // actors the system was asked to spawn this step } // attempt notes the actors effects ask the system to spawn. @@ -625,13 +625,15 @@ func (p *parentFires[S]) attempt(effects []state.Effect) { p.attempted = map[string]bool{} } p.attempted[sp.ID] = true + // The latest attempt decides: until it starts, the actor hasn't run again. + delete(p.spawned, sp.ID) } } } // takeLifecycle returns the actors spawned and the actors asked to spawn since the // last call, and forgets them. It's safe on a nil collector, which has none. -func (p *parentFires[S]) takeLifecycle() (spawned []string, attempted map[string]bool) { +func (p *parentFires[S]) takeLifecycle() (spawned, attempted map[string]bool) { if p == nil { return nil, nil } @@ -649,7 +651,10 @@ func (p *parentFires[S]) inspect(ev state.InspectionEvent) { return } p.mu.Lock() - p.spawned = append(p.spawned, ev.ActorID) + if p.spawned == nil { + p.spawned = map[string]bool{} + } + p.spawned[ev.ActorID] = true p.mu.Unlock() } @@ -1005,6 +1010,7 @@ func (h *Handle[S, E, C]) checkpointDue(step int) bool { // dispatch leaves the effect recoverable from the still-present tail rather than // orphaned behind the compaction. func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) error { + now := h.endedActors() if h.checkpointDue(step) { snap, err := state.MarshalSnapshot(h.inst.Snapshot()) if err != nil { @@ -1013,13 +1019,12 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // Wrap the kernel snapshot with the absolute deadlines of the timers armed at // this checkpoint, so a recovery whose compacted tail no longer carries their // arming ScheduleAfter can re-arm them at their recorded instants. - env, err := marshalCheckpoint(snap, h.timers, rec.followingStep(), h.endedActors()) + env, err := marshalCheckpoint(snap, h.timers, rec.followingStep(), now) if err != nil { return fmt.Errorf("durable: marshaling checkpoint envelope at step %d for %q: %w", step, h.id, err) } rec.Snapshot = env } - now := h.endedActors() if now != nil && (!h.endedSet || !slices.Equal(now.IDs, h.endedAt)) { rec.EndedActors = now } @@ -1035,9 +1040,9 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // endedActors returns the actors the instance's state declares that ran and have // ended, and remembers them for the next step. A declared actor that isn't running // has ended when it settled (the actor system keeps a settled actor), or when this -// step asked the system to spawn it and a spawn this step started it (then something -// stopped it), or, when this step didn't try to spawn it, when it was running or ended -// at the previous step. So an actor whose spawn failed, at entry or on a re-entry, +// step asked the system to spawn it and the latest of those spawns started it (then +// something stopped it), or, when this step didn't try to spawn it, when it was +// running or ended at the previous step. So an actor whose spawn failed, at entry or on a re-entry, // hasn't ended, and Recover tries it again. It is nil with no actor palette. func (h *Handle[S, E, C]) endedActors() *ActorSet { if h.actors == nil { @@ -1054,7 +1059,7 @@ func (h *Handle[S, E, C]) endedActors() *ActorSet { switch { case ran: case attempted[id]: - ran = slices.Contains(spawned, id) + ran = spawned[id] default: ran = h.seen[id] } From fe0ad122d19fbf76805733ffef0944f808effcc0 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 14:01:30 -0700 Subject: [PATCH 12/38] fix(state): StartEffects includes a compound state's invokes StartEffects read only the active leaves, so a service or actor declared on a compound state never started while one of its children was active: not at a durable Start or Recover, and not for a child actor's own nested actors. It now walks each active leaf's ancestors, outermost first, each state once. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 4 +++ durable/actor_lifecycle_test.go | 44 ++++++++++++++++++++++++++ state/CHANGELOG.md | 7 ++++ state/invoke.go | 38 ++++++++++++++++------ state/start_effects_superstate_test.go | 41 ++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 10 deletions(-) create mode 100644 state/start_effects_superstate_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 0be54c02..bfb8e2ba 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -162,6 +162,10 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. set, so `Recover` spawns the declared actors that aren't in it. An actor whose spawn failed never ran, so `Recover` tries it again, as before. A journal from before this records no set, and `Recover` spawns every declared actor, as before. +- **A compound state's services and actors start.** `Start` and `Recover` armed only + those declared on the active leaves, so a service or actor on a compound state didn't + run while one of its children was active. They come from `state.StartEffects`, which + now covers every active state. - **A parent Fire that middleware denied replays.** Denied before the kernel saw it, it is recorded as refused, and replay meets the same refusal instead of failing `Recover`. - **A panic during a step fails the Handle.** A panic in host code under the step lock, diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go index 33aada5e..c936a6e4 100644 --- a/durable/actor_lifecycle_test.go +++ b/durable/actor_lifecycle_test.go @@ -397,3 +397,47 @@ func TestRecover_RetriesAnActorWhoseLatestSpawnInAStepFailed(t *testing.T) { t.Fatal("Recover didn't retry the actor whose latest spawn failed") } } + +// TestRecover_SpawnsASuperstatesActor proves an actor a compound state declares runs +// while one of its children is active: Start spawns it, and so does Recover after a +// step moved between the children. +func TestRecover_SpawnsASuperstatesActor(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[actorCtx]("nest"). + Actor("spawnChild"). + SuperState("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + SubState("a"). + SubState("b"). + Initial("a"). + EndSuperState(). + State("done").Final(). + Initial("working"). + Transition("a").On("next").GoTo("b"). + Transition("working").On("childDone").GoTo("done"). + Quench() + var runs int64 + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](counterPalette(&runs))} + store := durable.NewMemStore() + id := durable.InstanceID("nest") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + childID := state.ActorID("nest", "working", 0) + if _, ok := h.ActorRef(childID); !ok { + t.Fatal("Start didn't spawn the superstate's actor") + } + if _, err = h.Fire(ctx, "next"); err != nil { + t.Fatalf("Fire: %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if found, _ := recovered.DeliverToActor(ctx, state.ActorRef{ID: childID}, "finish"); !found { + t.Fatal("Recover didn't spawn the superstate's actor") + } + if got := recovered.Instance().Current(); got != "done" { + t.Fatalf("state = %q, want done after the actor finished", got) + } +} diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 253f54de..09b583cc 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -48,6 +48,13 @@ counts as an additive (minor) versus breaking (major) change. Use the transitions' guards ran now fails, whether or not one was chosen, where it could succeed before. +### Fixed + +- **`StartEffects` includes a compound state's invokes.** It looked only at the active + leaves, so a service or actor declared on a compound state wasn't started while one of + its children was active: not at a durable `Start` or `Recover`, and not for a child + actor's own nested actors. It now reports every active state's, ancestors first. + ## [1.0.0] — 2026-06-13 The first stable release. It freezes the data model, the serialized IR, the diff --git a/state/invoke.go b/state/invoke.go index 6dac951b..95994b30 100644 --- a/state/invoke.go +++ b/state/invoke.go @@ -224,14 +224,15 @@ func (i *Instance[S, E, C]) invokeEffectsOnExit(exits []S, tr *Trace) []Effect { return out } -// StartEffects returns the StartService effects for the invoked services declared -// on the instance's initial active configuration, so a host can arm the services -// of the state(s) entered at Cast — the entry that Fire never observes because no -// event drove it. Call it once, right after Cast, and route the effects through -// the same ServiceRunner used for Fire's effects. It is a pure read of the +// StartEffects returns the StartService and SpawnActor effects for the invoked +// services and actors declared on every active state, so a host can arm the services +// and actors of the state(s) entered at Cast, the entry that Fire never observes +// because no event drove it. Call it once, right after Cast, and route the effects +// through the same drivers used for Fire's effects. It is a pure read of the // configuration and emits no IO, consistent with the kernel's effects-as-data -// contract. A flat or single-spine instance reports its single starting state's -// services; a parallel initial configuration reports every active region's. +// contract. The active states are each active leaf and its ancestors, outermost +// first, so a compound state's invokes come before its children's; a parallel +// configuration reports every active region's. // // StartEffects recomputes over the live configuration on every call, so it is // correct on both Cast (configuration is the initial leaves) and Restore @@ -240,9 +241,26 @@ func (i *Instance[S, E, C]) invokeEffectsOnExit(exits []S, tr *Trace) []Effect { // the invoke/actor starts of the resumed state(s). func (i *Instance[S, E, C]) StartEffects() []Effect { var tr Trace - cfg := i.Configuration() - out := i.invokeEffectsOnEntry(cfg, &tr) - out = append(out, i.actorEffectsOnEntry(cfg, &tr)...) + active := i.activeStates() + out := i.invokeEffectsOnEntry(active, &tr) + out = append(out, i.actorEffectsOnEntry(active, &tr)...) + return out +} + +// activeStates returns every active state: each active leaf's ancestors, outermost +// first, then the leaf, each state once, in the configuration's order. +func (i *Instance[S, E, C]) activeStates() []S { + var out []S + seen := map[S]bool{} + for _, leaf := range i.Configuration() { + chain := i.machine.ancestors(leaf) + for k := len(chain) - 1; k >= 0; k-- { + if s := chain[k]; !seen[s] { + seen[s] = true + out = append(out, s) + } + } + } return out } diff --git a/state/start_effects_superstate_test.go b/state/start_effects_superstate_test.go new file mode 100644 index 00000000..683e0848 --- /dev/null +++ b/state/start_effects_superstate_test.go @@ -0,0 +1,41 @@ +package state_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestStartEffects_IncludesTheSuperstatesInvokes proves StartEffects reports the +// services and actors a compound state declares while one of its children is active, +// the compound state's before its child's. +func TestStartEffects_IncludesTheSuperstatesInvokes(t *testing.T) { + svc := func(context.Context, state.ServiceCtx[*trec]) (any, error) { return nil, nil } + m := state.ForgeFor[*trec]("nest"). + Service("outerSvc", svc). + Service("innerSvc", svc). + Actor("outerActor"). + SuperState("outer").Invoke("outerSvc").InvokeActor("outerActor"). + SubState("inner").Invoke("innerSvc"). + Initial("inner"). + EndSuperState(). + Initial("outer"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("inner")) + var services, actors []string + for _, eff := range inst.StartEffects() { + switch e := eff.(type) { + case state.StartService: + services = append(services, e.Src.Name) + case state.SpawnActor: + actors = append(actors, e.Src.Name) + } + } + if len(services) != 2 || services[0] != "outerSvc" || services[1] != "innerSvc" { + t.Fatalf("services = %v, want [outerSvc innerSvc]", services) + } + if len(actors) != 1 || actors[0] != "outerActor" { + t.Fatalf("actors = %v, want [outerActor]", actors) + } +} From b8b1be835773bdd70f544f13507f00212906c9f4 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 14:11:17 -0700 Subject: [PATCH 13/38] fix(durable): journal a failed spawn's onError When an actor a Fire, RunService, Start or Recover spawned couldn't start and its onError applied, nothing recorded the onError. Recover then applied it again by retrying the spawn, or, once the spawn worked, never applied it, so a later step could replay from a state the live run never had. state.ParentFire now names the actor each parent Fire came from and marks the onError of a spawn that couldn't start. A Fire's or settle's absorb-driven parent Fires are recorded as actor entries with their step, and replay re-fires them after the step's own work. The ones Start's or Recover's spawns drove are held and recorded with the next step, marked to replay before its own work. A spawn whose onError applied counts as ended, so Recover doesn't retry it; one with no onError to route to is still retried. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 9 +- durable/actor.go | 91 ++++++++++++++----- durable/actor_lifecycle_test.go | 12 +-- durable/runner.go | 131 ++++++++++++++++++++-------- durable/service.go | 12 ++- durable/step_rule_test.go | 149 ++++++++++++++++++++++++++++++++ durable/store.go | 7 +- state/CHANGELOG.md | 5 +- state/actor_system.go | 12 ++- 9 files changed, 350 insertions(+), 78 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index bfb8e2ba..aef361d2 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -160,8 +160,15 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. without leaving the state, or an explicit stop. Each step now records the declared actors that ran and ended, in the new `Record.EndedActors`, and a checkpoint keeps the set, so `Recover` spawns the declared actors that aren't in it. An actor whose spawn - failed never ran, so `Recover` tries it again, as before. A journal from before this + failed with no onError never ran, so `Recover` tries it again, as before; one whose + onError applied counts as ended, since the journal holds that onError. A journal from before this records no set, and `Recover` spawns every declared actor, as before. +- **A failed spawn's onError is journaled.** When an actor a `Fire`, `RunService`, + `Start` or `Recover` spawned couldn't start and its onError applied, nothing recorded + the onError, so `Recover` either applied it again by retrying the spawn, or, once the + spawn worked, never applied it. A Fire's or settle's onError is now recorded with its + step, and one from `Start`'s or `Recover`'s spawns with the step after, and replay + re-fires each where it ran. - **A compound state's services and actors start.** `Start` and `Recover` armed only those declared on the active leaves, so a service or actor on a compound state didn't run while one of its children was active. They come from `state.StartEffects`, which diff --git a/durable/actor.go b/durable/actor.go index 6fc8c121..ef9bc703 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -93,6 +93,10 @@ type actorMessagePayload struct { // on it. A refusal because a context ended is never recorded: that step fails the // Handle instead. Refused bool `json:"refused,omitempty"` + // Before reports a parent Fire that ran before the step's own work: one a spawn at + // Start or Recover drove, recorded with the step that followed. Replay re-fires it + // first. + Before bool `json:"before,omitempty"` } // DeliverToActor routes event into the running actor identified by ref, runs the @@ -202,36 +206,77 @@ func recordActorTransitions[S comparable](id string, traces []state.Trace, fires } entries := make([]state.JournalEntry, 0, len(traces)) for i, tr := range traces { - var mp actorMessagePayload - mp.Event = append(json.RawMessage(nil), tr.EventPayload...) - mp.Refused = fires[i].Result.Err != nil - if fires[i].Settle { - mp.HasData = true - switch { - case fires[i].Err != nil: - msg := fires[i].Err.Error() - mp.Error = &msg - case fires[i].Output != nil: - raw, err := json.Marshal(fires[i].Output) - if err != nil { - return nil, fmt.Errorf("marshaling actor output: %w", err) - } - mp.Data = raw - } + entry, err := actorEntry(id, tr.EventPayload, fires[i], false) + if err != nil { + return nil, err } - payload, err := json.Marshal(mp) + entries = append(entries, entry) + } + return entries, nil +} + +// recordParentFires builds the JournalActorMessage entries for parent Fires an actor +// system drove outside a delivery, such as a failed spawn's onError, each under the +// actor it came from. before marks Fires that ran before the step's own work. +func recordParentFires[S comparable](fires []state.ParentFire[S], before bool) ([]state.JournalEntry, error) { + entries := make([]state.JournalEntry, 0, len(fires)) + for _, pf := range fires { + entry, err := actorEntry(pf.ActorID, pf.Result.Trace.EventPayload, pf, before) if err != nil { - return nil, fmt.Errorf("marshaling actor transition: %w", err) + return nil, err } - entries = append(entries, state.JournalEntry{ - Kind: state.JournalActorMessage, - CorrelationID: id, - Payload: payload, - }) + entries = append(entries, entry) } return entries, nil } +// actorEntry builds one JournalActorMessage entry: the parent Fire's event payload, +// whether the live Fire was refused, and, for a Fire that settled an actor, the +// actor's outcome, which it passed as event data, so replay re-fires the same onDone +// or onError with it. +func actorEntry[S comparable](id string, event json.RawMessage, pf state.ParentFire[S], before bool) (state.JournalEntry, error) { + var mp actorMessagePayload + mp.Event = append(json.RawMessage(nil), event...) + mp.Refused = pf.Result.Err != nil + mp.Before = before + if pf.Settle { + mp.HasData = true + switch { + case pf.Err != nil: + msg := pf.Err.Error() + mp.Error = &msg + case pf.Output != nil: + raw, err := json.Marshal(pf.Output) + if err != nil { + return state.JournalEntry{}, fmt.Errorf("marshaling actor output: %w", err) + } + mp.Data = raw + } + } + payload, err := json.Marshal(mp) + if err != nil { + return state.JournalEntry{}, fmt.Errorf("marshaling actor transition: %w", err) + } + return state.JournalEntry{Kind: state.JournalActorMessage, CorrelationID: id, Payload: payload}, nil +} + +// splitActorEntries returns a Record's actor entries in recorded order, the ones that +// ran before the step's own work apart from the rest. +func splitActorEntries(rec *Record) (before, rest []state.JournalEntry, err error) { + for _, e := range actorEntries(rec) { + var mp actorMessagePayload + if err := json.Unmarshal(e.Payload, &mp); err != nil { + return nil, nil, fmt.Errorf("durable: decoding recorded actor %q transition: %w", e.CorrelationID, err) + } + if mp.Before { + before = append(before, e) + } else { + rest = append(rest, e) + } + } + return before, rest, nil +} + // replayActor re-fires one recorded parent transition directly through the // instance, in place of re-running the actor: it decodes the recorded payload and // re-fires the parent's event — carrying the recorded done-data / error via diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go index c936a6e4..523f8831 100644 --- a/durable/actor_lifecycle_test.go +++ b/durable/actor_lifecycle_test.go @@ -113,12 +113,11 @@ func probeChild() state.ActorBehavior { func probeMachine() *state.Machine[string, string, probeCtx] { return state.ForgeFor[probeCtx]("probe"). Actor("spawnChild"). - State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone"), state.WithInvokeOnError("childErr")). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). State("done").Final(). Initial("working"). Transition("working").On("re").GoTo("working").Reenter(). Transition("working").On("poke").GoTo("working"). - Transition("working").On("childErr").GoTo("working"). Transition("working").On("childDone").GoTo("done"). Quench() } @@ -235,10 +234,9 @@ func TestRecover_RetriesASpawnThatFailedWhenASettleReentered(t *testing.T) { ctx := context.Background() m := state.ForgeFor[probeCtx]("probe2"). Actor("spawnChild"). - State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone"), state.WithInvokeOnError("childErr")). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). Initial("working"). Transition("working").On("childDone").GoTo("working").Reenter(). - Transition("working").On("childErr").GoTo("working"). Quench() store := durable.NewMemStore() id := durable.InstanceID("p4") @@ -289,10 +287,9 @@ func rsChild() state.ActorBehavior { func rsMachine() *state.Machine[string, string, rsCtx] { return state.ForgeFor[rsCtx]("rs"). Actor("spawnChild"). - State("working").InvokeActor("spawnChild", state.WithInvokeOnError("childErr")). + State("working").InvokeActor("spawnChild"). Initial("working"). Transition("working").On("re").GoTo("working").Reenter(). - Transition("working").On("childErr").GoTo("working"). Transition("working").On("poke").GoTo("working"). Quench() } @@ -364,12 +361,11 @@ func TestRecover_RetriesAnActorWhoseLatestSpawnInAStepFailed(t *testing.T) { m := state.ForgeFor[actorCtx]("flip"). Actor("spawnDriver").Actor("spawnChild"). State("y").InvokeActor("spawnDriver"). - State("z").InvokeActor("spawnChild", state.WithInvokeOnError("childErr")). + State("z").InvokeActor("spawnChild"). Initial("y"). Transition("y").On("toZ").GoTo("z"). Transition("z").On("kill").GoTo("z").StopActor(state.ActorID("flip", "z", 0)). Transition("z").On("re").GoTo("z").Reenter(). - Transition("z").On("childErr").GoTo("z"). Quench() var n, runs int64 pal := map[string]state.ActorBehavior{"spawnDriver": driver3(), "spawnChild": func(in map[string]any) (state.ActorInstance, error) { diff --git a/durable/runner.go b/durable/runner.go index ac62dba5..0378bedd 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -138,6 +138,7 @@ type Handle[S comparable, E comparable, C any] struct { endedAt []string // the ended actors the journal last recorded endedSet bool // whether endedAt holds a recorded set seen map[string]bool // declared actors seen running, so a stopped one counts as ended + pending []state.ParentFire[S] // parent Fires Start's or Recover's spawns drove, journaled with the next step actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step @@ -542,12 +543,12 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt actorBuf := make([]state.JournalEntry, 0) actors, actorFires := r.newActorSystem(inst) if actors != nil { + actorFires.attempt(inst.StartEffects()) actors.Absorb(ctx, inst.StartEffects()) - // A parent Fire a starting actor drove (a failed spawn's onError) belongs to no - // recorded step, so it mustn't reach the first step's check. - actorFires.take() - actorFires.takeLifecycle() } + // A parent Fire a starting actor drove (a failed spawn's onError) applied to the + // instance after its baseline, so the first step journals it, ahead of its own work. + startFires := heldFires(actorFires.take()) // The actors that started are seen running, so one later stopped counts as ended. seen := map[string]bool{} if actors != nil { @@ -570,6 +571,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt actorBuf: &actorBuf, actorFires: actorFires, seen: seen, + pending: startFires, lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, }, nil @@ -610,6 +612,7 @@ type parentFires[S comparable] struct { fires []state.ParentFire[S] spawned map[string]bool // actors whose latest spawn this step started attempted map[string]bool // actors the system was asked to spawn this step + failed map[string]bool // actors whose latest spawn failed and whose onError applied } // attempt notes the actors effects ask the system to spawn. @@ -627,21 +630,22 @@ func (p *parentFires[S]) attempt(effects []state.Effect) { p.attempted[sp.ID] = true // The latest attempt decides: until it starts, the actor hasn't run again. delete(p.spawned, sp.ID) + delete(p.failed, sp.ID) } } } // takeLifecycle returns the actors spawned and the actors asked to spawn since the // last call, and forgets them. It's safe on a nil collector, which has none. -func (p *parentFires[S]) takeLifecycle() (spawned, attempted map[string]bool) { +func (p *parentFires[S]) takeLifecycle() (spawned, attempted, failed map[string]bool) { if p == nil { - return nil, nil + return nil, nil, nil } p.mu.Lock() defer p.mu.Unlock() - spawned, attempted = p.spawned, p.attempted - p.spawned, p.attempted = nil, nil - return spawned, attempted + spawned, attempted, failed = p.spawned, p.attempted, p.failed + p.spawned, p.attempted, p.failed = nil, nil, nil + return spawned, attempted, failed } // inspect notes each actor the system spawned. The system reports a spawn only once @@ -661,6 +665,14 @@ func (p *parentFires[S]) inspect(ev state.InspectionEvent) { func (p *parentFires[S]) note(pf state.ParentFire[S]) { p.mu.Lock() p.fires = append(p.fires, pf) + // A spawn whose onError applied is handled: the journal holds the onError, so + // retrying the spawn would apply it twice. + if pf.SpawnFailed && pf.Result.Err == nil { + if p.failed == nil { + p.failed = map[string]bool{} + } + p.failed[pf.ActorID] = true + } p.mu.Unlock() // The system absorbs a parent Fire's effects next, which spawns what they declare. p.attempt(pf.Result.Effects) @@ -791,9 +803,16 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi // 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. - if err := refusedByContext(parentFireErrs(h.actorFires.take())...); err != nil { + fires := h.actorFires.take() + if err := refusedByContext(parentFireErrs(fires)...); err != nil { return res, nil, nil, h.fail(fmt.Errorf("durable: firing %q: %w", h.id, err)) } + // The parent Fires the absorb drove, such as a spawned actor's onError, applied + // after the event, so the step journals them, and replay re-fires them after it. + driven, err := recordParentFires(fires, false) + if err != nil { + return res, nil, nil, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) + } step := h.nextStep // Stamp this step's domain effects with their deterministic ids and carry them @@ -804,7 +823,7 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi if err != nil { return res, nil, nil, h.fail(err) } - rec := &Record{Step: step, Event: []byte(res.Trace.EventPayload), EventData: payload.data, EventDataError: payload.errMsg, Entries: h.drainClock(), Effects: effEnvs} + rec := &Record{Step: step, Event: []byte(res.Trace.EventPayload), EventData: payload.data, EventDataError: payload.errMsg, Entries: append(h.drainClock(), driven...), Effects: effEnvs} if err := h.appendStep(ctx, step, rec); err != nil { return res, nil, nil, h.fail(err) } @@ -1011,6 +1030,14 @@ func (h *Handle[S, E, C]) checkpointDue(step int) bool { // orphaned behind the compaction. func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) error { now := h.endedActors() + held := len(h.pending) + if held > 0 { + before, err := recordParentFires(h.pending, true) + if err != nil { + return fmt.Errorf("durable: recording step %d for %q: %w", step, h.id, err) + } + rec.Entries = append(rec.Entries, before...) + } if h.checkpointDue(step) { snap, err := state.MarshalSnapshot(h.inst.Snapshot()) if err != nil { @@ -1034,9 +1061,23 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) if now != nil { h.endedAt, h.endedSet = now.IDs, true } + h.pending = h.pending[held:] return nil } +// heldFires returns the parent Fires a Start's or Recover's spawns drove that applied +// or were refused for good: one a context's ending refused never applied and isn't +// replayable, so it isn't journaled, and the spawn is tried again. +func heldFires[S comparable](fires []state.ParentFire[S]) []state.ParentFire[S] { + var out []state.ParentFire[S] + for _, pf := range fires { + if pf.Result.Err == nil || !isContextErr(pf.Result.Err) { + out = append(out, pf) + } + } + return out +} + // endedActors returns the actors the instance's state declares that ran and have // ended, and remembers them for the next step. A declared actor that isn't running // has ended when it settled (the actor system keeps a settled actor), or when this @@ -1048,7 +1089,7 @@ func (h *Handle[S, E, C]) endedActors() *ActorSet { if h.actors == nil { return nil } - spawned, attempted := h.actorFires.takeLifecycle() + spawned, attempted, failed := h.actorFires.takeLifecycle() running := h.actors.IDs() ended := []string{} for _, id := range declaredActors(h.inst.StartEffects()) { @@ -1059,7 +1100,7 @@ func (h *Handle[S, E, C]) endedActors() *ActorSet { switch { case ran: case attempted[id]: - ran = spawned[id] + ran = spawned[id] || failed[id] default: ran = h.seen[id] } @@ -1240,12 +1281,13 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // the recorded run already settled, which replay reconstructed by re-firing the // parent rather than re-running behavior. if actors != nil { - actors.Absorb(ctx, spawnsExcept(inst.StartEffects(), ended)) - // A parent Fire a re-spawned actor drove (a failed spawn's onError) belongs to no - // recorded step, so it mustn't reach the next step's check. - actorFires.take() - actorFires.takeLifecycle() + spawns := spawnsExcept(inst.StartEffects(), ended) + actorFires.attempt(spawns) + actors.Absorb(ctx, spawns) } + // A parent Fire a re-spawned actor drove (a failed spawn's onError) applied to the + // instance past its journal, so the next step journals it, ahead of its own work. + recoverFires := heldFires(actorFires.take()) // The journal's ended actors stay ended, and seen, so the next step records a set // only when it changes them. seen := map[string]bool{} @@ -1330,6 +1372,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S endedAt: endedAt, endedSet: actors != nil && ended != nil, seen: seen, + pending: recoverFires, lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, }, nil @@ -1580,9 +1623,12 @@ type replayed[S comparable] struct { // it, running no service, actor or effect handler. Recover and StateAt both walk the // journal with it; Recover adds its deadline table and effect re-dispatch on top. // +// - Parent Fires a Start's or Recover's spawns drove, recorded with the next step, +// re-fire first, before the step's own work. // - An actor delivery re-fires each parent transition the delivery drove, in fire // order, with the recorded done-data or error, so the kernel re-derives the same -// onDone / onError (or message) transition. +// onDone / onError (or message) transition. A Fire's or settle's absorb-driven +// parent Fires, such as a spawned actor's onError, re-fire after its own work. // - A service settlement re-settles each recorded outcome through the same settle // seam, in settle order; the settle absorbs its own follow-on StartService // effects, so a chained invoke arms its successor for the next entry. @@ -1600,23 +1646,16 @@ func replayRecord[S comparable, E comparable, C any]( rec *Record, ) (replayed[S], error) { var out replayed[S] + before, rest, err := splitActorEntries(rec) + if err != nil { + return out, 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, rec, before); err != nil { + return out, err + } switch { - case hasActorEntry(rec): - for _, entry := range actorEntries(rec) { - if err := replayActor(ctx, inst, cfg.eventCodec, entry); err != nil { - return out, fmt.Errorf("at step %d: %w", rec.Step, err) - } - } - case hasServiceEntry(rec): - for _, entry := range serviceEntries(rec) { - if err := replayService(ctx, svc, entry); err != nil { - return out, fmt.Errorf("at step %d: %w", rec.Step, err) - } - } - case rec.Tick: - out.tick = sched.Tick(ctx) - case len(rec.Event) == 0: - default: + case len(rec.Event) > 0: event, err := cfg.eventCodec.Decode(rec.Event) if err != nil { return out, fmt.Errorf("decoding recorded event at step %d: %w", rec.Step, err) @@ -1636,6 +1675,26 @@ func replayRecord[S comparable, E comparable, C any]( svc.Absorb(ctx, res.Effects) } out.fired = &res + case hasServiceEntry(rec): + for _, entry := range serviceEntries(rec) { + if err := replayService(ctx, svc, entry); err != nil { + return out, fmt.Errorf("at step %d: %w", rec.Step, err) + } + } + case rec.Tick: + out.tick = sched.Tick(ctx) } - return out, nil + // 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 out, replayActors(ctx, inst, cfg, rec, rest) +} + +// replayActors re-fires recorded parent transitions, in order. +func replayActors[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], rec *Record, entries []state.JournalEntry) error { + for _, entry := range entries { + if err := replayActor(ctx, inst, cfg.eventCodec, entry); err != nil { + return fmt.Errorf("at step %d: %w", rec.Step, err) + } + } + return nil } diff --git a/durable/service.go b/durable/service.go index 80467fe4..a282161b 100644 --- a/durable/service.go +++ b/durable/service.go @@ -134,7 +134,8 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire // 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. - if err := h.stepCanceled(ctx, append([]error{res.Err}, parentFireErrs(h.actorFires.take())...)...); err != nil { + fires := h.actorFires.take() + if err := h.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)) } @@ -146,8 +147,15 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire *h.svcBuf = append(*h.svcBuf, entry) } + // The parent Fires the absorb drove, such as a spawned actor's onError, applied + // after the settle, so the step journals them, and replay re-fires them after it. + driven, err := recordParentFires(fires, false) + if err != nil { + return res, true, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) + } + step := h.nextStep - rec := Record{Step: step, Entries: h.drainServices()} + rec := Record{Step: step, Entries: append(h.drainServices(), driven...)} if err := h.persistStep(ctx, step, &rec); err != nil { return res, true, err } diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index 4c49fda4..0bbd2eee 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -629,3 +629,152 @@ func TestRecover_RetriesAFailedSpawn(t *testing.T) { t.Fatal("Recover didn't spawn the actor whose live spawn failed") } } + +// failNoteMachine has a state whose actor can't start; its onError applies, staying in +// the state (stay) or leaving it (leave), and notes the failure, so a recovered +// context shows how many times it applied. +func failNoteMachine(initial string, leave bool) stepMachine { + fail := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "fail") + return c + } + target := "spawning" + if leave { + target = "failed" + } + poke := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "poke") + return c + } + return state.ForgeFor[stepCtx]("noting"). + Reducer("noteFail", fail). + Reducer("notePoke", poke). + Actor("spawnChild"). + State("idle"). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + State("failed"). + Initial(initial). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo(target).Assign("noteFail"). + Transition("spawning").On("poke").GoTo("spawning").Assign("notePoke"). + Transition("failed").On("poke").GoTo("failed").Assign("notePoke"). + Quench() +} + +// TestRecover_ReplaysASpawnsOnErrorOnce proves a failed spawn's onError that applied is +// journaled with the step that drove it, or with the step after Start or Recover drove +// it, so Recover reaches the live state and context, applying it once, and doesn't +// retry the spawn. +func TestRecover_ReplaysASpawnsOnErrorOnce(t *testing.T) { + ctx := context.Background() + failing := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnChild": failingSpawn(nil)})} + check := func(t *testing.T, h *durable.Handle[string, string, stepCtx], m stepMachine, store durable.Store, id durable.InstanceID, opts []stepOption) { + t.Helper() + liveState, liveNotes := h.Instance().Current(), fmt.Sprint(h.Instance().Entity().Notes) + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + if got, notes := recovered.Instance().Current(), fmt.Sprint(recovered.Instance().Entity().Notes); got != liveState || notes != liveNotes { + t.Fatalf("Recover %d = %s %s, want the live %s %s", round, got, notes, liveState, liveNotes) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + // The next Recover rebuilds the Handle that just continued. + liveState, liveNotes = recovered.Instance().Current(), fmt.Sprint(recovered.Instance().Entity().Notes) + } + } + for _, leave := range []bool{false, true} { + for _, every := range []int{0, 1} { + opts := append([]stepOption{}, failing...) + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + t.Run(fmt.Sprintf("Fire/leave=%v/every=%d", leave, every), func(t *testing.T) { + m, store, id := failNoteMachine("idle", leave), durable.NewMemStore(), durable.InstanceID("fire") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + check(t, h, m, store, id, opts) + }) + t.Run(fmt.Sprintf("Start/leave=%v/every=%d", leave, every), func(t *testing.T) { + m, store, id := failNoteMachine("spawning", leave), durable.NewMemStore(), durable.InstanceID("start") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("spawning")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + check(t, h, m, store, id, opts) + }) + } + } + t.Run("RunService", func(t *testing.T) { + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + fail := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "fail") + return c + } + m := state.ForgeFor[stepCtx]("noting"). + Service("fetch", fetch). + Reducer("noteFail", fail). + Actor("spawnChild"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + Initial("loading"). + Transition("loading").On("ok").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("spawning").Assign("noteFail"). + Transition("spawning").On("poke").GoTo("spawning"). + Quench() + opts := append([]stepOption{durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch))}, failing...) + store, id := durable.NewMemStore(), durable.InstanceID("settle") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, ran, err := h.RunService(ctx, state.InvokeID("noting", "loading", 0)); err != nil || !ran { + t.Fatalf("RunService = %v, %v", ran, err) + } + check(t, h, m, store, id, opts) + }) + t.Run("a spawn that fails during Recover", func(t *testing.T) { + m, store, id := failNoteMachine("spawning", false), durable.NewMemStore(), durable.InstanceID("at-recover") + good := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnChild": finishingChild()})} + h, err := durable.NewRunner(m, store, good...).Start(ctx, id, stepCtx{}, state.WithInitialState("spawning")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + // Recover while the actor can't start: its onError applies on this Handle. + r1, err := durable.Recover(ctx, m, store, id, failing...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = r1.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + // A later Recover, with the actor able to start, reaches what r1 had. + r2, err := durable.Recover(ctx, m, store, id, good...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if got, want := fmt.Sprint(r2.Instance().Entity().Notes), fmt.Sprint(r1.Instance().Entity().Notes); got != want { + t.Fatalf("second Recover notes = %s, want r1's %s", got, want) + } + if found, _ := r2.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("noting", "spawning", 0)}, "finish"); found { + t.Fatal("second Recover spawned the actor r1 had handled as failed") + } + }) +} diff --git a/durable/store.go b/durable/store.go index 7e385053..9d750631 100644 --- a/durable/store.go +++ b/durable/store.go @@ -85,9 +85,10 @@ type Record struct { TickSteps int // EndedActors, when set, holds the child-machine actors the instance's state - // declared once this step ended that ran and have ended, settled or stopped, so - // Recover doesn't spawn them again. An actor whose spawn failed never ran, so it - // isn't one, and Recover tries it again. The first step after Start records the + // declared once this step ended that ran and have ended, settled or stopped, or + // whose spawn failed and whose onError applied (the journal holds that onError), so + // Recover doesn't spawn them again. An actor whose spawn failed with no onError to + // route to isn't one, and Recover tries it again. The first step after Start records the // set, and later steps record it when they change it. It is nil otherwise, for a // machine with no actor palette, and on a Record from before this field. An empty // set is not nil: a Store must keep it, though it treats other empty fields as nil. diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 09b583cc..530738da 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -14,8 +14,9 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Added - **`ActorSystem.WithParentFireObserver`** calls a function with each parent Fire the - system drives (a `ParentFire`: its result, refused ones included, and whether it - settled an actor, with the actor's output or error), so a host that records a delivery or spawn + system drives (a `ParentFire`: its result, refused ones included, the actor it came + from, whether it settled that actor, with its output or error, and whether it routed + the onError of a spawn that couldn't start), so a host that records a delivery or spawn can tell a parent transition refused because its context ended from one that applied, and which Fire carried the actor's output. It's additive, within v1.1.0. - **`FireEventData`** reports the payload a `WithEventData` option carries, so a host diff --git a/state/actor_system.go b/state/actor_system.go index c9f07b50..b63e5db7 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -391,7 +391,7 @@ func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err return } res := s.parent.Fire(ctx, ev) - s.noteParentFire(ParentFire[S]{Result: res}) + s.noteParentFire(ParentFire[S]{Result: res, ActorID: e.ID, SpawnFailed: true}) s.Absorb(ctx, res.Effects) } @@ -673,7 +673,7 @@ func (s *ActorSystem[S, E, C]) fireParentFrom(ctx context.Context, event any, se s.mu.Unlock() res := s.parent.Fire(ctx, ev) - s.noteParentFire(ParentFire[S]{Result: res}) + s.noteParentFire(ParentFire[S]{Result: res, ActorID: senderID}) s.Absorb(ctx, res.Effects) s.mu.Lock() @@ -735,7 +735,7 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any payload = output } res := s.parent.Fire(ctx, ev, WithEventData(payload)) - s.noteParentFire(ParentFire[S]{Result: res, Settle: true, Output: output, Err: err}) + s.noteParentFire(ParentFire[S]{Result: res, ActorID: id, Settle: true, Output: output, Err: err}) s.Absorb(ctx, res.Effects) return res, true } @@ -801,6 +801,12 @@ func (s *ActorSystem[S, E, C]) LastError() error { type ParentFire[S comparable] struct { // Result is the parent Fire's result. A refused Fire carries its error. Result FireResult[S] + // ActorID is the actor the Fire came from: the one that settled, sent the message, + // or couldn't start. + ActorID string + // SpawnFailed reports that the Fire routed the onError of a spawn that couldn't + // start (an unbound Src, or a behavior that returned an error). + SpawnFailed bool // Settle reports that the Fire routed a settled actor's onDone or onError, which // carried the actor's outcome as its event data (WithEventData): Err for an onError, // Output for an onDone. A message the actor sent the parent, or the onError of a From e9a00b7fb4aff32572e0dac9e79fd66ac7501e45 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 12 Nov 2026 14:29:23 -0700 Subject: [PATCH 14/38] fix(durable): journal only an absorb's settles and failed-spawn onErrors Journaling every parent Fire an absorb drove included the message a running actor sends as it spawns. Recover spawns that actor again, which sends it again, so the message applied twice, and once more with each Recover. An absorb's journal now holds only settles, after which the actor has ended, and failed spawns' onErrors; a spawn-time message is re-sent by the spawn on Recover, as before. Held entries go first in the Record, the order they ran. ResumeEffects walks a compound state's ancestors, as StartEffects does. The CHANGELOG says what an older journal and an older durable do, that a settled service is re-armed by a Recover from a later checkpoint (a follow-up), and that a Fire or RunService now fails the Handle on an actor output with no JSON form, as a delivery does. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 26 ++++++--- durable/actor_lifecycle_test.go | 71 ++++++++++++++++++++++++ durable/runner.go | 39 +++++++++++--- durable/service.go | 7 +-- durable/step_rule_test.go | 75 ++++++++++++++++++++++++++ state/CHANGELOG.md | 3 +- state/snapshot.go | 8 +-- state/start_effects_superstate_test.go | 15 ++++-- 8 files changed, 217 insertions(+), 27 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index aef361d2..bd676dd8 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -55,7 +55,8 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **A journal this version writes isn't for an older one.** An actor entry can now say its parent Fire was refused, which an older `durable` fails `Recover` on, or, for an entry with no event, replays as the zero event. An older `durable` also ignores the - recorded ended actors and spawns them again. Don't downgrade a Store this version has + recorded ended actors and spawns them again, and replays a step that records actor + entries as a delivery, skipping its event, settle or tick. Don't downgrade a Store this version has written to. - **A journal an older version wrote replays as it did.** Its actor entries carry no refusal, so `Recover` still fails on one whose parent Fire was refused, and an output @@ -163,16 +164,25 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. failed with no onError never ran, so `Recover` tries it again, as before; one whose onError applied counts as ended, since the journal holds that onError. A journal from before this records no set, and `Recover` spawns every declared actor, as before. -- **A failed spawn's onError is journaled.** When an actor a `Fire`, `RunService`, - `Start` or `Recover` spawned couldn't start and its onError applied, nothing recorded - the onError, so `Recover` either applied it again by retrying the spawn, or, once the - spawn worked, never applied it. A Fire's or settle's onError is now recorded with its - step, and one from `Start`'s or `Recover`'s spawns with the step after, and replay - re-fires each where it ran. +- **A failed spawn's onError, and a settle an absorb drove, are journaled.** When an + actor a `Fire`, `RunService`, `Start` or `Recover` spawned couldn't start and its + onError applied, nothing recorded the onError, so `Recover` either applied it again + by retrying the spawn, or, once the spawn worked, never applied it. Likewise a settle + a Fire's effects drove, such as one from a `SendTo` to a running actor, wasn't + recorded, so `Recover` lost it. These are now recorded with their step, or, for + `Start`'s and `Recover`'s spawns, with the step after, and replay re-fires each where + it ran. An actor output that has no JSON form now fails the Handle here too, as it + does for a delivery. A message a running actor sends as it spawns isn't journaled: + `Recover` spawns the actor again, which sends it again, so it can land after the + steps that followed it live. - **A compound state's services and actors start.** `Start` and `Recover` armed only those declared on the active leaves, so a service or actor on a compound state didn't run while one of its children was active. They come from `state.StartEffects`, which - now covers every active state. + now covers every active state. A journal from before this records no ended actors, + so `Recover` from it also spawns a compound state's actor that had settled, as it + already did for a leaf's. A settled service is re-armed by a `Recover` from a + checkpoint taken after its settle, on a compound or a leaf state; that, and restoring + a checkpoint's timers before the replay walk, is left to a follow-up. - **A parent Fire that middleware denied replays.** Denied before the kernel saw it, it is recorded as refused, and replay meets the same refusal instead of failing `Recover`. - **A panic during a step fails the Handle.** A panic in host code under the step lock, diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go index 523f8831..c46c2121 100644 --- a/durable/actor_lifecycle_test.go +++ b/durable/actor_lifecycle_test.go @@ -437,3 +437,74 @@ func TestRecover_SpawnsASuperstatesActor(t *testing.T) { t.Fatalf("state = %q, want done after the actor finished", got) } } + +// greeter is an actor that sends its parent "hello" as it spawns, then keeps running. +type greeter struct{ sent bool } + +func (g *greeter) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (g *greeter) ChildEffects() []state.Effect { + if g.sent { + return nil + } + g.sent = true + return []state.Effect{state.SendParent{Event: "hello"}} +} +func (g *greeter) Output() any { return nil } + +// TestRecover_AppliesASpawnMessageOnce proves a message a running actor sends its parent +// as it spawns isn't journaled with the step that spawned it: Recover spawns the actor +// again, which sends it again, so journaling it too would apply it twice. +func TestRecover_AppliesASpawnMessageOnce(t *testing.T) { + ctx := context.Background() + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + opts := []durable.Option[string, string, actorCtx]{durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { return &greeter{}, nil }, + })} + for _, initial := range []string{"idle", "greeting"} { + t.Run("from "+initial, func(t *testing.T) { + m := state.ForgeFor[actorCtx]("greet"). + Reducer("noteHello", note("hello")). + Reducer("notePoke", note("poke")). + Actor("greeter"). + State("idle"). + State("greeting").InvokeActor("greeter"). + Initial(initial). + Transition("idle").On("go").GoTo("greeting"). + Transition("greeting").On("hello").GoTo("greeting").Assign("noteHello"). + Transition("greeting").On("poke").GoTo("greeting").Assign("notePoke"). + Quench() + store, id := durable.NewMemStore(), durable.InstanceID("greet") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + if initial == "idle" { + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + hellos := 0 + for _, n := range recovered.Instance().Entity().Notes { + if n == "hello" { + hellos++ + } + } + if hellos != 1 { + t.Fatalf("recovered notes = %v, want the spawn's hello once", recovered.Instance().Entity().Notes) + } + }) + } +} diff --git a/durable/runner.go b/durable/runner.go index 0378bedd..dca41dc0 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -55,7 +55,10 @@ import ( // the actor's onDone / onError, or a message it sends — is journaled as a // JournalActorMessage; on recovery the recorded transition is replayed by re-firing // the parent directly with the recorded done-data, so the actor behavior is never -// re-instantiated. A purely event-driven machine records no Entries. +// re-instantiated. A Fire's or RunService's Record also journals the settles and +// failed spawns' onErrors its absorb drove, replayed after its own work, and the step +// after Start or Recover journals the ones their spawns drove, replayed first. A +// purely event-driven machine records no Entries. type Runner[S comparable, E comparable, C any] struct { machine *state.Machine[S, E, C] store Store @@ -548,6 +551,8 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt } // A parent Fire a starting actor drove (a failed spawn's onError) applied to the // instance after its baseline, so the first step journals it, ahead of its own work. + // One a context's ending refused never applied and isn't journaled; the spawn is + // retried at Recover. startFires := heldFires(actorFires.take()) // The actors that started are seen running, so one later stopped counts as ended. seen := map[string]bool{} @@ -807,9 +812,10 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi if err := refusedByContext(parentFireErrs(fires)...); err != nil { return res, nil, nil, h.fail(fmt.Errorf("durable: firing %q: %w", h.id, err)) } - // The parent Fires the absorb drove, such as a spawned actor's onError, applied - // after the event, so the step journals them, and replay re-fires them after it. - driven, err := recordParentFires(fires, false) + // The parent Fires the absorb drove that settled an actor or routed a failed spawn's + // onError applied after the event, so the step journals them, and replay re-fires + // them after it. + driven, err := recordParentFires(journaledFires(fires), false) if err != nil { return res, nil, nil, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) } @@ -1036,7 +1042,8 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) if err != nil { return fmt.Errorf("durable: recording step %d for %q: %w", step, h.id, err) } - rec.Entries = append(rec.Entries, before...) + // They ran before the step's own work, so they come first. + rec.Entries = append(before, rec.Entries...) } if h.checkpointDue(step) { snap, err := state.MarshalSnapshot(h.inst.Snapshot()) @@ -1070,7 +1077,7 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // replayable, so it isn't journaled, and the spawn is tried again. func heldFires[S comparable](fires []state.ParentFire[S]) []state.ParentFire[S] { var out []state.ParentFire[S] - for _, pf := range fires { + for _, pf := range journaledFires(fires) { if pf.Result.Err == nil || !isContextErr(pf.Result.Err) { out = append(out, pf) } @@ -1078,13 +1085,29 @@ func heldFires[S comparable](fires []state.ParentFire[S]) []state.ParentFire[S] return out } +// journaledFires returns the parent Fires an absorb drove that the journal must hold: +// a settle, after which the actor has ended, and the onError of a spawn that couldn't +// start. A message an actor sends as it spawns isn't one: Recover spawns a running +// actor again, which sends it again. +func journaledFires[S comparable](fires []state.ParentFire[S]) []state.ParentFire[S] { + var out []state.ParentFire[S] + for _, pf := range fires { + if pf.Settle || pf.SpawnFailed { + out = append(out, pf) + } + } + return out +} + // endedActors returns the actors the instance's state declares that ran and have // ended, and remembers them for the next step. A declared actor that isn't running // has ended when it settled (the actor system keeps a settled actor), or when this // step asked the system to spawn it and the latest of those spawns started it (then // something stopped it), or, when this step didn't try to spawn it, when it was -// running or ended at the previous step. So an actor whose spawn failed, at entry or on a re-entry, -// hasn't ended, and Recover tries it again. It is nil with no actor palette. +// running or ended at the previous step. A spawn whose onError applied also counts as +// ended, since the journal holds that onError. So an actor whose spawn failed with no +// onError, at entry or on a re-entry, hasn't ended, and Recover tries it again. It is nil +// with no actor palette. func (h *Handle[S, E, C]) endedActors() *ActorSet { if h.actors == nil { return nil diff --git a/durable/service.go b/durable/service.go index a282161b..a11e6753 100644 --- a/durable/service.go +++ b/durable/service.go @@ -147,9 +147,10 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire *h.svcBuf = append(*h.svcBuf, entry) } - // The parent Fires the absorb drove, such as a spawned actor's onError, applied - // after the settle, so the step journals them, and replay re-fires them after it. - driven, err := recordParentFires(fires, false) + // The parent Fires the absorb drove that settled an actor or routed a failed spawn's + // onError applied after the settle, so the step journals them, and replay re-fires + // them after it. + driven, err := recordParentFires(journaledFires(fires), false) if err != nil { return res, true, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) } diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index 0bbd2eee..55530f91 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -778,3 +778,78 @@ func TestRecover_ReplaysASpawnsOnErrorOnce(t *testing.T) { } }) } + +// TestRecover_RetriesASpawnWhoseLatestOnErrorWasRefused proves the latest spawn attempt +// decides: a failed spawn's onError applies and re-enters the state, the spawn there +// fails too, and the parent refuses that onError, so the actor isn't handled and +// Recover tries it again. +func TestRecover_RetriesASpawnWhoseLatestOnErrorWasRefused(t *testing.T) { + ctx := context.Background() + fail := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "fail") + return c + } + m := state.ForgeFor[stepCtx]("again"). + Guard("firstFailure", func(in state.GuardCtx[stepCtx]) bool { return len(in.Entity.Notes) == 0 }). + Reducer("noteFail", fail). + Actor("spawnChild"). + State("idle"). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("spawning").Reenter().When("firstFailure").Assign("noteFail"). + Quench() + store, id := durable.NewMemStore(), durable.InstanceID("again") + failing := durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnChild": failingSpawn(nil)}) + h, err := durable.NewRunner(m, store, failing).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnChild": finishingChild()})) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ok := recovered.ActorRef(state.ActorID("again", "spawning", 0)); !ok { + t.Fatal("Recover didn't retry the spawn whose latest onError the parent refused") + } +} + +// TestRecover_AfterAStartSpawnRefusedByAContext proves a parent Fire a Start's spawn +// drove that a context's ending refused isn't journaled with the next step: it never +// applied, and replay under a live context would apply it. +func TestRecover_AfterAStartSpawnRefusedByAContext(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("held"). + Actor("spawnFail"). + State("spawning").InvokeActor("spawnFail", state.WithInvokeOnError("spawnFailed")). + State("failed"). + Initial("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed"). + Transition("spawning").On("poke").GoTo("spawning"). + Quench() + turn, cancel := context.WithCancel(ctx) + defer cancel() + // The spawn ends Start's own context, so the parent refuses its onError. + ending := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(cancel)})} + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(nil)})} + store, id := durable.NewMemStore(), durable.InstanceID("held") + h, err := durable.NewRunner(m, store, ending...).Start(turn, id, stepCtx{}, state.WithInitialState("spawning")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + // Recover retried the spawn, and with a live context its onError applied. + if got := recovered.Instance().Current(); got != "failed" { + t.Fatalf("recovered state = %q, want failed", got) + } +} diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 530738da..eec82174 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -54,7 +54,8 @@ counts as an additive (minor) versus breaking (major) change. Use the - **`StartEffects` includes a compound state's invokes.** It looked only at the active leaves, so a service or actor declared on a compound state wasn't started while one of its children was active: not at a durable `Start` or `Recover`, and not for a child - actor's own nested actors. It now reports every active state's, ancestors first. + actor's own nested actors. It now reports every active state's, ancestors first, and + so does `ResumeEffects`. ## [1.0.0] — 2026-06-13 diff --git a/state/snapshot.go b/state/snapshot.go index 4bcbf732..54704570 100644 --- a/state/snapshot.go +++ b/state/snapshot.go @@ -415,10 +415,10 @@ func (i *Instance[S, E, C]) pendingRefs(cfg []S) PendingRefs { // post-1.0 ADDITIVE item, not a v1.0 contract. func (i *Instance[S, E, C]) ResumeEffects() []Effect { var tr Trace - cfg := i.Configuration() - out := i.afterEffectsOnEntry(cfg, &tr) - out = append(out, i.invokeEffectsOnEntry(cfg, &tr)...) - out = append(out, i.actorEffectsOnEntry(cfg, &tr)...) + active := i.activeStates() + out := i.afterEffectsOnEntry(active, &tr) + out = append(out, i.invokeEffectsOnEntry(active, &tr)...) + out = append(out, i.actorEffectsOnEntry(active, &tr)...) return out } diff --git a/state/start_effects_superstate_test.go b/state/start_effects_superstate_test.go index 683e0848..1e5f8054 100644 --- a/state/start_effects_superstate_test.go +++ b/state/start_effects_superstate_test.go @@ -7,9 +7,9 @@ import ( "github.com/stablekernel/crucible/state" ) -// TestStartEffects_IncludesTheSuperstatesInvokes proves StartEffects reports the -// services and actors a compound state declares while one of its children is active, -// the compound state's before its child's. +// TestStartEffects_IncludesTheSuperstatesInvokes proves StartEffects and ResumeEffects +// report the services and actors a compound state declares while one of its children +// is active, the compound state's before its child's. func TestStartEffects_IncludesTheSuperstatesInvokes(t *testing.T) { svc := func(context.Context, state.ServiceCtx[*trec]) (any, error) { return nil, nil } m := state.ForgeFor[*trec]("nest"). @@ -38,4 +38,13 @@ func TestStartEffects_IncludesTheSuperstatesInvokes(t *testing.T) { if len(actors) != 1 || actors[0] != "outerActor" { t.Fatalf("actors = %v, want [outerActor]", actors) } + var resumed []string + for _, eff := range inst.ResumeEffects() { + if e, ok := eff.(state.SpawnActor); ok { + resumed = append(resumed, e.Src.Name) + } + } + if len(resumed) != 1 || resumed[0] != "outerActor" { + t.Fatalf("ResumeEffects actors = %v, want [outerActor]", resumed) + } } From 6dcc04e948ac7463975da2592f3d059b49308ca0 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 13 Nov 2026 09:39:14 -0700 Subject: [PATCH 15/38] style(durable): fix lint: shadowed errs and an unused helper hasActorEntry lost its last caller when failed-spawn onErrors began journaling. Rename the Fire seam's refusal error and reuse the tests' outer err instead of shadowing it. Signed-off-by: Ray Karnes --- durable/actor.go | 12 ------------ durable/actor_lifecycle_test.go | 26 +++++++++++++------------- durable/runner.go | 4 ++-- 3 files changed, 15 insertions(+), 27 deletions(-) diff --git a/durable/actor.go b/durable/actor.go index ef9bc703..278d839d 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -353,15 +353,3 @@ func actorEntries(rec *Record) []state.JournalEntry { } return out } - -// hasActorEntry reports whether a Record carries any recorded actor transition, so -// replay can route it to the actor re-fire path rather than re-firing an external -// event. -func hasActorEntry(rec *Record) bool { - for _, e := range rec.Entries { - if e.Kind == state.JournalActorMessage { - return true - } - } - return false -} diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go index c46c2121..0a75afc9 100644 --- a/durable/actor_lifecycle_test.go +++ b/durable/actor_lifecycle_test.go @@ -65,7 +65,7 @@ func TestRecover_ActorSpawnedAndStoppedInOneStep_StaysEnded(t *testing.T) { if !ok { t.Fatal("no driver") } - if _, err := h.DeliverToActor(ctx, ref, "go"); err != nil { + if _, err = h.DeliverToActor(ctx, ref, "go"); err != nil { t.Fatal(err) } if got := h.Instance().Current(); got != "z" { @@ -82,7 +82,7 @@ func TestRecover_ActorSpawnedAndStoppedInOneStep_StaysEnded(t *testing.T) { t.Error("Recover: child is running, live had it stopped") } // A step on the recovered Handle, then a second Recover. - if _, err := rec.Fire(ctx, "poke"); err != nil { + if _, err = rec.Fire(ctx, "poke"); err != nil { t.Fatal(err) } again, err := durable.Recover(ctx, m, store, id, opts...) @@ -140,10 +140,10 @@ func TestRecover_RetriesAFailedReentrySpawn(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := h.Fire(ctx, "poke"); err != nil { + if _, err = h.Fire(ctx, "poke"); err != nil { t.Fatal(err) } - if _, err := h.Fire(ctx, "re"); err != nil { + if _, err = h.Fire(ctx, "re"); err != nil { t.Fatal(err) } aid := state.ActorID("probe", "working", 0) @@ -173,14 +173,14 @@ func TestRecover_RetriesASpawnThatFailedAtRecover(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := h.Fire(ctx, "poke"); err != nil { + if _, err = h.Fire(ctx, "poke"); err != nil { t.Fatal(err) } r1, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](bad)) if err != nil { t.Fatal(err) } - if _, err := r1.Fire(ctx, "poke"); err != nil { + if _, err = r1.Fire(ctx, "poke"); err != nil { t.Fatal(err) } r2, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) @@ -211,14 +211,14 @@ func TestRecover_RetriesAFailedReentrySpawnOnARecoveredHandle(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := h.Fire(ctx, "poke"); err != nil { + if _, err = h.Fire(ctx, "poke"); err != nil { t.Fatal(err) } r1, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](once)) if err != nil { t.Fatal(err) } - if _, err := r1.Fire(ctx, "re"); err != nil { + if _, err = r1.Fire(ctx, "re"); err != nil { t.Fatal(err) } r2, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, probeCtx](good)) @@ -254,8 +254,8 @@ func TestRecover_RetriesASpawnThatFailedWhenASettleReentered(t *testing.T) { } aid := state.ActorID("probe2", "working", 0) ref, _ := h.ActorRef(aid) - if found, err := h.DeliverToActor(ctx, ref, "finish"); !found || err != nil { - t.Fatalf("deliver: %v %v", found, err) + if found, derr := h.DeliverToActor(ctx, ref, "finish"); !found || derr != nil { + t.Fatalf("deliver: %v %v", found, derr) } if _, ok := h.ActorRef(aid); ok { t.Fatal("setup: respawn should have failed") @@ -319,7 +319,7 @@ func TestRecover_RetriesAnActorWhoseSecondReentrySpawnFailed(t *testing.T) { if !ok { t.Fatal("no child") } - if _, err := h.DeliverToActor(ctx, ref, "go"); err != nil { + if _, err = h.DeliverToActor(ctx, ref, "go"); err != nil { t.Fatal(err) } if got := atomic.LoadInt64(&n); got != 3 { @@ -329,7 +329,7 @@ func TestRecover_RetriesAnActorWhoseSecondReentrySpawnFailed(t *testing.T) { t.Fatal("setup: last respawn should have failed") } if poke { - if _, err := h.Fire(ctx, "poke"); err != nil { + if _, err = h.Fire(ctx, "poke"); err != nil { t.Fatal(err) } } @@ -380,7 +380,7 @@ func TestRecover_RetriesAnActorWhoseLatestSpawnInAStepFailed(t *testing.T) { t.Fatal(err) } ref, _ := h.ActorRef(state.ActorID("flip", "y", 0)) - if _, err := h.DeliverToActor(ctx, ref, "go"); err != nil { + if _, err = h.DeliverToActor(ctx, ref, "go"); err != nil { t.Fatal(err) } cid := state.ActorID("flip", "z", 0) diff --git a/durable/runner.go b/durable/runner.go index dca41dc0..a4f72994 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -809,8 +809,8 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi // where the onError applies. Record nothing. A Fire that drove no Fire a context refused // applied whole, so it records even when ctx ended afterward. fires := h.actorFires.take() - if err := refusedByContext(parentFireErrs(fires)...); err != nil { - return res, nil, nil, h.fail(fmt.Errorf("durable: firing %q: %w", h.id, err)) + if refused := refusedByContext(parentFireErrs(fires)...); refused != nil { + return res, nil, nil, h.fail(fmt.Errorf("durable: firing %q: %w", h.id, refused)) } // The parent Fires the absorb drove that settled an actor or routed a failed spawn's // onError applied after the event, so the step journals them, and replay re-fires From 49fe9eba46172b3e2031c26c449d21b1dad50bb7 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 13 Nov 2026 15:31:57 -0700 Subject: [PATCH 16/38] fix(durable): address review: spawn messages, Start refusals, settled services - Journal every parent Fire an absorb drove, spawn-time messages included, on every path. Recover re-spawns a still-running actor without re-sending its spawn-time messages (state.ActorSystem.AbsorbRespawn), and spawns an actor that never started as new (Record.UnstartedActors). - Start and Recover fail when their context ends or a context refuses a Fire their spawns drove, rather than return a Handle out of step. - A checkpoint records the declared services that aren't in flight, so Recover doesn't re-arm one that already settled. - state.ResumeEffects returns the active leaves' timers only, as before. - DeliverToActor journals each Fire under the actor that drove it, without copying the instance's history. - Skip the actor-set walk on a step that touched no actor. - unmarshalCheckpoint no longer returns an error it can't produce. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 42 ++++- durable/actor.go | 30 +-- durable/actor_lifecycle_test.go | 4 +- durable/actor_sets_internal_test.go | 58 ++++++ durable/checkpoint.go | 25 ++- durable/checkpoint_internal_test.go | 37 ++-- durable/memstore.go | 3 + durable/runner.go | 250 ++++++++++++++++++------- durable/service.go | 8 +- durable/service_test.go | 60 ++++++ durable/spawn_message_test.go | 212 +++++++++++++++++++++ durable/step_rule_test.go | 56 ++---- durable/store.go | 14 +- durable/timetravel.go | 7 +- state/CHANGELOG.md | 9 +- state/actor_respawn_test.go | 81 ++++++++ state/actor_system.go | 34 ++++ state/snapshot.go | 12 +- state/start_effects_superstate_test.go | 39 ++++ 19 files changed, 791 insertions(+), 190 deletions(-) create mode 100644 durable/actor_sets_internal_test.go create mode 100644 durable/spawn_message_test.go create mode 100644 state/actor_respawn_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index bd676dd8..09503722 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -12,6 +12,9 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **`Record.EndedActors` and `ActorSet`** record the declared child-machine actors that ran and have ended, settled or stopped, so `Recover` doesn't spawn them again. A Store must keep an empty set distinct from nil. +- **`Record.UnstartedActors`** records the declared actors that aren't running and + haven't ended, because their spawn failed with no onError, so `Recover` can tell them + from the actors that were running. A Store must keep an empty set distinct from nil. - **Fencing.** `WithFence` on `Store.Append` and `WithCheckpointFence` on `Store.Checkpoint` carry a caller-issued token, and a Store refuses a token lower @@ -56,13 +59,21 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. its parent Fire was refused, which an older `durable` fails `Recover` on, or, for an entry with no event, replays as the zero event. An older `durable` also ignores the recorded ended actors and spawns them again, and replays a step that records actor - entries as a delivery, skipping its event, settle or tick. Don't downgrade a Store this version has + entries as a delivery, skipping its event, settle or tick. It also spawns a running + actor as new, so a message the actor sent its parent as it started applies twice. Don't downgrade a Store this version has written to. - **A journal an older version wrote replays as it did.** Its actor entries carry no refusal, so `Recover` still fails on one whose parent Fire was refused, and an output recorded with a delivery's last Fire still replays into that transition. Only steps this version records get the fixes below. - Requires Go 1.27.4. +- **`Start` fails when a context ends during it.** If ctx ends, or a context's ending + (ctx's, or one middleware derived from it) refuses a parent Fire an initial actor + drove, such as a failed spawn's onError, `Start` returns an error wrapping the + context's error and no Handle. It used to return a Handle whose state lacked that + Fire, while `Recover` would apply it. The baseline is recorded, so `Recover` the + instance. `Recover` likewise fails when a context's ending refuses a parent Fire its + own spawns drove, rather than returning a Handle the journal can't reach. - **A Handle's steps are serialized across goroutines.** `Fire`, `Tick`, `RunService` and `DeliverToActor` hold a lock while they apply to the kernel and record the step, so a host's timer loop no longer loses acknowledged steps. Effects dispatch after the lock @@ -172,17 +183,34 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. recorded, so `Recover` lost it. These are now recorded with their step, or, for `Start`'s and `Recover`'s spawns, with the step after, and replay re-fires each where it ran. An actor output that has no JSON form now fails the Handle here too, as it - does for a delivery. A message a running actor sends as it spawns isn't journaled: - `Recover` spawns the actor again, which sends it again, so it can land after the - steps that followed it live. + does for a delivery. +- **A message an actor sends its parent as it spawns applies once.** A `Fire`, + `RunService`, `Start` or `Recover` didn't journal it, and `Recover` spawned the actor + again to send it again: it landed after the steps that followed it live, or never, if + it had ended the actor. A delivery did journal it, for an actor its onDone or onError + spawned, so `Recover` applied it twice. Every step now journals every parent Fire it + drove, and `Start`'s and `Recover`'s go with the step after, so replay re-fires each + where it ran. `Recover` spawns an actor that was running with `state`'s new + `ActorSystem.AbsorbRespawn`, which keeps such messages from the parent. An actor whose + spawn failed with no onError never ran, so its messages are new: they reach the parent + and are journaled with the next step. A journal from before this records no unstarted + actors, and `Recover` spawns every actor as new, as before. +- **A delivery journals each parent Fire under the actor that drove it,** where it used to + record every one under the actor delivered to. It no longer copies the instance's + history twice per delivery to do it. - **A compound state's services and actors start.** `Start` and `Recover` armed only those declared on the active leaves, so a service or actor on a compound state didn't run while one of its children was active. They come from `state.StartEffects`, which now covers every active state. A journal from before this records no ended actors, so `Recover` from it also spawns a compound state's actor that had settled, as it - already did for a leaf's. A settled service is re-armed by a `Recover` from a - checkpoint taken after its settle, on a compound or a leaf state; that, and restoring - a checkpoint's timers before the replay walk, is left to a follow-up. + already did for a leaf's. Restoring a checkpoint's timers before the replay walk is + left to a follow-up. +- **`Recover` doesn't start a service that settled while its state stayed active.** A + checkpoint taken after such a settle, on a compound state whose onDone went to a child, + or on a leaf state that stayed put, left the service in flight again on recovery, so + `RunService` ran it a second time. A checkpoint now records the declared services that + weren't in flight, and `Recover` doesn't start them. A checkpoint from before this + records none, and `Recover` starts every declared service, as before. - **A parent Fire that middleware denied replays.** Denied before the kernel saw it, it is recorded as refused, and replay meets the same refusal instead of failing `Recover`. - **A panic during a step fails the Handle.** A panic in host code under the step lock, diff --git a/durable/actor.go b/durable/actor.go index 278d839d..a91aad01 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -132,7 +132,6 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef return false, fmt.Errorf("durable: no actor palette wired for %q (supply WithActorPalette)", h.id) } - before := len(h.inst.History()) delivered := h.actors.Deliver(h.stepContext(ctx), ref, event) fires := h.actorFires.take() if !delivered { @@ -148,7 +147,7 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) } - entries, err := recordActorTransitions(ref.ID, h.inst.History()[before:], fires) + entries, err := recordParentFires(fires, false) if err != nil { return true, h.fail(fmt.Errorf("durable: recording actor %q result for %q: %w", ref.ID, h.id, err)) } @@ -194,30 +193,9 @@ func (h *Handle[S, E, C]) drainActors() []state.JournalEntry { return out } -// recordActorTransitions builds the JournalActorMessage entries for the parent Traces -// a delivery appended, one per parent transition the actor system drove, in fire -// order. Each carries its transition's event payload, and whether the live Fire was -// refused. A Fire that settled an actor also carries the actor's outcome, which it -// passed as event data, so replay re-fires the same onDone or onError with it. fires -// are the actor system's own record of those Fires, matching the traces one for one. -func recordActorTransitions[S comparable](id string, traces []state.Trace, fires []state.ParentFire[S]) ([]state.JournalEntry, error) { - if len(fires) != len(traces) { - return nil, fmt.Errorf("the actor system drove %d parent Fires, but the parent recorded %d", len(fires), len(traces)) - } - entries := make([]state.JournalEntry, 0, len(traces)) - for i, tr := range traces { - entry, err := actorEntry(id, tr.EventPayload, fires[i], false) - if err != nil { - return nil, err - } - entries = append(entries, entry) - } - return entries, nil -} - -// recordParentFires builds the JournalActorMessage entries for parent Fires an actor -// system drove outside a delivery, such as a failed spawn's onError, each under the -// actor it came from. before marks Fires that ran before the step's own work. +// recordParentFires builds the JournalActorMessage entries for the parent Fires an +// actor system drove, in fire order, each under the actor it came from. before marks +// Fires that ran before the step's own work. func recordParentFires[S comparable](fires []state.ParentFire[S], before bool) ([]state.JournalEntry, error) { entries := make([]state.JournalEntry, 0, len(fires)) for _, pf := range fires { diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go index 0a75afc9..25eeba0f 100644 --- a/durable/actor_lifecycle_test.go +++ b/durable/actor_lifecycle_test.go @@ -452,8 +452,8 @@ func (g *greeter) ChildEffects() []state.Effect { func (g *greeter) Output() any { return nil } // TestRecover_AppliesASpawnMessageOnce proves a message a running actor sends its parent -// as it spawns isn't journaled with the step that spawned it: Recover spawns the actor -// again, which sends it again, so journaling it too would apply it twice. +// as it spawns is journaled with the step that spawned it, or the step after Start, and +// Recover spawns the actor again without sending it again, so it applies once. func TestRecover_AppliesASpawnMessageOnce(t *testing.T) { ctx := context.Background() note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { diff --git a/durable/actor_sets_internal_test.go b/durable/actor_sets_internal_test.go new file mode 100644 index 00000000..ae519c1f --- /dev/null +++ b/durable/actor_sets_internal_test.go @@ -0,0 +1,58 @@ +package durable + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +type setsCtx struct { + Notes []string `json:"notes"` +} + +// TestActorSets_SkipsAStepThatTouchedNoActor proves a step that spawned nothing and +// changed neither the configuration nor the running actors gets the last actor sets +// back without recomputing them, while a step that moves the configuration recomputes. +func TestActorSets_SkipsAStepThatTouchedNoActor(t *testing.T) { + ctx := context.Background() + child := state.ForgeFor[setsCtx]("child"). + State("working"). + State("done").Final(). + Initial("working"). + Transition("working").On("finish").GoTo("done"). + Quench() + m := state.ForgeFor[setsCtx]("sets"). + Actor("child"). + State("working").InvokeActor("child"). + State("idle"). + Initial("working"). + Transition("working").On("poke").GoTo("working"). + Transition("working").On("leave").GoTo("idle"). + Quench() + palette := map[string]state.ActorBehavior{"child": func(map[string]any) (state.ActorInstance, error) { + return state.NewActor(child.Cast(setsCtx{}, state.WithInitialState("working")), nil), nil + }} + h, err := NewRunner(m, NewMemStore(), WithActorPalette[string, string, setsCtx](palette)). + Start(ctx, "sets", setsCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + ended, unstarted := h.actorSets() + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + again, againUnstarted := h.actorSets() + if again != ended || againUnstarted != unstarted { + t.Fatal("a step that touched no actor recomputed the actor sets") + } + if _, err = h.Fire(ctx, "leave"); err != nil { + t.Fatalf("Fire(leave): %v", err) + } + if moved, _ := h.actorSets(); moved == ended { + t.Fatal("a step that left the actor's state reused the old actor sets") + } +} diff --git a/durable/checkpoint.go b/durable/checkpoint.go index 254401c5..b38b709b 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -89,14 +89,21 @@ type checkpointEnvelope struct { // doesn't spawn them. Nil means none was recorded: no actor palette, a Start // baseline, or an older checkpoint. EndedActors *ActorSet `json:"endedActors,omitempty"` + // UnstartedActors is the set of declared actors that weren't running and hadn't + // ended at the checkpoint (see Record.UnstartedActors). Nil means none was recorded. + UnstartedActors *ActorSet `json:"unstartedActors,omitempty"` + // EndedServices are the invoked services the active states declared that weren't in + // flight at the checkpoint, sorted: each settled in the current activation of the + // state that declares it, so Recover doesn't start it again. None, as in a Start + // baseline or an older checkpoint, means Recover starts every declared service. + EndedServices []string `json:"endedServices,omitempty"` } -// marshalCheckpoint wraps the marshaled kernel snapshot and the armed pending -// timers into a checkpoint envelope's bytes. Timers are emitted in scheduleID -// order so the persisted form is deterministic regardless of the map iteration -// order they were collected in. nextStep is the ordinal that follows the checkpoint. -func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int, ended *ActorSet) ([]byte, error) { - env := checkpointEnvelope{Snapshot: snap, NextStep: nextStep, EndedActors: ended} +// marshalCheckpoint adds the armed pending timers to env, which carries the marshaled +// kernel snapshot and the rest of the checkpoint, and returns the envelope's bytes. +// Timers are emitted in scheduleID order so the persisted form is deterministic +// regardless of the map iteration order they were collected in. +func marshalCheckpoint(env checkpointEnvelope, timers map[string]pendingTimer) ([]byte, error) { if len(timers) > 0 { ids := make([]string, 0, len(timers)) for id := range timers { @@ -130,14 +137,14 @@ func marshalCheckpoint(snap []byte, timers map[string]pendingTimer, nextStep int // are returned as the snapshot with no timers and a zero ordinal, so an older // checkpoint still restores. A checkpoint envelope is distinguished by carrying a // non-empty "snapshot" member. -func unmarshalCheckpoint(b []byte) (checkpointEnvelope, error) { +func unmarshalCheckpoint(b []byte) checkpointEnvelope { var env checkpointEnvelope if err := json.Unmarshal(b, &env); err != nil || len(env.Snapshot) == 0 { // Not an envelope (or an envelope without the wrapped snapshot member): treat // the bytes as a bare kernel snapshot, the pre-timer-survival checkpoint form. - return checkpointEnvelope{Snapshot: b}, nil + return checkpointEnvelope{Snapshot: b} } - return env, nil + return env } // decodeTimerEvent decodes a persisted timer event wire back into the machine's diff --git a/durable/checkpoint_internal_test.go b/durable/checkpoint_internal_test.go index d5ac857e..9459f318 100644 --- a/durable/checkpoint_internal_test.go +++ b/durable/checkpoint_internal_test.go @@ -17,14 +17,11 @@ func TestMarshalCheckpoint_RoundTrip(t *testing.T) { timers := map[string]pendingTimer{ "m:a:after:0": {id: "m:a:after:0", due: due, event: "elapsed"}, } - b, err := marshalCheckpoint(snap, timers, 0, nil) + b, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap}, timers) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } - gotSnap, gotWires, _, err := unmarshalCheckpointParts(b) - if err != nil { - t.Fatalf("unmarshalCheckpoint: %v", err) - } + gotSnap, gotWires, _ := unmarshalCheckpointParts(b) if string(gotSnap) != string(snap) { t.Fatalf("snapshot round-trip: want %s, got %s", snap, gotSnap) } @@ -45,7 +42,7 @@ func TestMarshalCheckpoint_RoundTrip(t *testing.T) { // armed, so an event-driven checkpoint's envelope stays minimal. func TestMarshalCheckpoint_NoTimers(t *testing.T) { snap := []byte(`{"machine":"m"}`) - b, err := marshalCheckpoint(snap, nil, 0, nil) + b, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap}, nil) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } @@ -64,10 +61,7 @@ func TestMarshalCheckpoint_NoTimers(t *testing.T) { // checkpoint still restores. func TestUnmarshalCheckpoint_BareSnapshotFallback(t *testing.T) { bare := []byte(`{"machine":"m","current":"a","configuration":["a"]}`) - snap, wires, _, err := unmarshalCheckpointParts(bare) - if err != nil { - t.Fatalf("unmarshalCheckpoint: %v", err) - } + snap, wires, _ := unmarshalCheckpointParts(bare) if string(snap) != string(bare) { t.Fatalf("bare snapshot not passed through: want %s, got %s", bare, snap) } @@ -81,10 +75,7 @@ func TestUnmarshalCheckpoint_BareSnapshotFallback(t *testing.T) { // any real decode failure when it unmarshals the kernel snapshot). func TestUnmarshalCheckpoint_Garbage(t *testing.T) { garbage := []byte(`not json`) - snap, wires, _, err := unmarshalCheckpointParts(garbage) - if err != nil { - t.Fatalf("unmarshalCheckpoint should tolerate garbage: %v", err) - } + snap, wires, _ := unmarshalCheckpointParts(garbage) if string(snap) != string(garbage) || wires != nil { t.Fatalf("garbage not passed through: snap=%s wires=%+v", snap, wires) } @@ -155,7 +146,7 @@ func TestMarshalCheckpoint_BadEventErrors(t *testing.T) { timers := map[string]pendingTimer{ "bad": {id: "bad", due: time.Unix(0, 1), event: make(chan int)}, } - if _, err := marshalCheckpoint([]byte(`{}`), timers, 0, nil); err == nil { + if _, err := marshalCheckpoint(checkpointEnvelope{Snapshot: []byte(`{}`)}, timers); err == nil { t.Fatal("want encode error for unmarshalable timer event, got nil") } } @@ -178,20 +169,20 @@ func TestTickInstant(t *testing.T) { // TestCheckpoint_NextStepRoundTrips proves the envelope carries the ordinal after // the checkpoint, and that a checkpoint without one reports zero, the old form. func TestCheckpoint_NextStepRoundTrips(t *testing.T) { - b, err := marshalCheckpoint([]byte(`{"v":1}`), nil, 9, nil) + b, err := marshalCheckpoint(checkpointEnvelope{Snapshot: []byte(`{"v":1}`), NextStep: 9}, nil) if err != nil { t.Fatalf("marshalCheckpoint: %v", err) } - if _, _, next, err := unmarshalCheckpointParts(b); err != nil || next != 9 { - t.Fatalf("unmarshalCheckpoint = (%d, %v), want (9, nil)", next, err) + if _, _, next := unmarshalCheckpointParts(b); next != 9 { + t.Fatalf("unmarshalCheckpoint next = %d, want 9", next) } - if _, _, next, err := unmarshalCheckpointParts([]byte(`{"snapshot":{"v":1}}`)); err != nil || next != 0 { - t.Fatalf("old envelope = (%d, %v), want (0, nil)", next, err) + if _, _, next := unmarshalCheckpointParts([]byte(`{"snapshot":{"v":1}}`)); next != 0 { + t.Fatalf("old envelope next = %d, want 0", next) } } // unmarshalCheckpointParts is unmarshalCheckpoint split into the parts these tests check. -func unmarshalCheckpointParts(b []byte) ([]byte, []pendingTimerWire, int, error) { - env, err := unmarshalCheckpoint(b) - return env.Snapshot, env.Timers, env.NextStep, err +func unmarshalCheckpointParts(b []byte) ([]byte, []pendingTimerWire, int) { + env := unmarshalCheckpoint(b) + return env.Snapshot, env.Timers, env.NextStep } diff --git a/durable/memstore.go b/durable/memstore.go index 327989e8..2cd13598 100644 --- a/durable/memstore.go +++ b/durable/memstore.go @@ -409,5 +409,8 @@ func cloneRecord(rec Record) Record { if rec.EndedActors != nil { out.EndedActors = &ActorSet{IDs: append([]string{}, rec.EndedActors.IDs...)} } + if rec.UnstartedActors != nil { + out.UnstartedActors = &ActorSet{IDs: append([]string{}, rec.UnstartedActors.IDs...)} + } return out } diff --git a/durable/runner.go b/durable/runner.go index a4f72994..433d3e94 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -138,9 +138,10 @@ type Handle[S comparable, E comparable, C any] struct { svcBuf *[]state.JournalEntry // recording service-result accumulator, flushed per step actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired - endedAt []string // the ended actors the journal last recorded - endedSet bool // whether endedAt holds a recorded set + ended recordedSet // the ended actors the journal last recorded + unstarted recordedSet // the unstarted actors the journal last recorded seen map[string]bool // declared actors seen running, so a stopped one counts as ended + lastSets *actorSetsAt[S] // what actorSets last computed, and from what pending []state.ParentFire[S] // parent Fires Start's or Recover's spawns drove, journaled with the next step actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step @@ -489,6 +490,11 @@ func (h *Handle[S, E, C]) ID() InstanceID { return h.id } // state.WithInitialState) configure the initial configuration. Starting an // InstanceID that already exists in the Store reports ErrInstanceExists rather // than clobbering its recorded baseline. +// +// If ctx ends during Start, or a context ending (ctx's, or one middleware derived from +// it) refuses a parent Fire an initial actor drove, such as a failed spawn's onError, +// Start returns an error wrapping the context's error and no Handle. The baseline is +// recorded by then, so Recover the instance rather than Start it again. func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opts ...state.CastOption[S]) (*Handle[S, E, C], error) { if _, _, err := r.store.Load(ctx, id); err == nil { return nil, fmt.Errorf("%w: %q", ErrInstanceExists, id) @@ -519,7 +525,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt } // Wrap the baseline snapshot in a checkpoint envelope (no timers armed yet) so // every checkpoint a recover loads carries the same durable envelope shape. - baseEnv, err := marshalCheckpoint(snap, nil, 0, nil) + baseEnv, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap}, nil) if err != nil { return nil, fmt.Errorf("durable: marshaling start checkpoint envelope for %q: %w", id, err) } @@ -549,11 +555,18 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt actorFires.attempt(inst.StartEffects()) actors.Absorb(ctx, inst.StartEffects()) } - // A parent Fire a starting actor drove (a failed spawn's onError) applied to the - // instance after its baseline, so the first step journals it, ahead of its own work. - // One a context's ending refused never applied and isn't journaled; the spawn is - // retried at Recover. - startFires := heldFires(actorFires.take()) + // A parent Fire a starting actor drove (a message it sent as it started, or a failed + // spawn's onError) applied to the instance after its baseline, so the first step + // journals it, ahead of its own work. One a context's ending refused never applied, + // and the Handle would hold state the journal can't reach, so Start fails, as it does + // when ctx ended: Recover starts from the baseline. + startFires, ended := heldFires(actorFires.take()) + if ended == nil { + ended = ctx.Err() + } + if ended != nil { + return nil, fmt.Errorf("durable: starting %q: %w", id, ended) + } // The actors that started are seen running, so one later stopped counts as ended. seen := map[string]bool{} if actors != nil { @@ -812,10 +825,10 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi if refused := refusedByContext(parentFireErrs(fires)...); refused != nil { return res, nil, nil, h.fail(fmt.Errorf("durable: firing %q: %w", h.id, refused)) } - // The parent Fires the absorb drove that settled an actor or routed a failed spawn's - // onError applied after the event, so the step journals them, and replay re-fires - // them after it. - driven, err := recordParentFires(journaledFires(fires), false) + // Every parent Fire the absorb drove (a message an actor sent as it spawned, a + // settle, a failed spawn's onError) applied after the event, so the step journals + // them, and replay re-fires them after it. + driven, err := recordParentFires(fires, false) if err != nil { return res, nil, nil, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) } @@ -1035,7 +1048,7 @@ func (h *Handle[S, E, C]) checkpointDue(step int) bool { // dispatch leaves the effect recoverable from the still-present tail rather than // orphaned behind the compaction. func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) error { - now := h.endedActors() + ended, unstarted := h.actorSets() held := len(h.pending) if held > 0 { before, err := recordParentFires(h.pending, true) @@ -1053,68 +1066,95 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // Wrap the kernel snapshot with the absolute deadlines of the timers armed at // this checkpoint, so a recovery whose compacted tail no longer carries their // arming ScheduleAfter can re-arm them at their recorded instants. - env, err := marshalCheckpoint(snap, h.timers, rec.followingStep(), now) + env, err := marshalCheckpoint(checkpointEnvelope{ + Snapshot: snap, + NextStep: rec.followingStep(), + EndedActors: ended, + UnstartedActors: unstarted, + EndedServices: h.endedServices(), + }, h.timers) if err != nil { return fmt.Errorf("durable: marshaling checkpoint envelope at step %d for %q: %w", step, h.id, err) } rec.Snapshot = env } - if now != nil && (!h.endedSet || !slices.Equal(now.IDs, h.endedAt)) { - rec.EndedActors = now + if h.ended.changedBy(ended) { + rec.EndedActors = ended + } + if h.unstarted.changedBy(unstarted) { + rec.UnstartedActors = unstarted } if _, err := h.runner.store.Append(ctx, h.id, *rec, WithFence(h.runner.cfg.fence)); err != nil { return fmt.Errorf("durable: recording step %d for %q: %w", step, h.id, err) } - if now != nil { - h.endedAt, h.endedSet = now.IDs, true - } + h.ended.note(ended) + h.unstarted.note(unstarted) h.pending = h.pending[held:] return nil } -// heldFires returns the parent Fires a Start's or Recover's spawns drove that applied -// or were refused for good: one a context's ending refused never applied and isn't -// replayable, so it isn't journaled, and the spawn is tried again. -func heldFires[S comparable](fires []state.ParentFire[S]) []state.ParentFire[S] { - var out []state.ParentFire[S] - for _, pf := range journaledFires(fires) { - if pf.Result.Err == nil || !isContextErr(pf.Result.Err) { - out = append(out, pf) - } +// heldFires returns the parent Fires a Start's or Recover's spawns drove, all of which +// the next step journals, or the context error that refused one: that Fire never +// applied, and replaying it under a live context would apply it. +func heldFires[S comparable](fires []state.ParentFire[S]) ([]state.ParentFire[S], error) { + if err := refusedByContext(parentFireErrs(fires)...); err != nil { + return nil, err } - return out + return fires, nil } -// journaledFires returns the parent Fires an absorb drove that the journal must hold: -// a settle, after which the actor has ended, and the onError of a spawn that couldn't -// start. A message an actor sends as it spawns isn't one: Recover spawns a running -// actor again, which sends it again. -func journaledFires[S comparable](fires []state.ParentFire[S]) []state.ParentFire[S] { - var out []state.ParentFire[S] - for _, pf := range fires { - if pf.Settle || pf.SpawnFailed { - out = append(out, pf) - } +// recordedSet is an actor set the journal records when a step changes it. +type recordedSet struct { + ids []string // the set the journal last recorded + set bool // whether ids holds a recorded set +} + +// changedBy reports whether now differs from the set the journal last recorded, so the +// step records it. A nil now records nothing. +func (r *recordedSet) changedBy(now *ActorSet) bool { + return now != nil && (!r.set || !slices.Equal(now.IDs, r.ids)) +} + +// note remembers now as recorded, once the step that carries it is appended. +func (r *recordedSet) note(now *ActorSet) { + if now != nil { + r.ids, r.set = now.IDs, true } - return out } -// endedActors returns the actors the instance's state declares that ran and have -// ended, and remembers them for the next step. A declared actor that isn't running -// has ended when it settled (the actor system keeps a settled actor), or when this -// step asked the system to spawn it and the latest of those spawns started it (then -// something stopped it), or, when this step didn't try to spawn it, when it was -// running or ended at the previous step. A spawn whose onError applied also counts as -// ended, since the journal holds that onError. So an actor whose spawn failed with no -// onError, at entry or on a re-entry, hasn't ended, and Recover tries it again. It is nil -// with no actor palette. -func (h *Handle[S, E, C]) endedActors() *ActorSet { +// actorSetsAt is what actorSets last computed, and the configuration and running +// actors it computed them from. +type actorSetsAt[S comparable] struct { + config []S + running []string + ended, unstarted *ActorSet +} + +// actorSets returns the actors the instance's state declares that ran and have ended, +// and those that aren't running and haven't ended, and remembers them for the next +// step. A declared actor that isn't running has ended when it settled (the actor system +// keeps a settled actor), or when this step asked the system to spawn it and the latest +// of those spawns started it (then something stopped it), or, when this step didn't try +// to spawn it, when it was running or ended at the previous step. A spawn whose onError +// applied also counts as ended, since the journal holds that onError. So an actor whose +// spawn failed with no onError, at entry or on a re-entry, hasn't ended: it's unstarted, +// and Recover tries it again. Both are nil with no actor palette. +// +// A step that noted no spawn and changed neither the configuration nor the running +// actors can't change either set, so it gets the last ones back without a walk of the +// declared actors. +func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { if h.actors == nil { - return nil + return nil, nil } spawned, attempted, failed := h.actorFires.takeLifecycle() running := h.actors.IDs() - ended := []string{} + config := h.inst.Configuration() + if last := h.lastSets; last != nil && len(spawned) == 0 && len(attempted) == 0 && len(failed) == 0 && + slices.Equal(running, last.running) && slices.Equal(config, last.config) { + return last.ended, last.unstarted + } + endedIDs, unstartedIDs := []string{}, []string{} for _, id := range declaredActors(h.inst.StartEffects()) { if slices.Contains(running, id) { continue @@ -1128,15 +1168,38 @@ func (h *Handle[S, E, C]) endedActors() *ActorSet { ran = h.seen[id] } if ran { - ended = append(ended, id) + endedIDs = append(endedIDs, id) + } else { + unstartedIDs = append(unstartedIDs, id) } } - slices.Sort(ended) + slices.Sort(endedIDs) + slices.Sort(unstartedIDs) + unstartedIDs = slices.Compact(unstartedIDs) h.seen = map[string]bool{} - for _, id := range append(running, ended...) { + for _, id := range append(running, endedIDs...) { h.seen[id] = true } - return &ActorSet{IDs: ended} + ended, unstarted = &ActorSet{IDs: endedIDs}, &ActorSet{IDs: unstartedIDs} + h.lastSets = &actorSetsAt[S]{config: config, running: running, ended: ended, unstarted: unstarted} + return ended, unstarted +} + +// endedServices returns the invoked services the active states declare that aren't in +// flight, sorted: each settled while the state that declares it stayed active. It is nil +// with no service registry. +func (h *Handle[S, E, C]) endedServices() []string { + if h.svc == nil { + return nil + } + var ids []string + for _, eff := range h.inst.StartEffects() { + if sv, ok := eff.(state.StartService); ok && !h.svc.HasPending(sv.ID) { + ids = append(ids, sv.ID) + } + } + slices.Sort(ids) + return ids } // declaredActors returns the ids of the actors effects spawn. @@ -1168,12 +1231,43 @@ func spawnsExcept(effects []state.Effect, ended *ActorSet) []state.Effect { return out } +// servicesExcept returns effects without the starts of the services ended names, so +// Recover doesn't start a service that settled while its state stayed active. +func servicesExcept(effects []state.Effect, ended []string) []state.Effect { + if len(ended) == 0 { + return effects + } + out := make([]state.Effect, 0, len(effects)) + for _, eff := range effects { + if sv, ok := eff.(state.StartService); ok && slices.Contains(ended, sv.ID) { + continue + } + out = append(out, eff) + } + return out +} + +// respawn spawns the actors effects declare, in order. With a recorded unstarted set, +// an actor it leaves out was running, and the journal holds every parent Fire its start +// drove, so it spawns without letting its start reach the parent. An unstarted actor, +// or any actor when the journal recorded no set, spawns as new. +func respawn[S comparable, E comparable, C any](ctx context.Context, actors *state.ActorSystem[S, E, C], effects []state.Effect, unstarted *ActorSet) { + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok && unstarted != nil && !slices.Contains(unstarted.IDs, sp.ID) { + actors.AbsorbRespawn(ctx, []state.Effect{eff}) + continue + } + actors.Absorb(ctx, []state.Effect{eff}) + } +} + // Recover reconstructs a durable instance purely from the Store: it loads the // latest checkpoint Snapshot and the journal/effect tail after it, Restores the // snapshot (firing nothing, no IO), and replays the tail's recorded driving // events through the kernel to reach the instance's live state. The returned // Handle continues recording subsequent Fires. Recover reports ErrInstanceNotFound -// for an instance that was never started, and the context's error if ctx ends. +// for an instance that was never started, and the context's error if ctx ends or a +// context's ending refuses a parent Fire an actor it spawned drove. 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) @@ -1195,11 +1289,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // Unwrap the durable checkpoint envelope: the kernel snapshot bytes, the absolute // deadlines of the timers armed at the checkpoint, and the next step ordinal. A bare // (pre-envelope) checkpoint yields the snapshot with no persisted timers. - env, err := unmarshalCheckpoint(snapBytes) + env := unmarshalCheckpoint(snapBytes) kernelSnap, persistedTimers, checkpointNext := env.Snapshot, env.Timers, env.NextStep - if err != nil { - return nil, fmt.Errorf("durable: unmarshaling checkpoint envelope for %q: %w", id, err) - } snap, err := state.UnmarshalSnapshot[S, E, C](kernelSnap) if err != nil { @@ -1222,11 +1313,13 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // Install the invoked-service host driver and arm the restored configuration's // services, so a service in flight at the checkpoint (or armed by a replayed - // step) can be re-settled from its recorded outcome without re-running it. + // step) can be re-settled from its recorded outcome without re-running it. A + // service that had settled by the checkpoint while its state stayed active isn't + // armed: it would run again. svcBuf := make([]state.JournalEntry, 0) svc := r.newServiceRunner(inst) if svc != nil { - svc.Absorb(ctx, inst.StartEffects()) + svc.Absorb(ctx, servicesExcept(inst.StartEffects(), env.EndedServices)) } // Build the child-machine actor host driver, but DO NOT spawn the restored @@ -1248,6 +1341,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // the checkpoint's, then each tail Record's that records one. Nil means none was // recorded, so Recover spawns every actor the configuration declares. ended := env.EndedActors + // unstarted is the latest recorded set of the declared actors that weren't running + // and hadn't ended, recorded alongside ended. Nil means none was recorded. + unstarted := env.UnstartedActors for i := range tail { // A canceled context can stop a replayed settle or tick with no error, leaving @@ -1263,6 +1359,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S if rec.EndedActors != nil { ended = rec.EndedActors } + if rec.UnstartedActors != nil { + unstarted = rec.UnstartedActors + } now, haveNow := tickInstant(rec.Entries) // Mirror the step into the armed table so it tracks the still-pending set, with // deadlines drawn from the step's recorded clock read, not the live wall clock: @@ -1303,24 +1402,33 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // so a subsequent DeliverToActor finds them — without re-instantiating an actor // the recorded run already settled, which replay reconstructed by re-firing the // parent rather than re-running behavior. + // + // An actor that was running sends the parent nothing as it spawns again: the journal + // holds what its start drove. if actors != nil { spawns := spawnsExcept(inst.StartEffects(), ended) actorFires.attempt(spawns) - actors.Absorb(ctx, spawns) + respawn(ctx, actors, spawns, unstarted) + } + // A parent Fire a newly started actor drove (a message it sent as it started, or a + // failed spawn's onError) applied to the instance past its journal, so the next step + // journals it, ahead of its own work. One a context's ending refused never applied, + // and the Handle would hold state the journal can't reach, so Recover fails. + recoverFires, refused := heldFires(actorFires.take()) + if refused != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, refused) } - // A parent Fire a re-spawned actor drove (a failed spawn's onError) applied to the - // instance past its journal, so the next step journals it, ahead of its own work. - recoverFires := heldFires(actorFires.take()) // The journal's ended actors stay ended, and seen, so the next step records a set // only when it changes them. seen := map[string]bool{} - var endedAt []string + var endedRec, unstartedRec recordedSet if actors != nil { for _, id := range actors.IDs() { seen[id] = true } + endedRec.note(ended) + unstartedRec.note(unstarted) if ended != nil { - endedAt = ended.IDs for _, id := range ended.IDs { seen[id] = true } @@ -1392,8 +1500,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S actors: actors, actorBuf: &actorBuf, actorFires: actorFires, - endedAt: endedAt, - endedSet: actors != nil && ended != nil, + ended: endedRec, + unstarted: unstartedRec, seen: seen, pending: recoverFires, lock: make(chan struct{}, 1), diff --git a/durable/service.go b/durable/service.go index a11e6753..6d74e4c3 100644 --- a/durable/service.go +++ b/durable/service.go @@ -147,10 +147,10 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire *h.svcBuf = append(*h.svcBuf, entry) } - // The parent Fires the absorb drove that settled an actor or routed a failed spawn's - // onError applied after the settle, so the step journals them, and replay re-fires - // them after it. - driven, err := recordParentFires(journaledFires(fires), false) + // Every parent Fire the absorb drove (a message an actor sent as it spawned, a + // settle, a failed spawn's onError) applied after the settle, so the step journals + // them, and replay re-fires them after it. + driven, err := recordParentFires(fires, false) if err != nil { return res, true, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) } diff --git a/durable/service_test.go b/durable/service_test.go index 45e3be3b..a13a346f 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -832,3 +832,63 @@ func TestService_RefusedByADerivedContext_RecordsNothing(t *testing.T) { t.Fatalf("journal grew from %d to %d records, want nothing recorded", before, after) } } + +// TestRecover_DoesNotRearmASuperstatesSettledService proves a service a compound state +// declares, which settled into one of the compound's children, isn't in flight after +// Recover, so RunService doesn't run it again: not from the journal, and not from a +// checkpoint taken after the settle, where the compound is still active. +func TestRecover_DoesNotRearmASuperstatesSettledService(t *testing.T) { + ctx := context.Background() + for _, every := range []int{0, 1} { + t.Run(fmt.Sprintf("every=%d", every), func(t *testing.T) { + var runs int64 + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { + atomic.AddInt64(&runs, 1) + return "ok", nil + } + m := state.ForgeFor[stepCtx]("nestSvc"). + Service("fetch", fetch). + SuperState("outer").Invoke("fetch", state.WithInvokeOnDone("fetched")). + SubState("a"). + SubState("b"). + Initial("a"). + EndSuperState(). + Initial("outer"). + Transition("a").On("fetched").GoTo("b"). + Transition("b").On("poke").GoTo("b"). + Quench() + opts := []stepOption{durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch))} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("nest-svc") + svcID := state.InvokeID("nestSvc", "outer", 0) + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("a")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, ran, err := h.RunService(ctx, svcID); err != nil || !ran { + t.Fatalf("RunService = %v, %v", ran, err) + } + if got := h.Instance().Current(); got != "b" { + t.Fatalf("state = %q, want b after the settle", got) + } + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + if _, ran, runErr := recovered.RunService(ctx, svcID); runErr != nil || ran { + t.Fatalf("RunService after Recover %d = %v, %v, want the settled service not in flight", round, ran, runErr) + } + if n := atomic.LoadInt64(&runs); n != 1 { + t.Fatalf("the service ran %d times, want once", n) + } + // A step on the recovered Handle checkpoints again, from its own view. + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } + }) + } +} diff --git a/durable/spawn_message_test.go b/durable/spawn_message_test.go new file mode 100644 index 00000000..c433a7aa --- /dev/null +++ b/durable/spawn_message_test.go @@ -0,0 +1,212 @@ +package durable_test + +// The Recover tests for the messages an actor sends its parent as it spawns: every step +// and every Start or Recover journals them, and Recover spawns a running actor again +// without sending them again, so each applies exactly once. + +import ( + "context" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +type greetOption = durable.Option[string, string, actorCtx] + +// greetMachine spawns a greeter in "greeting", entered by "go" from idle, by the +// onDone of the finisher that "working" runs, or by the onDone of the service that +// "loading" invokes. The greeter's hello is noted and, with +// leave, moves to "greeted", which stops the greeter; without it, the greeter keeps +// running. +func greetMachine(leave bool) *state.Machine[string, string, actorCtx] { + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + target := "greeting" + if leave { + target = "greeted" + } + return state.ForgeFor[actorCtx]("greet"). + Service("fetch", fetchOK). + Reducer("noteHello", note("hello")). + Reducer("notePoke", note("poke")). + Actor("greeter"). + Actor("spawnChild"). + State("idle"). + State("working").InvokeActor("spawnChild", state.WithInvokeOnDone("childDone")). + State("loading").Invoke("fetch", state.WithInvokeOnDone("fetched")). + State("greeting").InvokeActor("greeter"). + State("greeted"). + Initial("idle"). + Transition("idle").On("go").GoTo("greeting"). + Transition("working").On("childDone").GoTo("greeting"). + Transition("loading").On("fetched").GoTo("greeting"). + Transition("greeting").On("hello").GoTo(target).Assign("noteHello"). + Transition("greeting").On("poke").GoTo("greeting").Assign("notePoke"). + Transition("greeted").On("poke").GoTo("greeted").Assign("notePoke"). + Quench() +} + +// fetchOK is a service that succeeds. +func fetchOK(context.Context, state.ServiceCtx[actorCtx]) (any, error) { return "ok", nil } + +// greetPalette binds a greeter, or one that can't start, and the finisher. +func greetPalette(greeterStarts bool) greetOption { + var runs int64 + greeter := func(map[string]any) (state.ActorInstance, error) { return &greeter{}, nil } + if !greeterStarts { + greeter = failingSpawn(nil) + } + return durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "greeter": greeter, + "spawnChild": counterChild(&runs), + }) +} + +// wantHellos fails unless the instance's notes hold hello exactly once. +func wantHellos(t *testing.T, what string, h *durable.Handle[string, string, actorCtx]) { + t.Helper() + hellos := 0 + for _, n := range h.Instance().Entity().Notes { + if n == "hello" { + hellos++ + } + } + if hellos != 1 { + t.Fatalf("%s: notes = %v, want the spawn's hello once", what, h.Instance().Entity().Notes) + } +} + +// TestRecover_AppliesEachSpawnMessageOnce proves the message a greeter sends its parent +// as it spawns, by Start, by a Fire, or by the onDone a delivery or a service settle +// drove, is journaled and applied exactly once across repeated Recovers, whether the +// greeter keeps running (Recover spawns it again without the message) or the message +// ends it (Recover doesn't spawn it, and the journal alone holds the message), with and +// without checkpoints. +func TestRecover_AppliesEachSpawnMessageOnce(t *testing.T) { + ctx := context.Background() + for _, leave := range []bool{false, true} { + for _, every := range []int{0, 1} { + for _, by := range []string{"Start", "Fire", "onDone", "RunService"} { + t.Run(fmt.Sprintf("%s/leave=%v/every=%d", by, leave, every), func(t *testing.T) { + m := greetMachine(leave) + opts := []greetOption{greetPalette(true), durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("fetch", fetchOK))} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, actorCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("greet") + initial := map[string]string{"Start": "greeting", "Fire": "idle", "onDone": "working", "RunService": "loading"}[by] + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + switch by { + case "Fire": + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + case "onDone": + if found, deliverErr := h.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("greet", "working", 0)}, "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActor = %v, %v", found, deliverErr) + } + case "RunService": + if _, ran, runErr := h.RunService(ctx, state.InvokeID("greet", "loading", 0)); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v", ran, runErr) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + wantHellos(t, "live", h) + liveState := h.Instance().Current() + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d", round), recovered) + if got := recovered.Instance().Current(); got != liveState { + t.Fatalf("Recover %d state = %q, want the live %q", round, got, liveState) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } + }) + } + } + } +} + +// TestRecover_AnUnstartedActorsSpawnMessageApplies proves an actor whose spawn failed +// with no onError, so it never ran, sends its spawn message live when Recover retries +// the spawn, and the next step journals it: each Recover before that step applies it +// live once, and one after it replays it once without sending it again. +func TestRecover_AnUnstartedActorsSpawnMessageApplies(t *testing.T) { + ctx := context.Background() + m := greetMachine(false) + store, id := durable.NewMemStore(), durable.InstanceID("unstarted") + h, err := durable.NewRunner(m, store, greetPalette(false)).Start(ctx, id, actorCtx{}, state.WithInitialState("greeting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if notes := h.Instance().Entity().Notes; len(notes) != 1 { + t.Fatalf("live notes = %v, want only the poke, since the greeter never started", notes) + } + var recovered *durable.Handle[string, string, actorCtx] + for round := 1; round <= 2; round++ { + if recovered, err = durable.Recover(ctx, m, store, id, greetPalette(true)); err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d, before a step", round), recovered) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + again, err := durable.Recover(ctx, m, store, id, greetPalette(true)) + if err != nil { + t.Fatalf("Recover after the step: %v", err) + } + wantHellos(t, "Recover after the step", again) +} + +// TestDeliverToActor_JournalsEachFireUnderItsActor proves a delivery journals each +// parent Fire it drove under the actor that drove it: the finisher's onDone under the +// finisher, and the hello of the greeter that onDone spawned under the greeter. +func TestDeliverToActor_JournalsEachFireUnderItsActor(t *testing.T) { + ctx := context.Background() + store, id := durable.NewMemStore(), durable.InstanceID("correlate") + h, err := durable.NewRunner(greetMachine(false), store, greetPalette(true)).Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + finisher := state.ActorID("greet", "working", 0) + if found, deliverErr := h.DeliverToActor(ctx, state.ActorRef{ID: finisher}, "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActor = %v, %v", found, deliverErr) + } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + var got []string + for _, rec := range tail { + for _, e := range rec.Entries { + if e.Kind == state.JournalActorMessage { + got = append(got, e.CorrelationID) + } + } + } + want := fmt.Sprint([]string{finisher, state.ActorID("greet", "greeting", 0)}) + if fmt.Sprint(got) != want { + t.Fatalf("journaled actor entries under %v, want %s", got, want) + } +} diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index 55530f91..b828df63 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -262,36 +262,22 @@ func spawnAtStartMachine() stepMachine { Quench() } -// TestStartAndRecover_SpawnRefusal_DoesNotFailTheNextStep proves a parent Fire -// refused while Start or Recover spawned the resume point's actors isn't charged to -// the next step, which records normally. -func TestStartAndRecover_SpawnRefusal_DoesNotFailTheNextStep(t *testing.T) { +// TestStartAndRecover_SpawnRefusal_Fails proves a parent Fire a context refused while +// Start or Recover spawned the resume point's actors fails the call: it never applied, +// so the Handle would hold state the journal can't reach. +func TestStartAndRecover_SpawnRefusal_Fails(t *testing.T) { ctx := context.Background() m := spawnAtStartMachine() opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(nil)})} - t.Run("after Start", func(t *testing.T) { - store := durable.NewMemStore() - h, err := durable.NewRunner(m, store, opts...).Start(ctx, "started", stepCtx{}, state.WithInitialState("spawning")) - if err != nil { - t.Fatalf("Start: %v", err) - } - if _, err = h.Fire(ctx, "poke"); err != nil { - t.Fatalf("Fire(poke): %v", err) - } - }) - t.Run("after Recover", func(t *testing.T) { - store := durable.NewMemStore() - if _, err := durable.NewRunner(m, store, opts...).Start(ctx, "recovered", stepCtx{}, state.WithInitialState("spawning")); err != nil { - t.Fatalf("Start: %v", err) - } - h, err := durable.Recover(ctx, m, store, "recovered", opts...) - if err != nil { - t.Fatalf("Recover: %v", err) - } - if _, err = h.Fire(ctx, "poke"); err != nil { - t.Fatalf("Fire(poke): %v", err) - } - }) + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store, opts...).Start(ctx, "refused", stepCtx{}, state.WithInitialState("spawning")) + if h != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Start = Handle %v, %v, want no Handle and context.Canceled", h != nil, err) + } + h, err = durable.Recover(ctx, m, store, "refused", opts...) + if h != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Recover = Handle %v, %v, want no Handle and context.Canceled", h != nil, err) + } } // TestFire_ContextEndedAfterACleanApply_Records proves a Fire that drove nothing @@ -818,10 +804,11 @@ func TestRecover_RetriesASpawnWhoseLatestOnErrorWasRefused(t *testing.T) { } } -// TestRecover_AfterAStartSpawnRefusedByAContext proves a parent Fire a Start's spawn -// drove that a context's ending refused isn't journaled with the next step: it never -// applied, and replay under a live context would apply it. -func TestRecover_AfterAStartSpawnRefusedByAContext(t *testing.T) { +// TestStart_FailsWhenItsContextEndsDuringASpawn proves Start returns no Handle when its +// context ends while an initial actor's spawn fails, so the parent refuses its onError: +// live never applied it. Recover starts from the baseline, retries the spawn, and with +// a live context the onError applies. +func TestStart_FailsWhenItsContextEndsDuringASpawn(t *testing.T) { ctx := context.Background() m := state.ForgeFor[stepCtx]("held"). Actor("spawnFail"). @@ -838,11 +825,8 @@ func TestRecover_AfterAStartSpawnRefusedByAContext(t *testing.T) { opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnFail": failingSpawn(nil)})} store, id := durable.NewMemStore(), durable.InstanceID("held") h, err := durable.NewRunner(m, store, ending...).Start(turn, id, stepCtx{}, state.WithInitialState("spawning")) - if err != nil { - t.Fatalf("Start: %v", err) - } - if _, err = h.Fire(ctx, "poke"); err != nil { - t.Fatalf("Fire(poke): %v", err) + if h != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Start = Handle %v, %v, want no Handle and context.Canceled", h != nil, err) } recovered, err := durable.Recover(ctx, m, store, id, opts...) if err != nil { diff --git a/durable/store.go b/durable/store.go index 9d750631..afccb18a 100644 --- a/durable/store.go +++ b/durable/store.go @@ -93,6 +93,17 @@ type Record struct { // machine with no actor palette, and on a Record from before this field. An empty // set is not nil: a Store must keep it, though it treats other empty fields as nil. EndedActors *ActorSet `json:",omitempty"` + + // UnstartedActors, when set, holds the child-machine actors the instance's state + // declared once this step ended that aren't running and haven't ended: their latest + // spawn failed with no onError to route to. Recover spawns them as new, so the + // messages they send the parent as they start apply and are journaled. A declared + // actor in neither set was running, and the journal holds every parent Fire its start + // drove, so Recover spawns it again without letting those reach the parent. It's + // recorded as EndedActors is: with the first step after Start, then when a step + // changes it, and an empty set is not nil. When the journal holds none, as on a + // Record from before this field, Recover lets every spawn reach the parent. + UnstartedActors *ActorSet `json:",omitempty"` } // ActorSet is a set of child-machine actor ids at a point in a durable instance's @@ -136,7 +147,8 @@ func (r *Record) followingStep() int { // order, and a different Record there is still a conflict. Two Records are the // same when every field matches, with a nil and an empty field counting as equal, // except EventDataError, where nil means no error and an empty message is an error, -// and EndedActors, where nil means none recorded and an empty set means none ended. +// and EndedActors and UnstartedActors, where nil means none recorded and an empty set +// means none. // An Append carrying WithIdempotencyKey (a backend reads it with // AppendIdempotencyKey) dedups on that key alone, so the caller vouches for the // Record: no comparison is made. Keys starting "step:" are reserved for the Store's diff --git a/durable/timetravel.go b/durable/timetravel.go index 5525f0b5..3a23ed5b 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -203,12 +203,7 @@ func restoreBaseline[S comparable, E comparable, C any]( baseline []byte, repClock state.Clock, ) (*state.Instance[S, E, C], error) { - env, err := unmarshalCheckpoint(baseline) - kernelSnap := env.Snapshot - if err != nil { - return nil, fmt.Errorf("unmarshaling baseline envelope: %w", err) - } - snap, err := state.UnmarshalSnapshot[S, E, C](kernelSnap) + snap, err := state.UnmarshalSnapshot[S, E, C](unmarshalCheckpoint(baseline).Snapshot) if err != nil { return nil, fmt.Errorf("unmarshaling baseline snapshot: %w", err) } diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index eec82174..d79897df 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -19,6 +19,11 @@ counts as an additive (minor) versus breaking (major) change. Use the the onError of a spawn that couldn't start), so a host that records a delivery or spawn can tell a parent transition refused because its context ended from one that applied, and which Fire carried the actor's output. It's additive, within v1.1.0. +- **`ActorSystem.AbsorbRespawn`** is `Absorb` for actors a host spawns again after + rebuilding the parent from a record that already holds the messages their earlier + start sent it: an actor it spawns starts as under `Absorb`, but no message reaches the + parent while it starts. The durable runner's `Recover` uses it for the actors that were + running. It's additive, within v1.1.0. - **`FireEventData`** reports the payload a `WithEventData` option carries, so a host that records a Fire can persist it. It's additive, so the next release is v1.1.0. - **Callbacks get the step's context.** `GuardCtx`, `ActionCtx` and `AssignCtx` have a new @@ -55,7 +60,9 @@ counts as an additive (minor) versus breaking (major) change. Use the leaves, so a service or actor declared on a compound state wasn't started while one of its children was active: not at a durable `Start` or `Recover`, and not for a child actor's own nested actors. It now reports every active state's, ancestors first, and - so does `ResumeEffects`. + so does `ResumeEffects` for services and actors. `ResumeEffects` still re-arms only the + active leaves' `after` timers: a compound state's timer may already have fired into + one of its children, and the snapshot can't say. ## [1.0.0] — 2026-06-13 diff --git a/state/actor_respawn_test.go b/state/actor_respawn_test.go new file mode 100644 index 00000000..9c1ccaa4 --- /dev/null +++ b/state/actor_respawn_test.go @@ -0,0 +1,81 @@ +package state_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// startGreeter is an actor that sends its parent "hello" from its initial entry, then +// keeps running. +type startGreeter struct{ sent bool } + +func (g *startGreeter) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (g *startGreeter) ChildEffects() []state.Effect { + if g.sent { + return nil + } + g.sent = true + return []state.Effect{state.SendParent{Event: "hello"}} +} +func (g *startGreeter) Output() any { return nil } + +// TestActorSystem_AbsorbRespawn_DropsStartMessages proves an actor AbsorbRespawn spawns +// runs, but the message it sends the parent as it starts doesn't reach the parent, as it +// does under Absorb, while a spawn that can't start still routes its onError. +func TestActorSystem_AbsorbRespawn_DropsStartMessages(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("respawn"). + Actor("greeter"). + Actor("broken"). + State("greeting").InvokeActor("greeter").InvokeActor("broken", state.WithInvokeOnError("brokenFailed")). + State("hellod"). + State("failed"). + Initial("greeting"). + Transition("greeting").On("hello").GoTo("hellod"). + Transition("greeting").On("brokenFailed").GoTo("failed"). + Quench() + behaviors := func(sys *state.ActorSystem[string, string, *trec], broken bool) { + sys.Register("greeter", func(map[string]any) (state.ActorInstance, error) { return &startGreeter{}, nil }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { + if broken { + return nil, errors.New("can't start") + } + return &startGreeter{sent: true}, nil + }) + } + + live := m.Cast(&trec{}, state.WithInitialState("greeting")) + liveSys := state.NewActorSystem(live) + behaviors(liveSys, false) + liveSys.Absorb(ctx, live.StartEffects()) + if got := live.Current(); got != "hellod" { + t.Fatalf("Absorb left the parent in %q, want hellod from the greeter's start", got) + } + + resumed := m.Cast(&trec{}, state.WithInitialState("greeting")) + var seen []state.ParentFire[string] + sys := state.NewActorSystem(resumed). + WithParentFireObserver(func(pf state.ParentFire[string]) { seen = append(seen, pf) }) + behaviors(sys, false) + sys.AbsorbRespawn(ctx, resumed.StartEffects()) + if got := resumed.Current(); got != "greeting" { + t.Fatalf("AbsorbRespawn left the parent in %q, want greeting: the start message should be dropped", got) + } + if len(seen) != 0 { + t.Fatalf("observed %d parent Fires, want none", len(seen)) + } + if !sys.IsRunning(state.ActorID("respawn", "greeting", 0)) { + t.Fatal("AbsorbRespawn didn't spawn the greeter") + } + + failing := m.Cast(&trec{}, state.WithInitialState("greeting")) + failSys := state.NewActorSystem(failing) + behaviors(failSys, true) + failSys.AbsorbRespawn(ctx, []state.Effect{failing.StartEffects()[1]}) + if got := failing.Current(); got != "failed" { + t.Fatalf("AbsorbRespawn of a spawn that can't start left the parent in %q, want failed by its onError", got) + } +} diff --git a/state/actor_system.go b/state/actor_system.go index b63e5db7..60ecff97 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -294,6 +294,37 @@ func (s *ActorSystem[S, E, C]) AbsorbFor(ctx context.Context, event any, effects s.absorb(ctx, effects, event) } +// AbsorbRespawn is Absorb for actors a host spawns again after rebuilding the parent +// from a record that already holds the messages their earlier start sent it, as the +// durable runner's Recover does for the actors that were running. Each actor it spawns +// starts as under Absorb, but no message reaches the parent while it starts: not one it +// sends the parent from its initial entry, nor one another actor sends the parent then, +// on receiving a message from it. Such a message is dropped without a parent Fire, so +// WithParentFireObserver doesn't see it. A spawn that can't start still routes its +// onError, and a settle its onDone or onError, since those aren't messages the earlier +// start sent. Its other effects absorb as under Absorb. +func (s *ActorSystem[S, E, C]) AbsorbRespawn(ctx context.Context, effects []Effect) { + quiet := context.WithValue(ctx, respawnKey{}, true) + for _, eff := range effects { + if e, ok := eff.(SpawnActor); ok { + s.spawn(quiet, e) + continue + } + s.absorb(ctx, []Effect{eff}, nil) + } +} + +// respawnKey marks the context of an AbsorbRespawn spawn, under which no message +// reaches the parent. +type respawnKey struct{} + +// respawning reports whether ctx is an AbsorbRespawn spawn's, so a message to the +// parent is dropped. +func respawning(ctx context.Context) bool { + quiet, _ := ctx.Value(respawnKey{}).(bool) + return quiet +} + // absorb scans effects emitted by the parent instance while handling curEvent, // spawning/stopping actors and routing the parent's outbound messages (the parent // is the sender). curEvent is nil for the plain Absorb path (a parent ForwardEvent @@ -647,6 +678,9 @@ func (s *ActorSystem[S, E, C]) resolveTarget(targetID, systemID string) (string, // drains it. This is the single path every routed message flows through, so parent // and child delivery share their sender bookkeeping. func (s *ActorSystem[S, E, C]) dispatch(ctx context.Context, targetID string, event any, senderID string) { + if targetID == parentActorID && respawning(ctx) { + return + } s.inspectMessage(senderID, targetID, MessageSent, event) if targetID == parentActorID { s.fireParentFrom(ctx, event, senderID) diff --git a/state/snapshot.go b/state/snapshot.go index 54704570..444baaae 100644 --- a/state/snapshot.go +++ b/state/snapshot.go @@ -388,9 +388,11 @@ func (i *Instance[S, E, C]) pendingRefs(cfg []S) PendingRefs { // ResumeEffects returns the re-arm effects a host absorbs after Restore to // re-establish the instance's pending timers, invoked services, and spawned -// actors for its restored configuration: a ScheduleAfter per pending delayed -// transition, a StartService per invoked service, and a SpawnActor per -// child-machine actor invocation active in the configuration. It is the restore +// actors for its restored configuration: a ScheduleAfter per delayed transition of +// an active leaf state, and a StartService per invoked service and a SpawnActor per +// child-machine actor invocation of every active state, a compound state's included. +// A compound state's own `after` timers aren't re-armed, since the snapshot can't say +// whether one already fired. It is the restore // twin of StartEffects (which arms an initial Cast configuration) extended with // the delayed-timer effects, so a restored instance // re-establishes its invoked/spawned children. Like StartEffects it is a pure @@ -415,8 +417,10 @@ func (i *Instance[S, E, C]) pendingRefs(cfg []S) PendingRefs { // post-1.0 ADDITIVE item, not a v1.0 contract. func (i *Instance[S, E, C]) ResumeEffects() []Effect { var tr Trace + // Timers come from the active leaves only: a compound state's `after` timer may + // already have fired into one of its children, and re-arming it would fire it again. + out := i.afterEffectsOnEntry(i.Configuration(), &tr) active := i.activeStates() - out := i.afterEffectsOnEntry(active, &tr) out = append(out, i.invokeEffectsOnEntry(active, &tr)...) out = append(out, i.actorEffectsOnEntry(active, &tr)...) return out diff --git a/state/start_effects_superstate_test.go b/state/start_effects_superstate_test.go index 1e5f8054..9859e9bc 100644 --- a/state/start_effects_superstate_test.go +++ b/state/start_effects_superstate_test.go @@ -3,6 +3,7 @@ package state_test import ( "context" "testing" + "time" "github.com/stablekernel/crucible/state" ) @@ -48,3 +49,41 @@ func TestStartEffects_IncludesTheSuperstatesInvokes(t *testing.T) { t.Fatalf("ResumeEffects actors = %v, want [outerActor]", resumed) } } + +// TestResumeEffects_DoesNotRearmASuperstatesTimer proves ResumeEffects re-arms an +// active leaf's `after` timer but not a compound state's: here the compound's timer +// already fired into one of its children, so re-arming it after Restore would fire it +// a second time. +func TestResumeEffects_DoesNotRearmASuperstatesTimer(t *testing.T) { + m := state.ForgeFor[*trec]("nestTimer"). + SuperState("outer"). + SubState("a"). + SubState("b"). + Initial("a"). + EndSuperState(). + State("done"). + Initial("outer"). + Transition("outer").After(time.Second).On("elapsed").GoTo("b"). + Transition("b").After(time.Minute).On("stale").GoTo("done"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("a")) + if res := inst.Fire(context.Background(), "elapsed"); res.Err != nil { + t.Fatalf("Fire(elapsed): %v", res.Err) + } + if got := inst.Current(); got != "b" { + t.Fatalf("state = %q, want b", got) + } + restored, err := m.Restore(inst.Snapshot()) + if err != nil { + t.Fatalf("Restore: %v", err) + } + var timers []any + for _, eff := range restored.ResumeEffects() { + if e, ok := eff.(state.ScheduleAfter); ok { + timers = append(timers, e.Event) + } + } + if len(timers) != 1 || timers[0] != "stale" { + t.Fatalf("ResumeEffects timers = %v, want only b's [stale]", timers) + } +} From e77ff5b882e88e9fbeeeab1a5ad913fdef89ec10 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 13 Nov 2026 16:20:55 -0700 Subject: [PATCH 17/38] fix(durable): spawn running actors before retried ones on Recover Recover now spawns the actors that were running before the actors whose spawn it retries. A retried actor's start message can enter a state that spawns a running actor; spawned second, that actor's start reached the parent again and its journaled message applied twice. EndedActors lists each actor id once, as UnstartedActors already does. A test pins that Recover fails when its context ends after replay. Signed-off-by: Ray Karnes --- durable/actor_sets_internal_test.go | 45 +++++++++++++++ durable/runner.go | 16 ++++-- durable/spawn_message_test.go | 89 +++++++++++++++++++++++++++++ durable/step_rule_test.go | 37 ++++++++++++ 4 files changed, 183 insertions(+), 4 deletions(-) diff --git a/durable/actor_sets_internal_test.go b/durable/actor_sets_internal_test.go index ae519c1f..1dc5707f 100644 --- a/durable/actor_sets_internal_test.go +++ b/durable/actor_sets_internal_test.go @@ -56,3 +56,48 @@ func TestActorSets_SkipsAStepThatTouchedNoActor(t *testing.T) { t.Fatal("a step that left the actor's state reused the old actor sets") } } + +// TestActorSets_ListsAnEndedActorOnce proves an actor id two active states declare is +// listed once when the actor has ended. +func TestActorSets_ListsAnEndedActorOnce(t *testing.T) { + ctx := context.Background() + child := state.ForgeFor[setsCtx]("child"). + State("working"). + State("done").Final(). + Initial("working"). + Transition("working").On("finish").GoTo("done"). + Quench() + m := state.ForgeFor[setsCtx]("twice"). + Actor("child"). + State("off"). + SuperState("par"). + Region("left"). + Initial("p"). + SubState("p").InvokeActor("child", state.WithInvokeID("v")). + EndRegion(). + Region("right"). + Initial("q"). + SubState("q").InvokeActor("child", state.WithInvokeID("v")). + EndRegion(). + EndSuperState(). + Initial("off"). + Transition("off").On("go").GoTo("par"). + Quench() + palette := map[string]state.ActorBehavior{"child": func(map[string]any) (state.ActorInstance, error) { + return state.NewActor(child.Cast(setsCtx{}, state.WithInitialState("working")), nil), nil + }} + h, err := NewRunner(m, NewMemStore(), WithActorPalette[string, string, setsCtx](palette)). + Start(ctx, "twice", setsCtx{}, state.WithInitialState("off")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + if found, deliverErr := h.DeliverToActorByID(ctx, "v", "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActorByID = %v, %v", found, deliverErr) + } + if ended, _ := h.actorSets(); len(ended.IDs) != 1 || ended.IDs[0] != "v" { + t.Fatalf("ended = %v, want [v]", ended.IDs) + } +} diff --git a/durable/runner.go b/durable/runner.go index 433d3e94..d7013b95 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -1174,6 +1174,7 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { } } slices.Sort(endedIDs) + endedIDs = slices.Compact(endedIDs) slices.Sort(unstartedIDs) unstartedIDs = slices.Compact(unstartedIDs) h.seen = map[string]bool{} @@ -1247,16 +1248,23 @@ func servicesExcept(effects []state.Effect, ended []string) []state.Effect { return out } -// respawn spawns the actors effects declare, in order. With a recorded unstarted set, -// an actor it leaves out was running, and the journal holds every parent Fire its start -// drove, so it spawns without letting its start reach the parent. An unstarted actor, -// or any actor when the journal recorded no set, spawns as new. +// respawn spawns the actors effects declare. With a recorded unstarted set, an actor it +// leaves out was running, and the journal holds every parent Fire its start drove, so it +// spawns without letting its start reach the parent. An unstarted actor, or any actor +// when the journal recorded no set, spawns as new. The running actors spawn first, in +// order, then the rest: a message a new actor sends the parent can enter a state that +// spawns a running actor, which must already be running, or its start would reach the +// parent a second time. func respawn[S comparable, E comparable, C any](ctx context.Context, actors *state.ActorSystem[S, E, C], effects []state.Effect, unstarted *ActorSet) { + var fresh []state.Effect for _, eff := range effects { if sp, ok := eff.(state.SpawnActor); ok && unstarted != nil && !slices.Contains(unstarted.IDs, sp.ID) { actors.AbsorbRespawn(ctx, []state.Effect{eff}) continue } + fresh = append(fresh, eff) + } + for _, eff := range fresh { actors.Absorb(ctx, []state.Effect{eff}) } } diff --git a/durable/spawn_message_test.go b/durable/spawn_message_test.go index c433a7aa..88570cfe 100644 --- a/durable/spawn_message_test.go +++ b/durable/spawn_message_test.go @@ -210,3 +210,92 @@ func TestDeliverToActor_JournalsEachFireUnderItsActor(t *testing.T) { t.Fatalf("journaled actor entries under %v, want %s", got, want) } } + +// sender is an actor that sends its parent ev from its initial entry, then keeps +// running. +type sender struct { + ev string + sent bool +} + +func (s *sender) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (s *sender) ChildEffects() []state.Effect { + if s.sent { + return nil + } + s.sent = true + return []state.Effect{state.SendParent{Event: s.ev}} +} +func (s *sender) Output() any { return nil } + +// TestRecover_ARetriedSpawnsMessageDoesNotRestartARunningActor proves Recover spawns the +// actors that were running before it retries an unstarted one. The parallel state +// declares the hopper, which can't start live, ahead of the greeter that one region +// declares as "v". When Recover's retry starts the hopper, its hop enters the other +// region's state, which declares "v" too. The greeter must already be running there, +// so that spawn is a no-op and its journaled hello applies once, across two Recovers. +func TestRecover_ARetriedSpawnsMessageDoesNotRestartARunningActor(t *testing.T) { + ctx := context.Background() + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + m := state.ForgeFor[actorCtx]("cascade"). + Reducer("noteHello", note("hello")). + Reducer("notePoke", note("poke")). + Actor("hopper"). + Actor("greeter"). + State("off"). + SuperState("par").InvokeActor("hopper"). + Region("left"). + Initial("p1"). + SubState("p1").InvokeActor("greeter", state.WithInvokeID("v")). + EndRegion(). + Region("right"). + Initial("q1"). + SubState("q1"). + SubState("q2").InvokeActor("greeter", state.WithInvokeID("v")). + EndRegion(). + EndSuperState(). + Initial("off"). + Transition("off").On("go").GoTo("par"). + Transition("p1").On("hello").GoTo("p1").Assign("noteHello"). + Transition("p1").On("poke").GoTo("p1").Assign("notePoke"). + Transition("q1").On("hop").GoTo("q2"). + Quench() + palette := func(hopperStarts bool) greetOption { + hopper := failingSpawn(nil) + if hopperStarts { + hopper = func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "hop"}, nil } + } + return durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "hopper": hopper, + "greeter": func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "hello"}, nil }, + }) + } + store, id := durable.NewMemStore(), durable.InstanceID("cascade") + h, err := durable.NewRunner(m, store, palette(false)).Start(ctx, id, actorCtx{}, state.WithInitialState("off")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + wantHellos(t, "live", h) + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, palette(true)) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d", round), recovered) + if got := fmt.Sprint(recovered.Instance().Configuration()); got != "[p1 q2]" { + t.Fatalf("Recover %d configuration = %s, want [p1 q2] after the hopper's hop", round, got) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } +} diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index b828df63..aef0bb7b 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -837,3 +837,40 @@ func TestStart_FailsWhenItsContextEndsDuringASpawn(t *testing.T) { t.Fatalf("recovered state = %q, want failed", got) } } + +// TestRecover_FailsWhenItsContextEndsAfterReplay proves Recover returns no Handle when +// its context ends after the journal is replayed, here while it spawns the resume +// point's actor, though no parent Fire was refused. +func TestRecover_FailsWhenItsContextEndsAfterReplay(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("late"). + Actor("quiet"). + State("working").InvokeActor("quiet"). + Initial("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + quiet := func(hook func()) []stepOption { + return []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "quiet": func(map[string]any) (state.ActorInstance, error) { + if hook != nil { + hook() + } + return &sender{sent: true}, nil + }, + })} + } + store, id := durable.NewMemStore(), durable.InstanceID("late") + h, err := durable.NewRunner(m, store, quiet(nil)...).Start(ctx, id, stepCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + turn, cancel := context.WithCancel(ctx) + defer cancel() + recovered, err := durable.Recover(turn, m, store, id, quiet(cancel)...) + if recovered != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Recover = Handle %v, %v, want no Handle and context.Canceled", recovered != nil, err) + } +} From fdd395ce81fbc4edd1fdb4425aa7534a9fb6abf6 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 13 Nov 2026 17:25:15 -0700 Subject: [PATCH 18/38] fix(durable): keep respawn quiet to the actor's own start; Start fails only on a refusal A respawned actor's start stays quiet, but the parent Fires its failure or settle drives (onError, onDone) and the effects they absorb now run as under Absorb. Before, an actor such a Fire spawned couldn't reach the parent, and its messages were dropped without being journaled. Start fails only when a context's ending refused a held actor Fire. A context that ends with no Fire refused no longer fails a consistent Start, which a retry couldn't recover from (ErrInstanceExists). Also: Recover absorbs the running and retried spawns in one call each, the service and actor start filters share one helper, and heldFires is inlined. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 15 ++++--- durable/runner.go | 86 ++++++++++++++----------------------- durable/step_rule_test.go | 67 +++++++++++++++++++++++++++++ state/actor_respawn_test.go | 52 ++++++++++++++++++++++ state/actor_system.go | 17 +++++++- 5 files changed, 175 insertions(+), 62 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 09503722..22f9f50e 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -67,13 +67,14 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. recorded with a delivery's last Fire still replays into that transition. Only steps this version records get the fixes below. - Requires Go 1.27.4. -- **`Start` fails when a context ends during it.** If ctx ends, or a context's ending - (ctx's, or one middleware derived from it) refuses a parent Fire an initial actor - drove, such as a failed spawn's onError, `Start` returns an error wrapping the - context's error and no Handle. It used to return a Handle whose state lacked that - Fire, while `Recover` would apply it. The baseline is recorded, so `Recover` the - instance. `Recover` likewise fails when a context's ending refuses a parent Fire its - own spawns drove, rather than returning a Handle the journal can't reach. +- **`Start` fails on a context refusal.** If a context's ending (ctx's, or one + middleware derived from it) refuses a parent Fire an initial actor drove, such as a + failed spawn's onError, `Start` returns an error wrapping the context's error and no + Handle. It used to return a Handle whose state lacked that Fire, while `Recover` + would apply it. The baseline is recorded, so `Recover` the instance. A ctx that ends + with no Fire refused doesn't fail `Start`. `Recover` likewise fails when a context's + ending refuses a parent Fire its own spawns drove, rather than returning a Handle the + journal can't reach. - **A Handle's steps are serialized across goroutines.** `Fire`, `Tick`, `RunService` and `DeliverToActor` hold a lock while they apply to the kernel and record the step, so a host's timer loop no longer loses acknowledged steps. Effects dispatch after the lock diff --git a/durable/runner.go b/durable/runner.go index d7013b95..41adbb43 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -491,10 +491,11 @@ func (h *Handle[S, E, C]) ID() InstanceID { return h.id } // InstanceID that already exists in the Store reports ErrInstanceExists rather // than clobbering its recorded baseline. // -// If ctx ends during Start, or a context ending (ctx's, or one middleware derived from -// it) refuses a parent Fire an initial actor drove, such as a failed spawn's onError, -// Start returns an error wrapping the context's error and no Handle. The baseline is -// recorded by then, so Recover the instance rather than Start it again. +// If a context ending (ctx's, or one middleware derived from it) refuses a parent Fire +// an initial actor drove, such as a failed spawn's onError, Start returns an error +// wrapping the context's error and no Handle. The baseline is recorded by then, so +// Recover the instance rather than Start it again. A ctx that ends with no Fire refused +// doesn't fail Start. func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opts ...state.CastOption[S]) (*Handle[S, E, C], error) { if _, _, err := r.store.Load(ctx, id); err == nil { return nil, fmt.Errorf("%w: %q", ErrInstanceExists, id) @@ -558,14 +559,11 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // A parent Fire a starting actor drove (a message it sent as it started, or a failed // spawn's onError) applied to the instance after its baseline, so the first step // journals it, ahead of its own work. One a context's ending refused never applied, - // and the Handle would hold state the journal can't reach, so Start fails, as it does - // when ctx ended: Recover starts from the baseline. - startFires, ended := heldFires(actorFires.take()) - if ended == nil { - ended = ctx.Err() - } - if ended != nil { - return nil, fmt.Errorf("durable: starting %q: %w", id, ended) + // and replaying it under a live context would apply it, so Start fails: Recover + // starts from the baseline. A context that ended with no Fire refused cost nothing. + startFires := actorFires.take() + if refused := refusedByContext(parentFireErrs(startFires)...); refused != nil { + return nil, fmt.Errorf("durable: starting %q: %w", id, refused) } // The actors that started are seen running, so one later stopped counts as ended. seen := map[string]bool{} @@ -1093,16 +1091,6 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) return nil } -// heldFires returns the parent Fires a Start's or Recover's spawns drove, all of which -// the next step journals, or the context error that refused one: that Fire never -// applied, and replaying it under a live context would apply it. -func heldFires[S comparable](fires []state.ParentFire[S]) ([]state.ParentFire[S], error) { - if err := refusedByContext(parentFireErrs(fires)...); err != nil { - return nil, err - } - return fires, nil -} - // recordedSet is an actor set the journal records when a step changes it. type recordedSet struct { ids []string // the set the journal last recorded @@ -1214,33 +1202,18 @@ func declaredActors(effects []state.Effect) []string { return ids } -// spawnsExcept returns effects without the spawns of the actors ended holds, so -// Recover doesn't spawn an actor the live run had ended. With no recorded set it -// returns effects unchanged, spawning every declared actor, as Recover did before the -// set was recorded. -func spawnsExcept(effects []state.Effect, ended *ActorSet) []state.Effect { - if ended == nil { +// startsExcept returns effects without the starts of kind T (a SpawnActor or a +// StartService) whose id, as id reads it, ids holds. Recover uses it so it doesn't +// spawn an actor the live run had ended, or start a service that settled while its +// state stayed active. The kind matters: an explicit invoke id can name both an actor +// and a service. With no ids it returns effects unchanged. +func startsExcept[T state.Effect](effects []state.Effect, ids []string, id func(T) string) []state.Effect { + if len(ids) == 0 { return effects } out := make([]state.Effect, 0, len(effects)) for _, eff := range effects { - if sp, ok := eff.(state.SpawnActor); ok && slices.Contains(ended.IDs, sp.ID) { - continue - } - out = append(out, eff) - } - return out -} - -// servicesExcept returns effects without the starts of the services ended names, so -// Recover doesn't start a service that settled while its state stayed active. -func servicesExcept(effects []state.Effect, ended []string) []state.Effect { - if len(ended) == 0 { - return effects - } - out := make([]state.Effect, 0, len(effects)) - for _, eff := range effects { - if sv, ok := eff.(state.StartService); ok && slices.Contains(ended, sv.ID) { + if start, ok := eff.(T); ok && slices.Contains(ids, id(start)) { continue } out = append(out, eff) @@ -1256,17 +1229,16 @@ func servicesExcept(effects []state.Effect, ended []string) []state.Effect { // spawns a running actor, which must already be running, or its start would reach the // parent a second time. func respawn[S comparable, E comparable, C any](ctx context.Context, actors *state.ActorSystem[S, E, C], effects []state.Effect, unstarted *ActorSet) { - var fresh []state.Effect + var running, fresh []state.Effect for _, eff := range effects { if sp, ok := eff.(state.SpawnActor); ok && unstarted != nil && !slices.Contains(unstarted.IDs, sp.ID) { - actors.AbsorbRespawn(ctx, []state.Effect{eff}) + running = append(running, eff) continue } fresh = append(fresh, eff) } - for _, eff := range fresh { - actors.Absorb(ctx, []state.Effect{eff}) - } + actors.AbsorbRespawn(ctx, running) + actors.Absorb(ctx, fresh) } // Recover reconstructs a durable instance purely from the Store: it loads the @@ -1327,7 +1299,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S svcBuf := make([]state.JournalEntry, 0) svc := r.newServiceRunner(inst) if svc != nil { - svc.Absorb(ctx, servicesExcept(inst.StartEffects(), env.EndedServices)) + svc.Absorb(ctx, startsExcept(inst.StartEffects(), env.EndedServices, func(sv state.StartService) string { return sv.ID })) } // Build the child-machine actor host driver, but DO NOT spawn the restored @@ -1414,7 +1386,13 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // An actor that was running sends the parent nothing as it spawns again: the journal // holds what its start drove. if actors != nil { - spawns := spawnsExcept(inst.StartEffects(), ended) + // With no recorded ended set, Recover spawns every declared actor, as it did + // before the set was recorded. + var endedIDs []string + if ended != nil { + endedIDs = ended.IDs + } + spawns := startsExcept(inst.StartEffects(), endedIDs, func(sp state.SpawnActor) string { return sp.ID }) actorFires.attempt(spawns) respawn(ctx, actors, spawns, unstarted) } @@ -1422,8 +1400,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // failed spawn's onError) applied to the instance past its journal, so the next step // journals it, ahead of its own work. One a context's ending refused never applied, // and the Handle would hold state the journal can't reach, so Recover fails. - recoverFires, refused := heldFires(actorFires.take()) - if refused != nil { + recoverFires := actorFires.take() + if refused := refusedByContext(parentFireErrs(recoverFires)...); refused != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, refused) } // The journal's ended actors stay ended, and seen, so the next step records a set diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index aef0bb7b..dbb98ffc 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -874,3 +874,70 @@ func TestRecover_FailsWhenItsContextEndsAfterReplay(t *testing.T) { t.Fatalf("Recover = Handle %v, %v, want no Handle and context.Canceled", recovered != nil, err) } } + +// cancelingStore ends a context once Start's baseline checkpoint is written. +type cancelingStore struct { + durable.Store + cancel context.CancelFunc +} + +func (s cancelingStore) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { + err := s.Store.Checkpoint(ctx, id, snapshot, throughStep, opts...) + s.cancel() + return err +} + +// TestStart_SucceedsWhenItsContextEndsWithNoRefusal proves Start fails only on a parent +// Fire a context's ending refused, not whenever its context ends after the baseline: +// with no actors, or with an actor that started and drove nothing, Start returns a +// Handle whose steps record, and Recover rebuilds the same state. +func TestStart_SucceedsWhenItsContextEndsWithNoRefusal(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("lateStart"). + Actor("quiet"). + State("idle"). + State("working").InvokeActor("quiet"). + Initial("idle"). + Transition("idle").On("go").GoTo("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + for _, initial := range []string{"idle", "working"} { + t.Run(initial, func(t *testing.T) { + turn, cancel := context.WithCancel(ctx) + defer cancel() + mem := durable.NewMemStore() + var store durable.Store = mem + hook := func() {} + if initial == "idle" { + store = cancelingStore{Store: mem, cancel: cancel} + } else { + hook = cancel + } + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "quiet": func(map[string]any) (state.ActorInstance, error) { + hook() + return &sender{sent: true}, nil + }, + })} + id := durable.InstanceID("late-" + initial) + h, err := durable.NewRunner(m, store, opts...).Start(turn, id, stepCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + if turn.Err() == nil { + t.Fatal("Start's context didn't end") + } + hook = func() {} + if _, err = h.Fire(ctx, map[string]string{"idle": "go", "working": "poke"}[initial]); err != nil { + t.Fatalf("Fire after Start: %v", err) + } + recovered, err := durable.Recover(ctx, m, mem, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "working" { + t.Fatalf("recovered state = %q, want working", got) + } + }) + } +} diff --git a/state/actor_respawn_test.go b/state/actor_respawn_test.go index 9c1ccaa4..a788deec 100644 --- a/state/actor_respawn_test.go +++ b/state/actor_respawn_test.go @@ -79,3 +79,55 @@ func TestActorSystem_AbsorbRespawn_DropsStartMessages(t *testing.T) { t.Fatalf("AbsorbRespawn of a spawn that can't start left the parent in %q, want failed by its onError", got) } } + +// starter is an actor that sends its first effects from its initial entry, then keeps +// running; finish ends it with no output. +type starter struct{ start []state.Effect } + +func (a *starter) DeliverFire(_ context.Context, ev any) (bool, any) { return ev == "finish", nil } +func (a *starter) ChildEffects() []state.Effect { + out := a.start + a.start = nil + return out +} +func (a *starter) Output() any { return nil } + +// TestActorSystem_AbsorbRespawn_ParentFiresItDrivesAreAudible proves the quiet of an +// AbsorbRespawn spawn covers only the spawned actor's own start: the onError of a spawn +// that can't start, and the onDone of an actor a respawned one ends as it starts, are +// parent Fires the earlier start didn't send, so the greeter their state spawns reaches +// the parent with its hello, as under Absorb. +func TestActorSystem_AbsorbRespawn_ParentFiresItDrivesAreAudible(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("audible"). + Actor("greeter"). + Actor("broken"). + Actor("finisher"). + Actor("poker"). + State("failing").InvokeActor("broken", state.WithInvokeOnError("brokenFailed")). + State("pair").InvokeActor("finisher", state.WithInvokeOnDone("finished")).InvokeActor("poker"). + State("greeting").InvokeActor("greeter"). + State("hellod"). + Initial("failing"). + Transition("failing").On("brokenFailed").GoTo("greeting"). + Transition("pair").On("finished").GoTo("greeting"). + Transition("greeting").On("hello").GoTo("hellod"). + Quench() + finisher := state.ActorID("audible", "pair", 0) + for _, from := range []string{"failing", "pair"} { + t.Run(from, func(t *testing.T) { + inst := m.Cast(&trec{}, state.WithInitialState(from)) + sys := state.NewActorSystem(inst) + sys.Register("greeter", func(map[string]any) (state.ActorInstance, error) { return &startGreeter{}, nil }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("can't start") }) + sys.Register("finisher", func(map[string]any) (state.ActorInstance, error) { return &starter{}, nil }) + sys.Register("poker", func(map[string]any) (state.ActorInstance, error) { + return &starter{start: []state.Effect{state.SendTo{TargetID: finisher, Event: "finish"}}}, nil + }) + sys.AbsorbRespawn(ctx, inst.StartEffects()) + if got := inst.Current(); got != "hellod" { + t.Fatalf("AbsorbRespawn from %s left the parent in %q, want hellod: the greeter its onError or onDone spawned should reach the parent", from, got) + } + }) + } +} diff --git a/state/actor_system.go b/state/actor_system.go index 60ecff97..b707d6f1 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -302,7 +302,9 @@ func (s *ActorSystem[S, E, C]) AbsorbFor(ctx context.Context, event any, effects // on receiving a message from it. Such a message is dropped without a parent Fire, so // WithParentFireObserver doesn't see it. A spawn that can't start still routes its // onError, and a settle its onDone or onError, since those aren't messages the earlier -// start sent. Its other effects absorb as under Absorb. +// start sent, and the effects such a Fire drives absorb as under Absorb: an actor its +// state spawns, or one it sends to, reaches the parent. Its other effects absorb as +// under Absorb. func (s *ActorSystem[S, E, C]) AbsorbRespawn(ctx context.Context, effects []Effect) { quiet := context.WithValue(ctx, respawnKey{}, true) for _, eff := range effects { @@ -325,6 +327,17 @@ func respawning(ctx context.Context) bool { return quiet } +// audible returns ctx without an AbsorbRespawn spawn's mark, for a parent Fire that +// isn't a message the earlier start sent (a failed spawn's onError, or a settle's +// onDone or onError) and the effects it drives: an actor that Fire's state spawns, or +// one it sends to, reaches the parent as under Absorb. +func audible(ctx context.Context) context.Context { + if !respawning(ctx) { + return ctx + } + return context.WithValue(ctx, respawnKey{}, false) +} + // absorb scans effects emitted by the parent instance while handling curEvent, // spawning/stopping actors and routing the parent's outbound messages (the parent // is the sender). curEvent is nil for the plain Absorb path (a parent ForwardEvent @@ -416,6 +429,7 @@ func (s *ActorSystem[S, E, C]) spawn(ctx context.Context, e SpawnActor) { // failure escalates to the parent as a typed ActorEscalation rather than being // silently swallowed (the G3 default), so a spawn that cannot start is never lost. func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err error) { + ctx = audible(ctx) ev, ok := e.OnError.(E) if !ok { s.escalate(ctx, &runningActor[E]{ref: ActorRef{ID: e.ID, SystemID: e.SystemID, Src: e.Src.Name}}, "", err) @@ -725,6 +739,7 @@ func (s *ActorSystem[S, E, C]) fireParentFrom(ctx context.Context, event any, se // (the G3 escalate-to-parent default), so an unhandled child crash always surfaces. // A clean completion with no onDone remains a fire-and-forget no-op. func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any, err error) (FireResult[S], bool) { + ctx = audible(ctx) s.mu.Lock() ra, ok := s.actors[id] if !ok { From 5d0b5e6885fd17a43bcbd70739846cd0855eba92 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 13 Nov 2026 19:00:14 -0700 Subject: [PATCH 19/38] fix(state): keep a respawn's nested start Fires quiet; mark quiet on the system AbsorbRespawn kept a respawned actor's messages from the parent, but let through the onDone or onError of a nested actor its start spawned. The journal holds that Fire too, so Recover applied it twice. Now only the actors AbsorbRespawn names can drive a new parent Fire: a spawn that fails now, or one that settles while the others start. While such a Fire and its effects run, the parent hears them. The quiet mark is a field on the ActorSystem, not a context value, so a dispatch to the parent no longer walks the context chain, and the mark can't leak into a context a behavior captures. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 3 +- durable/respawn_nested_test.go | 87 ++++++++++++++++++++++ state/CHANGELOG.md | 11 +-- state/actor_respawn_test.go | 128 +++++++++++++++++++++++++++++++++ state/actor_system.go | 118 ++++++++++++++++++++++-------- 5 files changed, 312 insertions(+), 35 deletions(-) create mode 100644 durable/respawn_nested_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 22f9f50e..c0923d45 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -192,7 +192,8 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. spawned, so `Recover` applied it twice. Every step now journals every parent Fire it drove, and `Start`'s and `Recover`'s go with the step after, so replay re-fires each where it ran. `Recover` spawns an actor that was running with `state`'s new - `ActorSystem.AbsorbRespawn`, which keeps such messages from the parent. An actor whose + `ActorSystem.AbsorbRespawn`, which keeps such messages from the parent, and the onDone + or onError of a nested actor its start spawns, which the journal holds too. An actor whose spawn failed with no onError never ran, so its messages are new: they reach the parent and are journaled with the next step. A journal from before this records no unstarted actors, and `Recover` spawns every actor as new, as before. diff --git a/durable/respawn_nested_test.go b/durable/respawn_nested_test.go new file mode 100644 index 00000000..df88c02e --- /dev/null +++ b/durable/respawn_nested_test.go @@ -0,0 +1,87 @@ +package durable_test + +import ( + "context" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// starting is an actor that emits start from its initial entry, then keeps running. +type starting struct{ start []state.Effect } + +func (a *starting) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (a *starting) ChildEffects() []state.Effect { + out := a.start + a.start = nil + return out +} +func (a *starting) Output() any { return nil } + +// TestRecover_ANestedChildsStartFireAppliesOnce proves a parent Fire that a running +// actor's start drives through a nested child it spawns, the onError of a nested spawn +// that can't start or the onDone of one the actor ends at once, is journaled live and +// applied exactly once across repeated Recovers: Recover spawns the running actor again, +// and its nested child fails or settles again, but that parent Fire is part of the +// actor's start, which the journal already holds. +func TestRecover_ANestedChildsStartFireAppliesOnce(t *testing.T) { + ctx := context.Background() + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + m := state.ForgeFor[actorCtx]("nested"). + Reducer("noteNested", note("nested")). + Reducer("notePoke", note("poke")). + Actor("host"). + State("hosting").InvokeActor("host"). + Initial("hosting"). + Transition("hosting").On("nestedFailed").GoTo("hosting").Assign("noteNested"). + Transition("hosting").On("nestedDone").GoTo("hosting").Assign("noteNested"). + Transition("hosting").On("poke").GoTo("hosting").Assign("notePoke"). + Quench() + starts := map[string][]state.Effect{ + "fails": {state.SpawnActor{ID: "child", Src: state.Ref{Name: "broken"}, OnError: "nestedFailed"}}, + "settles": { + state.SpawnActor{ID: "child", Src: state.Ref{Name: "finisher"}, OnDone: "nestedDone"}, + state.SendTo{TargetID: "child", Event: "finish"}, + }, + } + for _, how := range []string{"fails", "settles"} { + t.Run(how, func(t *testing.T) { + opts := []greetOption{durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "host": func(map[string]any) (state.ActorInstance, error) { + return &starting{start: starts[how]}, nil + }, + "broken": failingSpawn(nil), + "finisher": finishingChild(), + })} + store, id := durable.NewMemStore(), durable.InstanceID("nested") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("hosting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + want := fmt.Sprint([]string{"nested", "poke"}) + if got := fmt.Sprint(h.Instance().Entity().Notes); got != want { + t.Fatalf("live notes = %s, want %s", got, want) + } + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != want { + t.Fatalf("Recover %d notes = %s, want %s: the nested child's parent Fire is part of the host's start", round, got, want) + } + } + }) + } +} diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index d79897df..eb292417 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -20,10 +20,13 @@ counts as an additive (minor) versus breaking (major) change. Use the can tell a parent transition refused because its context ended from one that applied, and which Fire carried the actor's output. It's additive, within v1.1.0. - **`ActorSystem.AbsorbRespawn`** is `Absorb` for actors a host spawns again after - rebuilding the parent from a record that already holds the messages their earlier - start sent it: an actor it spawns starts as under `Absorb`, but no message reaches the - parent while it starts. The durable runner's `Recover` uses it for the actors that were - running. It's additive, within v1.1.0. + rebuilding the parent from a record that already holds every parent Fire their + earlier start drove: an actor it spawns starts as under `Absorb`, but its start + doesn't reach the parent, neither a message sent to the parent nor the onDone or + onError of a nested actor it spawns. The onError of a respawn that can't start, and + the onDone or onError of a respawned actor that settles as the others start, still + fire the parent, since that actor was running. The durable runner's `Recover` uses it + for the actors that were running. It's additive, within v1.1.0. - **`FireEventData`** reports the payload a `WithEventData` option carries, so a host that records a Fire can persist it. It's additive, so the next release is v1.1.0. - **Callbacks get the step's context.** `GuardCtx`, `ActionCtx` and `AssignCtx` have a new diff --git a/state/actor_respawn_test.go b/state/actor_respawn_test.go index a788deec..6c43560c 100644 --- a/state/actor_respawn_test.go +++ b/state/actor_respawn_test.go @@ -131,3 +131,131 @@ func TestActorSystem_AbsorbRespawn_ParentFiresItDrivesAreAudible(t *testing.T) { }) } } + +// TestActorSystem_AbsorbRespawn_NestedStartFiresStayQuiet proves the quiet of an +// AbsorbRespawn spawn covers a nested actor the respawned one spawns as it starts: the +// onError of a nested spawn that can't start, and the onDone of a nested actor the +// respawned one ends as it starts, are parent Fires its earlier start drove, so neither +// fires the parent again, though each does under Absorb. +func TestActorSystem_AbsorbRespawn_NestedStartFiresStayQuiet(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("nested"). + Actor("host"). + State("hosting").InvokeActor("host"). + State("heard"). + Initial("hosting"). + Transition("hosting").On("nestedFailed").GoTo("heard"). + Transition("hosting").On("nestedDone").GoTo("heard"). + Quench() + starts := map[string][]state.Effect{ + "fails": {state.SpawnActor{ID: "child", Src: state.Ref{Name: "broken"}, OnError: "nestedFailed"}}, + "settles": { + state.SpawnActor{ID: "child", Src: state.Ref{Name: "finisher"}, OnDone: "nestedDone"}, + state.SendTo{TargetID: "child", Event: "finish"}, + }, + } + for _, how := range []string{"fails", "settles"} { + t.Run(how, func(t *testing.T) { + build := func() (*state.Instance[string, string, *trec], *state.ActorSystem[string, string, *trec]) { + inst := m.Cast(&trec{}, state.WithInitialState("hosting")) + sys := state.NewActorSystem(inst) + sys.Register("host", func(map[string]any) (state.ActorInstance, error) { return &starter{start: starts[how]}, nil }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("can't start") }) + sys.Register("finisher", func(map[string]any) (state.ActorInstance, error) { return &starter{}, nil }) + return inst, sys + } + live, liveSys := build() + liveSys.Absorb(ctx, live.StartEffects()) + if got := live.Current(); got != "heard" { + t.Fatalf("Absorb left the parent in %q, want heard: the nested child's Fire should reach it", got) + } + resumed, sys := build() + var seen []state.ParentFire[string] + sys.WithParentFireObserver(func(pf state.ParentFire[string]) { seen = append(seen, pf) }) + sys.AbsorbRespawn(ctx, resumed.StartEffects()) + if got := resumed.Current(); got != "hosting" { + t.Fatalf("AbsorbRespawn left the parent in %q, want hosting: the nested child's Fire is part of the host's start", got) + } + if len(seen) != 0 { + t.Fatalf("observed %d parent Fires, want none", len(seen)) + } + }) + } +} + +// TestActorSystem_AbsorbRespawn_QuietResumesAfterANewFire proves a parent Fire +// AbsorbRespawn lets through, the onDone of a respawned actor another one's start ends, +// hears the parent only while it and its effects run: the hello the second actor's start +// sends next is still part of that start, and is dropped. +func TestActorSystem_AbsorbRespawn_QuietResumesAfterANewFire(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("resume"). + Actor("finisher"). + Actor("poker"). + State("pair").InvokeActor("finisher", state.WithInvokeOnDone("finished")).InvokeActor("poker"). + State("finishedState"). + State("hellod"). + Initial("pair"). + Transition("pair").On("finished").GoTo("finishedState"). + Transition("finishedState").On("hello").GoTo("hellod"). + Quench() + finisher := state.ActorID("resume", "pair", 0) + inst := m.Cast(&trec{}, state.WithInitialState("pair")) + sys := state.NewActorSystem(inst) + sys.Register("finisher", func(map[string]any) (state.ActorInstance, error) { return &starter{}, nil }) + sys.Register("poker", func(map[string]any) (state.ActorInstance, error) { + return &starter{start: []state.Effect{ + state.SendTo{TargetID: finisher, Event: "finish"}, + state.SendParent{Event: "hello"}, + }}, nil + }) + sys.AbsorbRespawn(ctx, inst.StartEffects()) + if got := inst.Current(); got != "finishedState" { + t.Fatalf("AbsorbRespawn left the parent in %q, want finishedState: the finisher's onDone is new, but the poker's hello is part of its start", got) + } +} + +// pinger is an actor that sends its parent "hello" each time it's delivered "ping". +type pinger struct{ out []state.Effect } + +func (p *pinger) DeliverFire(_ context.Context, ev any) (bool, any) { + if ev == "ping" { + p.out = []state.Effect{state.SendParent{Event: "hello"}} + } + return false, nil +} + +func (p *pinger) ChildEffects() []state.Effect { + out := p.out + p.out = nil + return out +} + +func (p *pinger) Output() any { return nil } + +// TestActorSystem_AbsorbRespawn_QuietEndsWithIt proves the quiet of an AbsorbRespawn +// spawn ends when it returns, even for the context the actor's behavior got: a delivery +// made later with that context reaches the parent with the message it drives. +func TestActorSystem_AbsorbRespawn_QuietEndsWithIt(t *testing.T) { + m := state.ForgeFor[*trec]("after"). + Actor("pinger"). + State("waiting").InvokeActor("pinger"). + State("hellod"). + Initial("waiting"). + Transition("waiting").On("hello").GoTo("hellod"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("waiting")) + sys := state.NewActorSystem(inst) + var captured context.Context + sys.RegisterContext("pinger", func(ctx context.Context, _ map[string]any) (state.ActorInstance, error) { + captured = ctx + return &pinger{}, nil + }) + sys.AbsorbRespawn(context.Background(), inst.StartEffects()) + if !sys.DeliverByID(captured, state.ActorID("after", "waiting", 0), "ping") { + t.Fatal("the pinger isn't running") + } + if got := inst.Current(); got != "hellod" { + t.Fatalf("a delivery after AbsorbRespawn left the parent in %q, want hellod: its hello should reach the parent", got) + } +} diff --git a/state/actor_system.go b/state/actor_system.go index b707d6f1..2eaea96b 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -178,6 +178,14 @@ type ActorSystem[S comparable, E comparable, C any] struct { // the per-instance Inspector wired with WithInspector: the ActorSystem owns // spawning, stopping, and message delivery, which the pure Fire step never sees. inspector Inspector + + // quiet is set while AbsorbRespawn spawns an actor: a message to the parent is + // dropped, and so is a nested actor's onDone or onError. A parent Fire it lets + // through clears it until that Fire's effects are absorbed. Guarded by mu. + quiet bool + // respawned holds the ids of the actors AbsorbRespawn is spawning, whose failed + // spawn or settle fires the parent even while it's quiet. Guarded by mu. + respawned map[string]bool } // WithActorInspector wires a live observer sink fed the ActorSystem's @@ -295,47 +303,81 @@ func (s *ActorSystem[S, E, C]) AbsorbFor(ctx context.Context, event any, effects } // AbsorbRespawn is Absorb for actors a host spawns again after rebuilding the parent -// from a record that already holds the messages their earlier start sent it, as the +// from a record that already holds every parent Fire their earlier start drove, as the // durable runner's Recover does for the actors that were running. Each actor it spawns -// starts as under Absorb, but no message reaches the parent while it starts: not one it -// sends the parent from its initial entry, nor one another actor sends the parent then, -// on receiving a message from it. Such a message is dropped without a parent Fire, so -// WithParentFireObserver doesn't see it. A spawn that can't start still routes its -// onError, and a settle its onDone or onError, since those aren't messages the earlier -// start sent, and the effects such a Fire drives absorb as under Absorb: an actor its -// state spawns, or one it sends to, reaches the parent. Its other effects absorb as -// under Absorb. +// starts as under Absorb, but its start doesn't reach the parent again: no message it, +// or an actor it sends to or spawns, sends the parent while it starts, and no onDone or +// onError of a nested actor its start spawns, fires the parent. Such a Fire is dropped, +// so WithParentFireObserver doesn't see it. What the earlier start can't have driven +// still fires the parent, since each actor in effects was running: the onError of one +// whose spawn fails now, and the onDone or onError of one that settles as the others +// start. A nested actor's failure with no onError still escalates. The effects such a Fire drives absorb as under Absorb: an actor +// its state spawns, or one it sends to, reaches the parent. Its other effects absorb as +// under Absorb. Don't drive the system from another goroutine while AbsorbRespawn runs: +// a parent Fire that one drives would be dropped too. func (s *ActorSystem[S, E, C]) AbsorbRespawn(ctx context.Context, effects []Effect) { - quiet := context.WithValue(ctx, respawnKey{}, true) + respawned := map[string]bool{} for _, eff := range effects { if e, ok := eff.(SpawnActor); ok { - s.spawn(quiet, e) + respawned[e.ID] = true + } + } + s.mu.Lock() + prev := s.respawned + s.respawned = respawned + s.mu.Unlock() + defer func() { + s.mu.Lock() + s.respawned = prev + s.mu.Unlock() + }() + for _, eff := range effects { + if e, ok := eff.(SpawnActor); ok { + s.respawnOne(ctx, e) continue } s.absorb(ctx, []Effect{eff}, nil) } } -// respawnKey marks the context of an AbsorbRespawn spawn, under which no message -// reaches the parent. -type respawnKey struct{} +// respawnOne spawns e with the parent quiet, so its start doesn't reach the parent. +func (s *ActorSystem[S, E, C]) respawnOne(ctx context.Context, e SpawnActor) { + prev := s.setQuiet(true) + defer s.setQuiet(prev) + s.spawn(ctx, e) +} -// respawning reports whether ctx is an AbsorbRespawn spawn's, so a message to the -// parent is dropped. -func respawning(ctx context.Context) bool { - quiet, _ := ctx.Value(respawnKey{}).(bool) - return quiet +// setQuiet sets whether the parent is quiet, as it is while AbsorbRespawn spawns an +// actor, and returns the previous setting. +func (s *ActorSystem[S, E, C]) setQuiet(quiet bool) bool { + s.mu.Lock() + defer s.mu.Unlock() + prev := s.quiet + s.quiet = quiet + return prev } -// audible returns ctx without an AbsorbRespawn spawn's mark, for a parent Fire that -// isn't a message the earlier start sent (a failed spawn's onError, or a settle's -// onDone or onError) and the effects it drives: an actor that Fire's state spawns, or -// one it sends to, reaches the parent as under Absorb. -func audible(ctx context.Context) context.Context { - if !respawning(ctx) { - return ctx +// isQuiet reports whether a message to the parent is dropped, as AbsorbRespawn drops +// one an actor's start sends. +func (s *ActorSystem[S, E, C]) isQuiet() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.quiet +} + +// hearingLocked reports how a parent Fire for actor id's failed spawn or settle goes +// while the parent may be quiet: dropped, when it's part of the start AbsorbRespawn is +// repeating, or fired with the parent heard again, when id is an actor AbsorbRespawn was +// given, which was running, so the Fire is new and so is all it drives. s.mu must be +// held. +func (s *ActorSystem[S, E, C]) hearingLocked(id string) (drop, lift bool) { + if !s.quiet { + return false, false } - return context.WithValue(ctx, respawnKey{}, false) + if s.respawned[id] { + return false, true + } + return true, false } // absorb scans effects emitted by the parent instance while handling curEvent, @@ -429,12 +471,21 @@ func (s *ActorSystem[S, E, C]) spawn(ctx context.Context, e SpawnActor) { // failure escalates to the parent as a typed ActorEscalation rather than being // silently swallowed (the G3 default), so a spawn that cannot start is never lost. func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err error) { - ctx = audible(ctx) ev, ok := e.OnError.(E) if !ok { s.escalate(ctx, &runningActor[E]{ref: ActorRef{ID: e.ID, SystemID: e.SystemID, Src: e.Src.Name}}, "", err) return } + s.mu.Lock() + drop, lift := s.hearingLocked(e.ID) + s.mu.Unlock() + if drop { + return + } + if lift { + prev := s.setQuiet(false) + defer s.setQuiet(prev) + } res := s.parent.Fire(ctx, ev) s.noteParentFire(ParentFire[S]{Result: res, ActorID: e.ID, SpawnFailed: true}) s.Absorb(ctx, res.Effects) @@ -692,7 +743,7 @@ func (s *ActorSystem[S, E, C]) resolveTarget(targetID, systemID string) (string, // drains it. This is the single path every routed message flows through, so parent // and child delivery share their sender bookkeeping. func (s *ActorSystem[S, E, C]) dispatch(ctx context.Context, targetID string, event any, senderID string) { - if targetID == parentActorID && respawning(ctx) { + if targetID == parentActorID && s.isQuiet() { return } s.inspectMessage(senderID, targetID, MessageSent, event) @@ -739,7 +790,6 @@ func (s *ActorSystem[S, E, C]) fireParentFrom(ctx context.Context, event any, se // (the G3 escalate-to-parent default), so an unhandled child crash always surfaces. // A clean completion with no onDone remains a fire-and-forget no-op. func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any, err error) (FireResult[S], bool) { - ctx = audible(ctx) s.mu.Lock() ra, ok := s.actors[id] if !ok { @@ -757,6 +807,7 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any ev, route = ra.onDone, ra.hasDone } s.lastOutcome = actorOutcome{output: output, err: err, set: true} + drop, lift := s.hearingLocked(id) s.mu.Unlock() // A completed actor's children are torn down with it. @@ -773,6 +824,13 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any } return FireResult[S]{}, false } + if drop { + return FireResult[S]{}, false + } + if lift { + prev := s.setQuiet(false) + defer s.setQuiet(prev) + } // Deliver the child's output/error to the parent's onDone/onError transition's // Assign through the done-event payload (AssignCtx.Event), not a side channel: // the reducer reads it from AssignCtx.Event. LastOutput/LastError remain for From 7670727f437f73fcecee0c93bf66facc9ca3a7a5 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 13 Nov 2026 19:00:47 -0700 Subject: [PATCH 20/38] fix(durable): arm the timers and services an actor-driven Fire enters A parent Fire an actor drove (its onDone, onError or a message) reached only the actor system, so the state it entered had no service in flight and no timer armed, live or after Recover; a checkpoint then recorded the service as settled. Such a Fire now arms them, live, at Start and Recover, and on replay, as a host Fire does. Fixing it exposed clock-read gaps, now closed: DeliverToActor and RunService journal their step's clock reads; a replayed service settle re-arms its timers; Recover keeps its spawns' reads and re-arms a checkpoint's timers before it spawns; Tick drops the timers it fired at its own read. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 10 + durable/actor.go | 27 ++- durable/actor_driven_drivers_test.go | 279 ++++++++++++++++++++++++ durable/checkpoint_internal_test.go | 15 -- durable/clock.go | 16 +- durable/runner.go | 313 ++++++++++++++++----------- durable/service.go | 31 +-- durable/timetravel.go | 2 +- 8 files changed, 526 insertions(+), 167 deletions(-) create mode 100644 durable/actor_driven_drivers_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index c0923d45..014646d3 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -197,6 +197,16 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. spawn failed with no onError never ran, so its messages are new: they reach the parent and are journaled with the next step. A journal from before this records no unstarted actors, and `Recover` spawns every actor as new, as before. +- **A state an actor's onDone, onError or message enters runs its timers and services.** + The actor system armed only that state's actors, so its service wasn't in flight, and + `RunService` reported none, and its timer never fired; a checkpoint then recorded the + service as settled, so `Recover` didn't start it either. Such a Fire now arms them, + live, at `Start` and `Recover`, and on replay, as a host `Fire` does. A service's + settle re-arms its state's timers on replay too, and `DeliverToActor` and `RunService` + now journal the clock reads their step took, so a checkpoint on that step can't leave + a read for the next to replay. `Recover` re-arms a checkpoint's timers before it + spawns the running actors, so a Fire one of theirs drives can cancel one, and a `Tick` + drops the timers it fired at its own clock read, not an earlier one its step records. - **A delivery journals each parent Fire under the actor that drove it,** where it used to record every one under the actor delivered to. It no longer copies the instance's history twice per delivery to do it. diff --git a/durable/actor.go b/durable/actor.go index a91aad01..f0ab4586 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -156,7 +156,8 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef } step := h.nextStep - rec := Record{Step: step, Entries: h.drainActors()} + // A parent Fire the delivery drove can arm a timer, which reads the clock. + rec := Record{Step: step, Entries: append(h.drainClock(), h.drainActors()...)} if err := h.persistStep(ctx, step, &rec); err != nil { return true, err } @@ -260,27 +261,29 @@ func splitActorEntries(rec *Record) (before, rest []state.JournalEntry, err erro // re-fires the parent's event — carrying the recorded done-data / error via // WithEventData for a settling fire, or plainly for a message-driven fire — so the // kernel re-derives the same parent transition with the same data, running no actor -// behavior. It reports an error only when the recorded entry cannot be decoded or -// the re-fired transition fails (a corrupt or mis-ordered journal). -func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry state.JournalEntry) error { +// behavior. It returns the effects of a re-fired transition that applied, so the caller +// arms the timers and services it declares, as the live run did. It reports an error +// only when the recorded entry cannot be decoded or the re-fired transition fails (a +// corrupt or mis-ordered journal). +func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry state.JournalEntry) ([]state.Effect, error) { var mp actorMessagePayload if err := json.Unmarshal(entry.Payload, &mp); err != nil { - return fmt.Errorf("durable: decoding recorded actor %q transition: %w", entry.CorrelationID, err) + return nil, fmt.Errorf("durable: decoding recorded actor %q transition: %w", entry.CorrelationID, err) } // A Fire refused before the kernel saw it (middleware that denied it) has no event // to re-fire; replay is refused the same way. if mp.Refused && len(mp.Event) == 0 { - return nil + return nil, nil } event, err := codec.Decode(mp.Event) if err != nil { - return fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.CorrelationID, err) + return nil, fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.CorrelationID, err) } var res state.FireResult[S] if mp.HasData { data, derr := replayActorData(mp) if derr != nil { - return fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.CorrelationID, derr) + return nil, fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.CorrelationID, derr) } res = inst.Fire(ctx, event, state.WithEventData(data)) } else { @@ -290,13 +293,13 @@ func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *s // replay was refused, as it said for the live Fire. switch { case res.Err != nil && mp.Refused: - return nil // the live run was refused the same way + return nil, nil // the live run was refused the same way case res.Err != nil: - return fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, res.Err) + return nil, fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, res.Err) case mp.Refused: - return fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) + return nil, fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) } - return nil + return res.Effects, nil } // replayActorData reconstructs the actor outcome a settling fire carried into the diff --git a/durable/actor_driven_drivers_test.go b/durable/actor_driven_drivers_test.go new file mode 100644 index 00000000..e242941e --- /dev/null +++ b/durable/actor_driven_drivers_test.go @@ -0,0 +1,279 @@ +package durable_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestActorDrivenFire_ArmsServicesAndTimers proves a state that an actor-driven parent +// Fire enters, by the onDone a delivery settles or by the message an actor sends as Start +// spawns it, has its service in flight and its timer armed, live and on Recover, with and +// without checkpoints: RunService runs the service and a Tick at the deadline fires the +// timer, as for a state a Fire enters. So does one a service's settle enters. Recover +// runs at the deadline, and a checkpoint lands on the step that enters armed, so a clock +// read that step left to the next would move the deadline. +func TestActorDrivenFire_ArmsServicesAndTimers(t *testing.T) { + ctx := context.Background() + m := armedMachine() + svcID := state.InvokeID("armed", "armed", 0) + for _, by := range []string{"delivery", "Start", "RunService"} { + for _, where := range []string{"live", "Recover", "Recover/every=2"} { + for _, check := range []string{"service", "timer"} { + t.Run(fmt.Sprintf("%s/%s/%s", by, where, check), func(t *testing.T) { + clk := state.NewFakeClock(epoch) + opts := armedOptions(clk, true) + if where == "Recover/every=2" { + // The checkpoint lands on the step that enters armed, so the tail + // holds only the poke after it. + opts = append(opts, durable.WithCheckpointEvery[string, string, actorCtx](2)) + } + store, id := durable.NewMemStore(), durable.InstanceID("armed") + initial := map[string]string{"delivery": "working", "Start": "going", "RunService": "loading"}[by] + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("first Fire(poke): %v", err) + } + switch by { + case "delivery": + if found, deliverErr := h.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("armed", "working", 0)}, "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActor = %v, %v", found, deliverErr) + } + case "RunService": + if _, ran, runErr := h.RunService(ctx, state.InvokeID("armed", "loading", 0)); !ran || runErr != nil { + t.Fatalf("RunService(loading) = %v, %v", ran, runErr) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if check == "timer" { + clk.Advance(10 * time.Second) + } + if where != "live" { + if h, err = durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + } + want := "fetched" + switch check { + case "service": + if _, ran, runErr := h.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v, want it to run the service the state invokes", ran, runErr) + } + case "timer": + want = "timedOut" + if _, tickErr := h.Tick(ctx); tickErr != nil { + t.Fatalf("Tick: %v", tickErr) + } + } + if got := h.Instance().Current(); got != want { + t.Fatalf("state = %q, want %q", got, want) + } + }) + } + } + } +} + +// armedMachine enters "armed", which invokes a service and arms a 10s timer, by the +// onDone of the finisher "working" runs, by the "go" the goer "going" runs sends as it +// starts, or by the onDone of the service "loading" invokes. +func armedMachine() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("armed"). + Service("fetch", fetchOK). + Actor("finisher"). + Actor("goer"). + State("working").InvokeActor("finisher", state.WithInvokeOnDone("childDone")). + State("going").InvokeActor("goer"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("loaded")). + State("armed").Invoke("fetch", state.WithInvokeOnDone("fetched")). + State("fetched"). + State("timedOut"). + Initial("working"). + Transition("working").On("childDone").GoTo("armed"). + Transition("working").On("poke").GoTo("working"). + Transition("loading").On("poke").GoTo("loading"). + Transition("going").On("go").GoTo("armed"). + Transition("loading").On("loaded").GoTo("armed"). + Transition("armed").On("poke").GoTo("armed"). + Transition("armed").On("fetched").GoTo("fetched"). + Transition("armed").After(10 * time.Second).On("elapsed").GoTo("timedOut"). + Quench() +} + +// armedOptions wires clk, the fetch service, and the finisher and goer, with a goer that +// can't start unless goerStarts. +func armedOptions(clk state.Clock, goerStarts bool) []greetOption { + goer := failingSpawn(nil) + if goerStarts { + goer = func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "go"}, nil } + } + return []greetOption{ + durable.WithRunnerClock[string, string, actorCtx](clk), + durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("fetch", fetchOK)), + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "finisher": finishingChild(), + "goer": goer, + }), + } +} + +// TestRecover_ASpawnsFireArmsATimerAtItsRead proves a timer a parent Fire arms when +// Recover's retried spawn drives it, here the go of a goer that couldn't start live, is +// due 10s after the clock read Recover took, and that the next step journals that read: +// a later Recover, its clock 5s past that read, replays the Fire's arming at it, so the +// timer comes due 5s on, and the service the state invokes is in flight. +func TestRecover_ASpawnsFireArmsATimerAtItsRead(t *testing.T) { + ctx := context.Background() + m := armedMachine() + clk := state.NewFakeClock(epoch) + store, id := durable.NewMemStore(), durable.InstanceID("retried") + if _, err := durable.NewRunner(m, store, armedOptions(clk, false)...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")); err != nil { + t.Fatalf("Start: %v", err) + } + clk.Advance(time.Hour) + h, err := durable.Recover(ctx, m, store, id, armedOptions(clk, true)...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := h.Instance().Current(); got != "armed" { + t.Fatalf("Recover left %q, want armed by the retried goer's go", got) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + clk.Advance(5 * time.Second) + again, err := durable.Recover(ctx, m, store, id, armedOptions(clk, true)...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + clk.Advance(5 * time.Second) + if _, err = again.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := again.Instance().Current(); got != "timedOut" { + t.Fatalf("state = %q, want timedOut 10s after the first Recover's read", got) + } +} + +// TestTick_DropsTheTimerItFiredPastAStartsRead proves a Tick reconciles the Handle's +// timer table at its own clock read, not at an earlier read the step also records, here +// the one Start took arming the timer a starting actor's go entered. The timer's +// transition stays in its state, so no cancel drops it: the tick must, or the checkpoint +// holds it and a recovered Handle fires it again. +func TestTick_DropsTheTimerItFiredPastAStartsRead(t *testing.T) { + ctx := context.Background() + m := tickingMachine() + clk := state.NewFakeClock(epoch) + opts := append(armedOptions(clk, true), durable.WithCheckpointEvery[string, string, actorCtx](1)) + store, id := durable.NewMemStore(), durable.InstanceID("tick") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")) + if err != nil { + t.Fatalf("Start: %v", err) + } + clk.Advance(10 * time.Second) + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v, want the timer to fire", len(results), tickErr) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if results, tickErr := recovered.Tick(ctx); tickErr != nil || len(results) != 0 { + t.Fatalf("recovered Tick = %d results, %v, want none: the timer already fired", len(results), tickErr) + } +} + +// tickingMachine enters "ticking" by the go the goer "going" runs sends as it starts. +// Its 10s timer's transition stays in "ticking", so nothing cancels the timer. +func tickingMachine() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("tick"). + Actor("goer"). + State("going").InvokeActor("goer"). + State("ticking"). + Initial("going"). + Transition("going").On("go").GoTo("ticking"). + Transition("ticking").After(10 * time.Second).On("elapsed").GoTo("ticking"). + Transition("ticking").On("poke").GoTo("ticking"). + Quench() +} + +// TestRecover_DropsTheTimerAReplayedTickFired proves Recover's replay of a tick drops the +// timer it fired from the recovered Handle's timer table at the tick's own clock read, +// not at the earlier read Start took arming it, which the tick's step also records: a +// checkpoint the recovered Handle takes doesn't hold the timer, so a Recover from it +// doesn't fire it again. +func TestRecover_DropsTheTimerAReplayedTickFired(t *testing.T) { + ctx := context.Background() + m := tickingMachine() + clk := state.NewFakeClock(epoch) + store, id := durable.NewMemStore(), durable.InstanceID("replayedTick") + h, err := durable.NewRunner(m, store, armedOptions(clk, true)...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")) + if err != nil { + t.Fatalf("Start: %v", err) + } + clk.Advance(10 * time.Second) + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v, want the timer to fire", len(results), tickErr) + } + checkpointing := append(armedOptions(clk, true), durable.WithCheckpointEvery[string, string, actorCtx](1)) + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the checkpoint: %v", err) + } + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 0 { + t.Fatalf("Tick = %d results, %v, want none: the timer already fired", len(results), tickErr) + } +} + +// TestRecover_KeepsAReplayedActorFiresTimerDeadline proves the deadline of a timer that +// replay arms for an actor-driven parent Fire, here the go a goer sent as Start spawned +// it, is the one the live run armed: a checkpoint the recovered Handle takes persists +// it, so a Recover from that checkpoint fires the timer at its deadline, not before. +func TestRecover_KeepsAReplayedActorFiresTimerDeadline(t *testing.T) { + ctx := context.Background() + m := armedMachine() + clk := state.NewFakeClock(epoch) + store, id := durable.NewMemStore(), durable.InstanceID("deadline") + h, err := durable.NewRunner(m, store, armedOptions(clk, true)...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + clk.Advance(5 * time.Second) + checkpointing := append(armedOptions(clk, true), durable.WithCheckpointEvery[string, string, actorCtx](1)) + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the checkpoint: %v", err) + } + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 0 { + t.Fatalf("Tick 5s before the deadline = %d results, %v, want none", len(results), tickErr) + } + clk.Advance(5 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick at the deadline: %v", err) + } + if got := h.Instance().Current(); got != "timedOut" { + t.Fatalf("state = %q, want timedOut at the deadline", got) + } +} diff --git a/durable/checkpoint_internal_test.go b/durable/checkpoint_internal_test.go index 9459f318..282ee6a3 100644 --- a/durable/checkpoint_internal_test.go +++ b/durable/checkpoint_internal_test.go @@ -151,21 +151,6 @@ func TestMarshalCheckpoint_BadEventErrors(t *testing.T) { } } -// TestTickInstant covers the no-clock-read branch (a tick that fired nothing -// records no read) alongside the happy path. -func TestTickInstant(t *testing.T) { - if _, ok := tickInstant(nil); ok { - t.Fatal("empty entries should report no instant") - } - entries := []state.JournalEntry{ - {Kind: state.JournalClockRead, ClockUnixNano: 42}, - } - got, ok := tickInstant(entries) - if !ok || got.UnixNano() != 42 { - t.Fatalf("tickInstant: ok=%v got=%d", ok, got.UnixNano()) - } -} - // TestCheckpoint_NextStepRoundTrips proves the envelope carries the ordinal after // the checkpoint, and that a checkpoint without one reports zero, the old form. func TestCheckpoint_NextStepRoundTrips(t *testing.T) { diff --git a/durable/clock.go b/durable/clock.go index ad5081f4..7351d69f 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -125,6 +125,7 @@ type replayClock struct { readings []int64 cursor int fallback state.Clock + last time.Time // the reading Now last returned } // newReplayClock builds a replayClock over the recorded readings, falling through @@ -139,11 +140,20 @@ func (c *replayClock) Now() time.Time { c.mu.Lock() defer c.mu.Unlock() if c.cursor < len(c.readings) { - t := time.Unix(0, c.readings[c.cursor]).UTC() + c.last = time.Unix(0, c.readings[c.cursor]).UTC() c.cursor++ - return t + return c.last } - return c.fallback.Now() + c.last = c.fallback.Now() + return c.last +} + +// lastRead returns the reading Now last returned: the instant a replayed timer arming +// or tick computed its deadlines against. +func (c *replayClock) lastRead() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.last } // After delegates to the fallback clock; replay drives elapses through Now + Tick diff --git a/durable/runner.go b/durable/runner.go index 41adbb43..9ea1887a 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -362,6 +362,20 @@ func (h *Handle[S, E, C]) absorbDrivers(ctx context.Context, effects []state.Eff } } +// absorbParentFire arms or cancels the timers and services a parent Fire the actor +// system drove declares, which the system itself leaves alone: the state an actor's +// onDone, onError or message enters runs its timers and services, as one a Fire enters +// does. Replay arms them the same way, in the same order, so the clock reads match. +func (h *Handle[S, E, C]) absorbParentFire(effects []state.Effect) { + ctx := context.Background() + if hasTimerEffect(effects) { + h.absorbTimers(ctx, effects) + } + if h.svc != nil { + h.svc.Absorb(ctx, effects) + } +} + // absorbTimers arms or cancels the step's delayed (`after`) timers on the kernel // scheduler and mirrors the same arming into the Handle's own timer table, so each // armed timer's absolute deadline is available to persist at a checkpoint. It must @@ -430,19 +444,6 @@ func (h *Handle[S, E, C]) armTimersFrom(effects []state.Effect, now time.Time) { } } -// tickInstant returns the single clock instant a tick's recorded reads share (the -// FakeClock does not advance within a tick; a SystemClock's intra-tick drift is -// sub-timer). It reads the first recorded JournalClockRead. ok is false when the -// tick recorded no clock read (it fired nothing), so the caller skips reconciliation. -func tickInstant(entries []state.JournalEntry) (time.Time, bool) { - for _, e := range entries { - if e.Kind == state.JournalClockRead { - return time.Unix(0, e.ClockUnixNano).UTC(), true - } - } - return time.Time{}, false -} - // dropFiredTimers removes from the Handle's timer table the timers a Tick fired, so // a checkpoint taken after the tick does not persist an already-fired timer. The // scheduler removes a due timer before re-firing it; the Handle mirrors that by @@ -549,10 +550,28 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // configuration's actors, so an actor declared on the very first state is running // before the first DeliverToActor. The actor buffer journals each parent // transition a delivery drives for replay. A machine with no actor palette wired - // spawns no actor and records no actor entries. + // spawns no actor and records no actor entries. A parent Fire a starting actor + // drives arms its state's timers and services on the Handle's drivers. actorBuf := make([]state.JournalEntry, 0) actors, actorFires := r.newActorSystem(inst) + h := &Handle[S, E, C]{ + runner: r, + id: id, + inst: inst, + nextStep: 0, + sched: state.NewScheduler(inst), + recClock: recClock, + timers: map[string]pendingTimer{}, + svc: svc, + svcBuf: &svcBuf, + actors: actors, + actorBuf: &actorBuf, + actorFires: actorFires, + lock: make(chan struct{}, 1), + out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, + } if actors != nil { + actorFires.arm = h.absorbParentFire actorFires.attempt(inst.StartEffects()) actors.Absorb(ctx, inst.StartEffects()) } @@ -566,31 +585,14 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt return nil, fmt.Errorf("durable: starting %q: %w", id, refused) } // The actors that started are seen running, so one later stopped counts as ended. - seen := map[string]bool{} + h.seen = map[string]bool{} if actors != nil { for _, id := range actors.IDs() { - seen[id] = true + h.seen[id] = true } } - - return &Handle[S, E, C]{ - runner: r, - id: id, - inst: inst, - nextStep: 0, - sched: state.NewScheduler(inst), - recClock: recClock, - timers: map[string]pendingTimer{}, - svc: svc, - svcBuf: &svcBuf, - actors: actors, - actorBuf: &actorBuf, - actorFires: actorFires, - seen: seen, - pending: startFires, - lock: make(chan struct{}, 1), - out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, - }, nil + h.pending = startFires + return h, nil } // newServiceRunner builds the kernel host driver for invoked services bound to @@ -624,6 +626,11 @@ func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) (*state. // them can check and record them, and the actors it spawned, so an actor spawned and // stopped inside one step still counts as having run. type parentFires[S comparable] struct { + // arm, when set, arms the timers and services a parent Fire's effects declare, as a + // host Fire's absorb does: the actor system handles only their actors. It's set + // before any spawn and runs on the goroutine driving the system. + arm func(effects []state.Effect) + mu sync.Mutex fires []state.ParentFire[S] spawned map[string]bool // actors whose latest spawn this step started @@ -690,6 +697,9 @@ func (p *parentFires[S]) note(pf state.ParentFire[S]) { p.failed[pf.ActorID] = true } p.mu.Unlock() + if p.arm != nil { + p.arm(pf.Result.Effects) + } // The system absorbs a parent Fire's effects next, which spawns what they declare. p.attempt(pf.Result.Effects) } @@ -923,7 +933,11 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro if err := h.refuse(ctx); err != nil { return nil, err } + // The tick's first read lands past what the buffer holds now, which can include reads + // of an earlier Start's or Recover's spawns, recorded with this step. + mark := h.recClock.markBuf() results := h.sched.Tick(h.stepContext(ctx)) + now, haveNow := h.recClock.armReadingAt(mark) // 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. @@ -941,7 +955,7 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro // (a FakeClock advances only between ticks; a SystemClock's intra-tick drift is // sub-timer), so the tick's recorded reads share one instant: use it for both the // drop (timers due at or before it fired) and any chained re-arm. - if now, ok := tickInstant(rec.Entries); ok { + if haveNow { h.dropFiredTimers(now) for i := range results { h.armTimersFrom(results[i].Effects, now) @@ -1332,7 +1346,10 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } rec := &tail[i] - did, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec) + // The mirror tracks the still-pending timers in armed as replay arms, cancels and + // fires them, with deadlines drawn from the recorded clock reads, not the live + // wall clock. + did, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, &armMirror{armed: armed, clock: repClock}) if err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } @@ -1342,25 +1359,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S if rec.UnstartedActors != nil { unstarted = rec.UnstartedActors } - now, haveNow := tickInstant(rec.Entries) - // Mirror the step into the armed table so it tracks the still-pending set, with - // deadlines drawn from the step's recorded clock read, not the live wall clock: - // a tick drops the timers it fired and arms any a chained transition scheduled, - // and a plain event arms the timers its Fire armed. - if rec.Tick && haveNow { - for id, pt := range armed { - if !pt.due.After(now) { - delete(armed, id) - } - } - for ri := range did.tick { - mirrorArmed(armed, did.tick[ri].Effects, now) - } - } if did.fired != nil { - if haveNow && hasTimerEffect(did.fired.Effects) { - mirrorArmed(armed, did.fired.Effects, now) - } // 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 @@ -1376,51 +1375,11 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // readings): they belong to no new step and must not leak into the next Fire. buf = buf[:0] - // Arm the live actors at the resume point from the final configuration's - // StartEffects: this spawns exactly the actors running where replay left the - // parent (for example the next child in a chain, after the prior one settled), - // so a subsequent DeliverToActor finds them — without re-instantiating an actor - // the recorded run already settled, which replay reconstructed by re-firing the - // parent rather than re-running behavior. + // Re-arming reads the clock past the journal, and so can arming a timer for a parent + // Fire an actor Recover spawns drives, which the next step records: re-arm before the + // spawns, so the re-arm's read can be dropped while theirs are kept, and so one of + // their Fires can cancel a re-armed timer. // - // An actor that was running sends the parent nothing as it spawns again: the journal - // holds what its start drove. - if actors != nil { - // With no recorded ended set, Recover spawns every declared actor, as it did - // before the set was recorded. - var endedIDs []string - if ended != nil { - endedIDs = ended.IDs - } - spawns := startsExcept(inst.StartEffects(), endedIDs, func(sp state.SpawnActor) string { return sp.ID }) - actorFires.attempt(spawns) - respawn(ctx, actors, spawns, unstarted) - } - // A parent Fire a newly started actor drove (a message it sent as it started, or a - // failed spawn's onError) applied to the instance past its journal, so the next step - // journals it, ahead of its own work. One a context's ending refused never applied, - // and the Handle would hold state the journal can't reach, so Recover fails. - recoverFires := actorFires.take() - if refused := refusedByContext(parentFireErrs(recoverFires)...); refused != nil { - return nil, fmt.Errorf("durable: recovering %q: %w", id, refused) - } - // The journal's ended actors stay ended, and seen, so the next step records a set - // only when it changes them. - seen := map[string]bool{} - var endedRec, unstartedRec recordedSet - if actors != nil { - for _, id := range actors.IDs() { - seen[id] = true - } - endedRec.note(ended) - unstartedRec.note(unstarted) - if ended != nil { - for _, id := range ended.IDs { - seen[id] = true - } - } - } - // Re-arm any timer that was pending at the checkpoint but whose arming // ScheduleAfter was compacted out of the tail, so it survives compaction: the // tail replay could not re-arm it (its arm is gone), so re-arm it here at its @@ -1470,10 +1429,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S } } } - if err := ctx.Err(); err != nil { - return nil, fmt.Errorf("durable: recovering %q: %w", id, err) - } - return &Handle[S, E, C]{ + // A parent Fire the actors Recover spawns drive arms its state's timers and services + // on this Handle's drivers. + h := &Handle[S, E, C]{ runner: r, id: id, inst: inst, @@ -1486,13 +1444,60 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S actors: actors, actorBuf: &actorBuf, actorFires: actorFires, - ended: endedRec, - unstarted: unstartedRec, - seen: seen, - pending: recoverFires, lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, - }, nil + } + + // Arm the live actors at the resume point from the final configuration's + // StartEffects: this spawns exactly the actors running where replay left the + // parent (for example the next child in a chain, after the prior one settled), + // so a subsequent DeliverToActor finds them — without re-instantiating an actor + // the recorded run already settled, which replay reconstructed by re-firing the + // parent rather than re-running behavior. + // + // An actor that was running sends the parent nothing as it spawns again: the journal + // holds what its start drove. + if actors != nil { + // With no recorded ended set, Recover spawns every declared actor, as it did + // before the set was recorded. + var endedIDs []string + if ended != nil { + endedIDs = ended.IDs + } + spawns := startsExcept(inst.StartEffects(), endedIDs, func(sp state.SpawnActor) string { return sp.ID }) + actorFires.arm = h.absorbParentFire + actorFires.attempt(spawns) + respawn(ctx, actors, spawns, unstarted) + } + // A parent Fire a newly started actor drove (a message it sent as it started, or a + // failed spawn's onError) applied to the instance past its journal, so the next step + // journals it, ahead of its own work. One a context's ending refused never applied, + // and the Handle would hold state the journal can't reach, so Recover fails. + recoverFires := actorFires.take() + if refused := refusedByContext(parentFireErrs(recoverFires)...); refused != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, refused) + } + // The journal's ended actors stay ended, and seen, so the next step records a set + // only when it changes them. + h.seen = map[string]bool{} + if actors != nil { + for _, id := range actors.IDs() { + h.seen[id] = true + } + h.ended.note(ended) + h.unstarted.note(unstarted) + if ended != nil { + for _, id := range ended.IDs { + h.seen[id] = true + } + } + } + + h.pending = recoverFires + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } + return h, nil } // eventPayload is the recorded form of a WithEventData payload. @@ -1738,17 +1743,20 @@ type replayed[S comparable] struct { // 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 and effect re-dispatch on top. +// journal with it; Recover adds its deadline table, which mirror tracks, and effect +// re-dispatch on top. A nil mirror tracks no deadlines. // // - Parent Fires a Start's or Recover's spawns drove, recorded with the next step, // re-fire first, before the step's own work. // - An actor delivery re-fires each parent transition the delivery drove, in fire // order, with the recorded done-data or error, so the kernel re-derives the same // onDone / onError (or message) transition. A Fire's or settle's absorb-driven -// parent Fires, such as a spawned actor's onError, re-fire after its own work. +// parent Fires, such as a spawned actor's onError, re-fire after its own work. Each +// re-arms the timers and services its state declares, as the live Fire did. // - A service settlement re-settles each recorded outcome through the same settle // seam, in settle order; the settle absorbs its own follow-on StartService -// effects, so a chained invoke arms its successor for the next entry. +// effects, so a chained invoke arms its successor for the next entry, and its +// timers are re-armed as RunService armed them. // - A tick barrier ticks the replay clock, which returns the recorded readings, so // the same deadlines come due and the same timers fire at their recorded instants. // - A plain event re-fires it with its recorded event data, then re-arms its timers @@ -1761,6 +1769,7 @@ func replayRecord[S comparable, E comparable, C any]( sched *state.Scheduler[S, E, C], svc *state.ServiceRunner[S, E, C], rec *Record, + mirror *armMirror, ) (replayed[S], error) { var out replayed[S] before, rest, err := splitActorEntries(rec) @@ -1768,7 +1777,7 @@ func replayRecord[S comparable, E comparable, C any]( return out, 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, rec, before); err != nil { + if err := replayActors(ctx, inst, cfg, sched, svc, rec, before, mirror); err != nil { return out, err } switch { @@ -1785,33 +1794,91 @@ func replayRecord[S comparable, E comparable, C any]( if res.Err != nil { return out, fmt.Errorf("replaying step %d: %w", rec.Step, res.Err) } - if hasTimerEffect(res.Effects) { - sched.Absorb(ctx, res.Effects) - } - if svc != nil { - svc.Absorb(ctx, res.Effects) - } + replayArm(ctx, sched, svc, res.Effects, mirror) out.fired = &res case hasServiceEntry(rec): for _, entry := range serviceEntries(rec) { - if err := replayService(ctx, svc, entry); err != nil { + effects, err := replayService(ctx, svc, entry) + if err != nil { return out, fmt.Errorf("at step %d: %w", rec.Step, err) } + // The settle armed its own services; arm its timers, as RunService did. + replayArm(ctx, sched, nil, effects, mirror) } case rec.Tick: out.tick = sched.Tick(ctx) + mirrorTick(mirror, out.tick) } // 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 out, replayActors(ctx, inst, cfg, rec, rest) + return out, replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror) } -// replayActors re-fires recorded parent transitions, in order. -func replayActors[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], rec *Record, entries []state.JournalEntry) error { +// replayActors re-fires recorded parent transitions, in order, arming the timers and +// services each declares, as the live run did. +func replayActors[S comparable, E comparable, C any]( + ctx context.Context, + inst *state.Instance[S, E, C], + cfg *runnerConfig[S, E, C], + sched *state.Scheduler[S, E, C], + svc *state.ServiceRunner[S, E, C], + rec *Record, + entries []state.JournalEntry, + mirror *armMirror, +) error { for _, entry := range entries { - if err := replayActor(ctx, inst, cfg.eventCodec, entry); err != nil { + effects, err := replayActor(ctx, inst, cfg.eventCodec, entry) + if err != nil { return fmt.Errorf("at step %d: %w", rec.Step, err) } + replayArm(ctx, sched, svc, effects, mirror) } return nil } + +// 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) { + if hasTimerEffect(effects) { + sched.Absorb(ctx, effects) + mirror.arm(effects) + } + if svc != nil { + svc.Absorb(ctx, effects) + } +} + +// armMirror tracks the timers a Recover's replay leaves pending, with the deadlines the +// scheduler computed from the recorded clock reads, so the Handle's timer table starts +// with them. A nil mirror, as a time-travel read uses, tracks nothing. +type armMirror struct { + armed map[string]pendingTimer + clock *replayClock +} + +// arm folds a replayed absorb's timer effects into the table, at the reading the +// scheduler's absorb just took. +func (m *armMirror) arm(effects []state.Effect) { + if m == nil { + return + } + mirrorArmed(m.armed, effects, m.clock.lastRead()) +} + +// mirrorTick drops from m the timers a replayed tick fired and arms any a chained +// transition scheduled, at the instant the tick read: the tick's reads share one instant. +func mirrorTick[S comparable](m *armMirror, results []state.FireResult[S]) { + if m == nil { + return + } + now := m.clock.lastRead() + for id, pt := range m.armed { + if !pt.due.After(now) { + delete(m.armed, id) + } + } + for i := range results { + mirrorArmed(m.armed, results[i].Effects, now) + } +} diff --git a/durable/service.go b/durable/service.go index 6d74e4c3..733db64c 100644 --- a/durable/service.go +++ b/durable/service.go @@ -156,7 +156,9 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire } step := h.nextStep - rec := Record{Step: step, Entries: append(h.drainServices(), driven...)} + // 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 } @@ -195,32 +197,35 @@ func recordServiceOutcome(id string, lastResult func() (any, bool), lastErr erro // the recorded payload and calls SettleDone (with the recorded result) or // SettleError (with the reconstructed error), so the kernel re-fires the same // onDone / onError event with the same data and re-derives identical context. It -// reports an error only when the recorded entry cannot be decoded or names no -// in-flight service (a corrupt or mis-ordered journal). -func replayService[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], entry state.JournalEntry) error { +// returns the settle's effects, so the caller arms the timers its state declares, as +// the live RunService did. It reports an error only when the recorded entry cannot be +// decoded or names no in-flight service (a corrupt or mis-ordered journal). +func replayService[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], entry state.JournalEntry) ([]state.Effect, error) { if svc == nil { - return errors.New("durable: replaying a service result requires a service registry (supply WithServiceRegistry)") + return nil, errors.New("durable: replaying a service result requires a service registry (supply WithServiceRegistry)") } var sp serviceResultPayload if err := json.Unmarshal(entry.Payload, &sp); err != nil { - return fmt.Errorf("durable: decoding recorded service %q outcome: %w", entry.CorrelationID, err) + return nil, fmt.Errorf("durable: decoding recorded service %q outcome: %w", entry.CorrelationID, err) } if sp.Error != nil { - if _, ok := svc.SettleError(ctx, entry.CorrelationID, errors.New(*sp.Error)); !ok { - return fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) + res, ok := svc.SettleError(ctx, entry.CorrelationID, errors.New(*sp.Error)) + if !ok { + return nil, fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) } - return nil + return res.Effects, nil } var result any if len(sp.Result) > 0 { if err := json.Unmarshal(sp.Result, &result); err != nil { - return fmt.Errorf("durable: decoding recorded service %q result: %w", entry.CorrelationID, err) + return nil, fmt.Errorf("durable: decoding recorded service %q result: %w", entry.CorrelationID, err) } } - if _, ok := svc.SettleDone(ctx, entry.CorrelationID, result); !ok { - return fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) + res, ok := svc.SettleDone(ctx, entry.CorrelationID, result) + if !ok { + return nil, fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) } - return nil + return res.Effects, nil } // serviceEntries returns the recorded service outcomes carried by a single diff --git a/durable/timetravel.go b/durable/timetravel.go index 3a23ed5b..dd52c14f 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -245,7 +245,7 @@ func replayThrough[S comparable, E comparable, C any]( } // A domain effect is never dispatched here: a time-travel read applies no // side effect. - if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i]); err != nil { + if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil); err != nil { return err } } From b4da79cd9b8619e2b5a470dba0045dfbcabbf93d Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 13 Nov 2026 20:03:09 -0700 Subject: [PATCH 21/38] fix(state): don't escalate a respawn's nested start failure again During AbsorbRespawn, a nested actor whose spawn failed, or that crashed, with no onError escalated again on every Recover, though the live run had already reported it. Escalation now follows the quiet rule: a failure the journal's run already saw stays quiet, and a respawned actor's own new failure still escalates. Signed-off-by: Ray Karnes --- state/CHANGELOG.md | 6 ++-- state/actor_respawn_test.go | 72 +++++++++++++++++++++++++++++++++++++ state/actor_system.go | 26 ++++++++------ 3 files changed, 91 insertions(+), 13 deletions(-) diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index eb292417..225ff6ee 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -25,8 +25,10 @@ counts as an additive (minor) versus breaking (major) change. Use the doesn't reach the parent, neither a message sent to the parent nor the onDone or onError of a nested actor it spawns. The onError of a respawn that can't start, and the onDone or onError of a respawned actor that settles as the others start, still - fire the parent, since that actor was running. The durable runner's `Recover` uses it - for the actors that were running. It's additive, within v1.1.0. + fire the parent, since that actor was running. A nested actor's failure with no + onError doesn't escalate again, since its start already escalated it; a respawned + actor's own failure with no onError does. The durable runner's `Recover` uses it for + the actors that were running. It's additive, within v1.1.0. - **`FireEventData`** reports the payload a `WithEventData` option carries, so a host that records a Fire can persist it. It's additive, so the next release is v1.1.0. - **Callbacks get the step's context.** `GuardCtx`, `ActionCtx` and `AssignCtx` have a new diff --git a/state/actor_respawn_test.go b/state/actor_respawn_test.go index 6c43560c..13d52f72 100644 --- a/state/actor_respawn_test.go +++ b/state/actor_respawn_test.go @@ -259,3 +259,75 @@ func TestActorSystem_AbsorbRespawn_QuietEndsWithIt(t *testing.T) { t.Fatalf("a delivery after AbsorbRespawn left the parent in %q, want hellod: its hello should reach the parent", got) } } + +// crasher is an actor that panics when it's delivered "crash". +type crasher struct{} + +func (crasher) DeliverFire(_ context.Context, ev any) (bool, any) { + if ev == "crash" { + panic("crash") + } + return false, nil +} +func (crasher) ChildEffects() []state.Effect { return nil } +func (crasher) Output() any { return nil } + +// TestActorSystem_AbsorbRespawn_DoesNotEscalateANestedStartFailureAgain proves a nested +// actor's failure with no onError, one whose spawn can't start or one that crashes as +// the respawned actor starts, escalates under Absorb but not again under AbsorbRespawn: +// it's part of the respawned actor's start, which escalated it when it first happened. +// A respawned actor whose own spawn fails now, with no onError, still escalates. +func TestActorSystem_AbsorbRespawn_DoesNotEscalateANestedStartFailureAgain(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("escalate"). + Actor("host"). + State("hosting").InvokeActor("host"). + Initial("hosting"). + Quench() + starts := map[string][]state.Effect{ + "fails": {state.SpawnActor{ID: "child", Src: state.Ref{Name: "broken"}}}, + "crashes": { + state.SpawnActor{ID: "child", Src: state.Ref{Name: "crasher"}}, + state.SendTo{TargetID: "child", Event: "crash"}, + }, + } + build := func(how string, hostStarts bool, escalations *int) (*state.Instance[string, string, *trec], *state.ActorSystem[string, string, *trec]) { + inst := m.Cast(&trec{}, state.WithInitialState("hosting")) + sys := state.NewActorSystem(inst). + WithEscalationHandler(func(context.Context, *state.ActorEscalation) { *escalations++ }) + sys.Register("host", func(map[string]any) (state.ActorInstance, error) { + if !hostStarts { + return nil, errors.New("can't start") + } + return &starter{start: starts[how]}, nil + }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("can't start") }) + sys.Register("crasher", func(map[string]any) (state.ActorInstance, error) { return crasher{}, nil }) + return inst, sys + } + for _, how := range []string{"fails", "crashes"} { + t.Run(how, func(t *testing.T) { + var live int + inst, sys := build(how, true, &live) + sys.Absorb(ctx, inst.StartEffects()) + if live != 1 { + t.Fatalf("Absorb escalated %d times, want once", live) + } + var respawned int + inst, sys = build(how, true, &respawned) + sys.AbsorbRespawn(ctx, inst.StartEffects()) + if respawned != 0 { + t.Fatalf("AbsorbRespawn escalated %d times, want none: the nested failure is part of the host's start", respawned) + } + }) + } + t.Run("respawned actor fails", func(t *testing.T) { + var n int + _, sys := build("fails", false, &n) + // A spawn with no onError, as an actor's own spawns are. + sys.AbsorbRespawn(ctx, []state.Effect{state.SpawnActor{ID: "host", Src: state.Ref{Name: "host"}}}) + if n != 1 { + t.Fatalf("AbsorbRespawn escalated %d times, want once: the respawned actor's own failure is new", n) + } + }) +} diff --git a/state/actor_system.go b/state/actor_system.go index 2eaea96b..87ea6ddd 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -311,10 +311,11 @@ func (s *ActorSystem[S, E, C]) AbsorbFor(ctx context.Context, event any, effects // so WithParentFireObserver doesn't see it. What the earlier start can't have driven // still fires the parent, since each actor in effects was running: the onError of one // whose spawn fails now, and the onDone or onError of one that settles as the others -// start. A nested actor's failure with no onError still escalates. The effects such a Fire drives absorb as under Absorb: an actor -// its state spawns, or one it sends to, reaches the parent. Its other effects absorb as -// under Absorb. Don't drive the system from another goroutine while AbsorbRespawn runs: -// a parent Fire that one drives would be dropped too. +// start. A nested actor's failure with no onError doesn't escalate again either, while +// one in effects that fails now does. The effects such a Fire drives absorb as under +// Absorb: an actor its state spawns, or one it sends to, reaches the parent. Its other +// effects absorb as under Absorb. Don't drive the system from another goroutine while +// AbsorbRespawn runs: a parent Fire that one drives would be dropped too. func (s *ActorSystem[S, E, C]) AbsorbRespawn(ctx context.Context, effects []Effect) { respawned := map[string]bool{} for _, eff := range effects { @@ -471,17 +472,19 @@ func (s *ActorSystem[S, E, C]) spawn(ctx context.Context, e SpawnActor) { // failure escalates to the parent as a typed ActorEscalation rather than being // silently swallowed (the G3 default), so a spawn that cannot start is never lost. func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err error) { - ev, ok := e.OnError.(E) - if !ok { - s.escalate(ctx, &runningActor[E]{ref: ActorRef{ID: e.ID, SystemID: e.SystemID, Src: e.Src.Name}}, "", err) - return - } s.mu.Lock() drop, lift := s.hearingLocked(e.ID) s.mu.Unlock() + // A failure the start AbsorbRespawn is repeating was routed or escalated when it + // first happened. if drop { return } + ev, ok := e.OnError.(E) + if !ok { + s.escalate(ctx, &runningActor[E]{ref: ActorRef{ID: e.ID, SystemID: e.SystemID, Src: e.Src.Name}}, "", err) + return + } if lift { prev := s.setQuiet(false) defer s.setQuiet(prev) @@ -818,8 +821,9 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any // G3 default: an unhandled child FAILURE (no onError wired) escalates to the // parent as a typed, observable ActorEscalation rather than being silently // swallowed. A clean completion with no onDone is still a fire-and-forget - // no-op — only a failure escalates. - if err != nil { + // no-op — only a failure escalates. A failure the start AbsorbRespawn is + // repeating escalated when it first happened. + if err != nil && !drop { s.escalate(ctx, ra, parentID, err) } return FireResult[S]{}, false From ba07ed08aae3ece578f75802ecb77a1b60eebf8f Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 13 Nov 2026 20:03:09 -0700 Subject: [PATCH 22/38] fix(durable): track settled services, drop fired timers by id, replay old journals as before - A checkpoint records the services that settled, not every declared service that isn't pending. A service a timer's state invoked never started, and Recover used to skip it for good. Re-entering or leaving a state forgets its settle. - Tick drops each timer the scheduler fired, by id, live and on replay. A timer that came due between a tick's clock reads, or a chained zero-delay timer, no longer stays in the table to fire again after Recover. - A journal written before actor-driven Fires armed timers and services replays without arming them, so its clock reads line up as they did. - An actor-driven Fire's arming gets the step's context; actor sets are computed each step; Recover builds one replay mirror. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 16 +- durable/actor.go | 5 +- durable/actor_driven_drivers_test.go | 155 ++++++++++++++++++ durable/actor_sets_internal_test.go | 19 +-- durable/checkpoint.go | 9 +- durable/clock.go | 11 ++ durable/respawn_nested_test.go | 79 +++++++++ durable/runner.go | 231 +++++++++++++++++++-------- durable/service.go | 11 ++ durable/service_test.go | 106 +++++++++++- durable/store.go | 6 +- durable/timer_checkpoint_test.go | 111 +++++++++++++ durable/timetravel.go | 9 +- 13 files changed, 671 insertions(+), 97 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 014646d3..1d50c463 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -201,12 +201,16 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. The actor system armed only that state's actors, so its service wasn't in flight, and `RunService` reported none, and its timer never fired; a checkpoint then recorded the service as settled, so `Recover` didn't start it either. Such a Fire now arms them, - live, at `Start` and `Recover`, and on replay, as a host `Fire` does. A service's + live, at `Start` and `Recover`, and on replay, as a host `Fire` does. Replay arms them + only in a journal this version wrote, which records the unstarted actors: one an + older version wrote took no clock read for them, and replays as it did. A service's settle re-arms its state's timers on replay too, and `DeliverToActor` and `RunService` now journal the clock reads their step took, so a checkpoint on that step can't leave a read for the next to replay. `Recover` re-arms a checkpoint's timers before it - spawns the running actors, so a Fire one of theirs drives can cancel one, and a `Tick` - drops the timers it fired at its own clock read, not an earlier one its step records. + spawns the running actors, so a Fire one of theirs drives can cancel one. A `Tick` + drops from the timers a checkpoint records exactly the ones it fired, live and on + replay: one that came due between its clock reads, and a chained one it armed and + fired, used to stay, so a `Recover` from a later checkpoint fired it again. - **A delivery journals each parent Fire under the actor that drove it,** where it used to record every one under the actor delivered to. It no longer copies the instance's history twice per delivery to do it. @@ -221,8 +225,10 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. checkpoint taken after such a settle, on a compound state whose onDone went to a child, or on a leaf state that stayed put, left the service in flight again on recovery, so `RunService` ran it a second time. A checkpoint now records the declared services that - weren't in flight, and `Recover` doesn't start them. A checkpoint from before this - records none, and `Recover` starts every declared service, as before. + settled while their state stayed active, and `Recover` doesn't start them. One that + never settled, such as one whose state a `Tick` entered or re-entered (a `Tick` + starts no service), isn't recorded, so `Recover` starts it, as before. A checkpoint + from before this records none, and `Recover` starts every declared service. - **A parent Fire that middleware denied replays.** Denied before the kernel saw it, it is recorded as refused, and replay meets the same refusal instead of failing `Recover`. - **A panic during a step fails the Handle.** A panic in host code under the step lock, diff --git a/durable/actor.go b/durable/actor.go index f0ab4586..f5fe03a6 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -132,7 +132,10 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef return false, fmt.Errorf("durable: no actor palette wired for %q (supply WithActorPalette)", h.id) } - delivered := h.actors.Deliver(h.stepContext(ctx), ref, event) + stepCtx := h.stepContext(ctx) + restore := h.actorFires.driving(stepCtx) + delivered := h.actors.Deliver(stepCtx, ref, event) + restore() fires := h.actorFires.take() if !delivered { return false, nil diff --git a/durable/actor_driven_drivers_test.go b/durable/actor_driven_drivers_test.go index e242941e..d72763b6 100644 --- a/durable/actor_driven_drivers_test.go +++ b/durable/actor_driven_drivers_test.go @@ -277,3 +277,158 @@ func TestRecover_KeepsAReplayedActorFiresTimerDeadline(t *testing.T) { t.Fatalf("state = %q, want timedOut at the deadline", got) } } + +// TestRecover_StartsAServiceAnActorsMessageReentered proves a service that settled, then +// started again because an actor's message re-entered its state, is recorded as in +// flight, not settled, so Recover starts it: by a checkpoint the live run took, and by +// one a recovered Handle took after replaying the run. +func TestRecover_StartsAServiceAnActorsMessageReentered(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[actorCtx]("relay"). + Service("fetch", fetchOK). + Actor("pinger"). + SuperState("outer").InvokeActor("pinger"). + SubState("fetching").Invoke("fetch", state.WithInvokeOnDone("fetched")). + Initial("fetching"). + EndSuperState(). + Initial("outer"). + Transition("fetching").On("fetched").GoTo("fetching"). + Transition("fetching").On("pong").GoTo("fetching").Reenter(). + Transition("fetching").On("poke").GoTo("fetching"). + Quench() + svcID := state.InvokeID("relay", "fetching", 0) + for _, where := range []string{"live checkpoint", "replayed checkpoint"} { + t.Run(where, func(t *testing.T) { + var msgs int64 + opts := []greetOption{ + durable.WithServiceRegistry[string, string, actorCtx](state.NewRegistry[actorCtx]().Service("fetch", fetchOK)), + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{"pinger": pingerChild(&msgs)}), + } + checkpointing := append(opts[:len(opts):len(opts)], durable.WithCheckpointEvery[string, string, actorCtx](1)) + live := checkpointing + if where == "replayed checkpoint" { + live = opts + } + store, id := durable.NewMemStore(), durable.InstanceID("relay") + h, err := durable.NewRunner(m, store, live...).Start(ctx, id, actorCtx{}, state.WithInitialState("fetching")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, ran, runErr := h.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v", ran, runErr) + } + if found, deliverErr := h.DeliverToActorByID(ctx, state.ActorID("relay", "outer", 0), "ping"); !found || deliverErr != nil { + t.Fatalf("DeliverToActorByID = %v, %v", found, deliverErr) + } + if where == "replayed checkpoint" { + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the journal: %v", err) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, checkpointing...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, runErr := recovered.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService after Recover = %v, %v, want the service the pong restarted in flight", ran, runErr) + } + }) + } +} + +// TestRecover_ReplaysAnOlderJournalsActorFireWithoutArming proves a journal an older +// version wrote, which didn't arm the timers an actor-driven parent Fire's state +// declares and took no clock read for them, replays as it did, in Recover and in +// StateAt: the Fire arms nothing, so it doesn't take the read a later step recorded, +// and the timer that step armed comes due at its recorded deadline, when a recorded +// Tick fires it. The journal is this version's, put back in the older shape: no clock +// read for the onDone's timer, and no recorded actor sets. +func TestRecover_ReplaysAnOlderJournalsActorFireWithoutArming(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[actorCtx]("older"). + Actor("finisher"). + State("working").InvokeActor("finisher", state.WithInvokeOnDone("childDone")). + State("armed"). + State("waiting"). + State("timedOut"). + State("late"). + Initial("working"). + Transition("working").On("childDone").GoTo("armed"). + Transition("armed").After(10 * time.Second).On("elapsed").GoTo("timedOut"). + Transition("armed").On("leave").GoTo("waiting"). + Transition("waiting").After(30 * time.Second).On("overdue").GoTo("late"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []greetOption{ + durable.WithRunnerClock[string, string, actorCtx](clk), + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{"finisher": finishingChild()}), + } + written, id := durable.NewMemStore(), durable.InstanceID("older") + h, err := durable.NewRunner(m, written, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if found, deliverErr := h.DeliverToActorByID(ctx, state.ActorID("older", "working", 0), "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActorByID = %v, %v", found, deliverErr) + } + clk.Advance(5 * time.Second) + if _, err = h.Fire(ctx, "leave"); err != nil { + t.Fatalf("Fire(leave): %v", err) + } + clk.Advance(30 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := h.Instance().Current(); got != "late" { + t.Fatalf("live state = %q, want late", got) + } + + baseline, tail, err := written.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(tail) != 3 { + t.Fatalf("journal holds %d Records, want the delivery, the leave and the tick", len(tail)) + } + older := durable.NewMemStore() + if err = older.Checkpoint(ctx, id, baseline, durable.BaselineStep); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + for i, rec := range tail { + rec.EndedActors, rec.UnstartedActors = nil, nil + if i == 0 { + // The older version armed nothing for the onDone, so took no read. + var entries []state.JournalEntry + for _, e := range rec.Entries { + if e.Kind != state.JournalClockRead { + entries = append(entries, e) + } + } + if len(entries) == len(rec.Entries) { + t.Fatal("the delivery recorded no clock read for the onDone's timer") + } + rec.Entries = entries + } + if _, err = older.Append(ctx, id, rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + + view, err := durable.StateAt(ctx, m, older, id, tail[2].Step+tail[2].TickSteps, opts...) + if err != nil { + t.Fatalf("StateAt: %v", err) + } + if got := view.Instance().Current(); got != "late" { + t.Fatalf("StateAt state = %q, want late: the recorded Tick should fire waiting's timer", got) + } + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "late" { + t.Fatalf("recovered state = %q, want late: the recorded Tick should fire waiting's timer", got) + } +} diff --git a/durable/actor_sets_internal_test.go b/durable/actor_sets_internal_test.go index 1dc5707f..2b21c129 100644 --- a/durable/actor_sets_internal_test.go +++ b/durable/actor_sets_internal_test.go @@ -11,10 +11,9 @@ type setsCtx struct { Notes []string `json:"notes"` } -// TestActorSets_SkipsAStepThatTouchedNoActor proves a step that spawned nothing and -// changed neither the configuration nor the running actors gets the last actor sets -// back without recomputing them, while a step that moves the configuration recomputes. -func TestActorSets_SkipsAStepThatTouchedNoActor(t *testing.T) { +// TestActorSets_FollowTheActorsState proves a step that touched no actor leaves both +// actor sets as they were, while a step that leaves the actor's state ends it. +func TestActorSets_FollowTheActorsState(t *testing.T) { ctx := context.Background() child := state.ForgeFor[setsCtx]("child"). State("working"). @@ -42,18 +41,20 @@ func TestActorSets_SkipsAStepThatTouchedNoActor(t *testing.T) { t.Fatalf("Fire(poke): %v", err) } ended, unstarted := h.actorSets() + if len(ended.IDs) != 0 || len(unstarted.IDs) != 0 { + t.Fatalf("sets = %v, %v, want none: the actor is running", ended.IDs, unstarted.IDs) + } if _, err = h.Fire(ctx, "poke"); err != nil { t.Fatalf("Fire(poke): %v", err) } - again, againUnstarted := h.actorSets() - if again != ended || againUnstarted != unstarted { - t.Fatal("a step that touched no actor recomputed the actor sets") + if ended, unstarted = h.actorSets(); len(ended.IDs) != 0 || len(unstarted.IDs) != 0 { + t.Fatalf("sets = %v, %v after a step that touched no actor, want none", ended.IDs, unstarted.IDs) } if _, err = h.Fire(ctx, "leave"); err != nil { t.Fatalf("Fire(leave): %v", err) } - if moved, _ := h.actorSets(); moved == ended { - t.Fatal("a step that left the actor's state reused the old actor sets") + if ended, unstarted = h.actorSets(); len(ended.IDs) != 0 || len(unstarted.IDs) != 0 { + t.Fatalf("sets = %v, %v after leaving the actor's state, want none: idle declares no actor", ended.IDs, unstarted.IDs) } } diff --git a/durable/checkpoint.go b/durable/checkpoint.go index b38b709b..7377041e 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -92,10 +92,11 @@ type checkpointEnvelope struct { // UnstartedActors is the set of declared actors that weren't running and hadn't // ended at the checkpoint (see Record.UnstartedActors). Nil means none was recorded. UnstartedActors *ActorSet `json:"unstartedActors,omitempty"` - // EndedServices are the invoked services the active states declared that weren't in - // flight at the checkpoint, sorted: each settled in the current activation of the - // state that declares it, so Recover doesn't start it again. None, as in a Start - // baseline or an older checkpoint, means Recover starts every declared service. + // EndedServices are the invoked services the active states declared that had settled + // in the current activation of the state that declares each, sorted, so Recover + // doesn't start them again. A declared service that wasn't in flight but never + // settled isn't one. None, as in a Start baseline or an older checkpoint, means + // Recover starts every declared service. EndedServices []string `json:"endedServices,omitempty"` } diff --git a/durable/clock.go b/durable/clock.go index 7351d69f..60682ad9 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -110,6 +110,17 @@ func (c *recordingClock) armReadingAt(i int) (time.Time, bool) { return time.Unix(0, (*c.buf)[i].ClockUnixNano).UTC(), true } +// lastReadingSince returns the last clock reading recorded at or past index i, ok false +// when none was. Taken under the clock mutex, like armReadingAt. +func (c *recordingClock) lastReadingSince(i int) (time.Time, bool) { + c.mu.Lock() + defer c.mu.Unlock() + if i < 0 || i >= len(*c.buf) { + return time.Time{}, false + } + return time.Unix(0, (*c.buf)[len(*c.buf)-1].ClockUnixNano).UTC(), true +} + // replayClock returns recorded clock readings in order instead of reading any // real clock, so a recovered instance's scheduler re-derives identical timer // deadlines without consulting the wall clock. It is the inverse of diff --git a/durable/respawn_nested_test.go b/durable/respawn_nested_test.go index df88c02e..9f9ab866 100644 --- a/durable/respawn_nested_test.go +++ b/durable/respawn_nested_test.go @@ -85,3 +85,82 @@ func TestRecover_ANestedChildsStartFireAppliesOnce(t *testing.T) { }) } } + +// relay is an actor that sends its parent "pong" each time it's delivered "ping", and +// keeps running. +type relay struct{ out []state.Effect } + +func (r *relay) DeliverFire(_ context.Context, ev any) (bool, any) { + if ev == "ping" { + r.out = append(r.out, state.SendParent{Event: "pong"}) + } + return false, nil +} + +func (r *relay) ChildEffects() []state.Effect { + out := r.out + r.out = nil + return out +} +func (r *relay) Output() any { return nil } + +// TestRecover_DropsAPongLiveNeverSent proves Recover's respawn of the running actors, +// which follows the order the configuration declares them in, not the order they +// spawned live, can't apply a parent Fire live never did. Live, the pinger in the right +// region spawned first and pinged the relay as it started, but the relay, in the left +// region, wasn't running yet, so the ping went nowhere; the relay spawned later. Recover +// spawns the relay first, so the pinger's ping reaches it, and its pong is part of a +// running actor's start, which the parent doesn't hear. +func TestRecover_DropsAPongLiveNeverSent(t *testing.T) { + ctx := context.Background() + note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { + return func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, s) + return c + } + } + m := state.ForgeFor[actorCtx]("order"). + Reducer("notePong", note("pong")). + Actor("relay"). + Actor("pinger"). + SuperState("par"). + Region("left"). + Initial("l1"). + SubState("l1"). + SubState("l2").InvokeActor("relay", state.WithInvokeID("relay")). + EndRegion(). + Region("right"). + Initial("r1"). + SubState("r1").InvokeActor("pinger"). + EndRegion(). + EndSuperState(). + Initial("par"). + Transition("l1").On("go").GoTo("l2"). + Transition("par").On("pong").GoTo("par").Assign("notePong"). + Quench() + opts := []greetOption{durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "relay": func(map[string]any) (state.ActorInstance, error) { return &relay{}, nil }, + "pinger": func(map[string]any) (state.ActorInstance, error) { + return &starting{start: []state.Effect{state.SendTo{TargetID: "relay", Event: "ping"}}}, nil + }, + })} + store, id := durable.NewMemStore(), durable.InstanceID("order") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("par")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + if notes := h.Instance().Entity().Notes; len(notes) != 0 { + t.Fatalf("live notes = %v, want none: the relay wasn't running when the pinger pinged", notes) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if notes := recovered.Instance().Entity().Notes; len(notes) != 0 { + t.Fatalf("recovered notes = %v, want none: live never heard a pong", notes) + } +} diff --git a/durable/runner.go b/durable/runner.go index 9ea1887a..8dc76a13 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -136,12 +136,14 @@ type Handle[S comparable, E comparable, C any] struct { svc *state.ServiceRunner[S, E, C] // host driver for invoked services, nil when none wired svcBuf *[]state.JournalEntry // recording service-result accumulator, flushed per step + // settled holds the services that settled in the current activation of the state + // that declares them, so a checkpoint records them and Recover doesn't start them. + settled map[string]bool actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired ended recordedSet // the ended actors the journal last recorded unstarted recordedSet // the unstarted actors the journal last recorded seen map[string]bool // declared actors seen running, so a stopped one counts as ended - lastSets *actorSetsAt[S] // what actorSets last computed, and from what pending []state.ParentFire[S] // parent Fires Start's or Recover's spawns drove, journaled with the next step actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step @@ -347,6 +349,7 @@ func (h *Handle[S, E, C]) drainClock() []state.JournalEntry { // effects is a no-op when that driver is not wired or the effects name none of its // kind. func (h *Handle[S, E, C]) absorbDrivers(ctx context.Context, effects []state.Effect) { + forgetSettled(h.settled, effects) // Arm or cancel timers only when the effects actually schedule or cancel one: the // kernel Scheduler reads the clock unconditionally on Absorb, so skipping the call // for a timer-free transition keeps a non-timer machine free of clock reads. @@ -358,6 +361,7 @@ func (h *Handle[S, E, C]) absorbDrivers(ctx context.Context, effects []state.Eff } if h.actors != nil { h.actorFires.attempt(effects) + defer h.actorFires.driving(ctx)() h.actors.Absorb(ctx, effects) } } @@ -365,9 +369,10 @@ func (h *Handle[S, E, C]) absorbDrivers(ctx context.Context, effects []state.Eff // absorbParentFire arms or cancels the timers and services a parent Fire the actor // system drove declares, which the system itself leaves alone: the state an actor's // onDone, onError or message enters runs its timers and services, as one a Fire enters -// does. Replay arms them the same way, in the same order, so the clock reads match. -func (h *Handle[S, E, C]) absorbParentFire(effects []state.Effect) { - ctx := context.Background() +// does. Replay arms them the same way, in the same order, so the clock reads match. ctx +// is the context of the step that drove the system. +func (h *Handle[S, E, C]) absorbParentFire(ctx context.Context, effects []state.Effect) { + forgetSettled(h.settled, effects) if hasTimerEffect(effects) { h.absorbTimers(ctx, effects) } @@ -428,8 +433,8 @@ func (h *Handle[S, E, C]) armNow(before int) time.Time { // armTimersFrom mirrors the ScheduleAfter/CancelScheduled effects a chained timer // transition emitted into the Handle's timer table at the tick instant now, so a // timer a fired transition re-armed (the next link in an `after` chain) is tracked -// for the next checkpoint. It is the Tick-side analog of absorbTimers, sharing the -// tick's single recorded instant rather than reading the clock again. +// for the next checkpoint. It is the Tick-side analog of absorbTimers, using the +// tick's last recorded read rather than reading the clock again. func (h *Handle[S, E, C]) armTimersFrom(effects []state.Effect, now time.Time) { for _, eff := range effects { switch e := eff.(type) { @@ -446,13 +451,35 @@ func (h *Handle[S, E, C]) armTimersFrom(effects []state.Effect, now time.Time) { // dropFiredTimers removes from the Handle's timer table the timers a Tick fired, so // a checkpoint taken after the tick does not persist an already-fired timer. The -// scheduler removes a due timer before re-firing it; the Handle mirrors that by -// dropping every timer whose deadline is at or before now, matching the scheduler's -// dueLocked selection. -func (h *Handle[S, E, C]) dropFiredTimers(now time.Time) { - for id, pt := range h.timers { - if !pt.due.After(now) { - delete(h.timers, id) +// scheduler removes a due timer before re-firing it, so a timer the table holds that the +// scheduler no longer does fired, or a fired transition canceled it. That covers a timer +// that came due between the tick's clock reads, and a chained timer the tick armed and +// then fired. +func (h *Handle[S, E, C]) dropFiredTimers() { + dropUnscheduled(h.timers, h.sched) +} + +// dropUnscheduled removes from timers each one sched no longer holds. +func dropUnscheduled[S comparable, E comparable, C any](timers map[string]pendingTimer, sched *state.Scheduler[S, E, C]) { + for id := range timers { + if !sched.HasPending(id) { + delete(timers, id) + } + } +} + +// forgetSettled removes from settled each service effects start or stop: a state that +// declares it was entered or exited, so the service is new or gone. +func forgetSettled(settled map[string]bool, effects []state.Effect) { + if len(settled) == 0 { + return + } + for _, eff := range effects { + switch e := eff.(type) { + case state.StartService: + delete(settled, e.ID) + case state.StopService: + delete(settled, e.ID) } } } @@ -573,7 +600,9 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt if actors != nil { actorFires.arm = h.absorbParentFire actorFires.attempt(inst.StartEffects()) + restore := actorFires.driving(ctx) actors.Absorb(ctx, inst.StartEffects()) + restore() } // 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 @@ -628,10 +657,12 @@ func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) (*state. type parentFires[S comparable] struct { // arm, when set, arms the timers and services a parent Fire's effects declare, as a // host Fire's absorb does: the actor system handles only their actors. It's set - // before any spawn and runs on the goroutine driving the system. - arm func(effects []state.Effect) + // before any spawn and runs on the goroutine driving the system, with the context + // driving names. + arm func(ctx context.Context, effects []state.Effect) mu sync.Mutex + ctx context.Context // the context of the step driving the system, for arm fires []state.ParentFire[S] spawned map[string]bool // actors whose latest spawn this step started attempted map[string]bool // actors the system was asked to spawn this step @@ -696,14 +727,35 @@ func (p *parentFires[S]) note(pf state.ParentFire[S]) { } p.failed[pf.ActorID] = true } + ctx := p.ctx p.mu.Unlock() if p.arm != nil { - p.arm(pf.Result.Effects) + if ctx == nil { + ctx = context.Background() + } + p.arm(ctx, pf.Result.Effects) } // The system absorbs a parent Fire's effects next, which spawns what they declare. p.attempt(pf.Result.Effects) } +// driving notes ctx as the context of the step about to drive the system, so arm gets +// it, and returns the func that restores the one before. It's safe on a nil collector. +func (p *parentFires[S]) driving(ctx context.Context) (restore func()) { + if p == nil { + return func() {} + } + p.mu.Lock() + prev := p.ctx + p.ctx = ctx + p.mu.Unlock() + return func() { + p.mu.Lock() + p.ctx = prev + p.mu.Unlock() + } +} + // take returns the Fires noted since the last take, in fire order, and forgets them. // It's safe on a nil collector, which has none. func (p *parentFires[S]) take() []state.ParentFire[S] { @@ -933,11 +985,11 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro if err := h.refuse(ctx); err != nil { return nil, err } - // The tick's first read lands past what the buffer holds now, which can include reads - // of an earlier Start's or Recover's spawns, recorded with this step. + // The tick's reads land past what the buffer holds now, which can include reads of an + // earlier Start's or Recover's spawns, recorded with this step. mark := h.recClock.markBuf() results := h.sched.Tick(h.stepContext(ctx)) - now, haveNow := h.recClock.armReadingAt(mark) + now, haveNow := h.recClock.lastReadingSince(mark) // 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. @@ -949,17 +1001,17 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro step := h.nextStep rec := Record{Step: step, Tick: true, TickSteps: len(results), Entries: h.drainClock()} - // Reconcile the Handle's timer table with the tick: drop the timers it fired and - // arm any a chained transition scheduled, so a checkpoint after the tick persists - // exactly the still-pending deadlines. The clock does not advance within one tick - // (a FakeClock advances only between ticks; a SystemClock's intra-tick drift is - // sub-timer), so the tick's recorded reads share one instant: use it for both the - // drop (timers due at or before it fired) and any chained re-arm. + // Reconcile the Handle's timer table with the tick: arm any timer a chained + // transition scheduled, then drop the ones the tick fired, by id, so a checkpoint + // after the tick persists exactly the still-pending deadlines. A chained timer's + // deadline counts from the tick's last read, as replay's does (a SystemClock's + // intra-tick drift is sub-timer). if haveNow { - h.dropFiredTimers(now) for i := range results { h.armTimersFrom(results[i].Effects, now) + forgetSettled(h.settled, results[i].Effects) } + h.dropFiredTimers() } // A tick that read no clock and fired nothing records nothing: there is no // nondeterminism to journal and no step was produced. @@ -1124,14 +1176,6 @@ func (r *recordedSet) note(now *ActorSet) { } } -// actorSetsAt is what actorSets last computed, and the configuration and running -// actors it computed them from. -type actorSetsAt[S comparable] struct { - config []S - running []string - ended, unstarted *ActorSet -} - // actorSets returns the actors the instance's state declares that ran and have ended, // and those that aren't running and haven't ended, and remembers them for the next // step. A declared actor that isn't running has ended when it settled (the actor system @@ -1141,21 +1185,12 @@ type actorSetsAt[S comparable] struct { // applied also counts as ended, since the journal holds that onError. So an actor whose // spawn failed with no onError, at entry or on a re-entry, hasn't ended: it's unstarted, // and Recover tries it again. Both are nil with no actor palette. -// -// A step that noted no spawn and changed neither the configuration nor the running -// actors can't change either set, so it gets the last ones back without a walk of the -// declared actors. func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { if h.actors == nil { return nil, nil } spawned, attempted, failed := h.actorFires.takeLifecycle() running := h.actors.IDs() - config := h.inst.Configuration() - if last := h.lastSets; last != nil && len(spawned) == 0 && len(attempted) == 0 && len(failed) == 0 && - slices.Equal(running, last.running) && slices.Equal(config, last.config) { - return last.ended, last.unstarted - } endedIDs, unstartedIDs := []string{}, []string{} for _, id := range declaredActors(h.inst.StartEffects()) { if slices.Contains(running, id) { @@ -1183,26 +1218,25 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { for _, id := range append(running, endedIDs...) { h.seen[id] = true } - ended, unstarted = &ActorSet{IDs: endedIDs}, &ActorSet{IDs: unstartedIDs} - h.lastSets = &actorSetsAt[S]{config: config, running: running, ended: ended, unstarted: unstarted} - return ended, unstarted + return &ActorSet{IDs: endedIDs}, &ActorSet{IDs: unstartedIDs} } -// endedServices returns the invoked services the active states declare that aren't in -// flight, sorted: each settled while the state that declares it stayed active. It is nil -// with no service registry. +// endedServices returns the invoked services the active states declare that settled +// while the state that declares them stayed active, sorted. A declared service that +// isn't in flight but never settled, such as one a Tick's timer entered, which a Tick +// doesn't start, isn't one: Recover starts it. It is nil with no service registry. func (h *Handle[S, E, C]) endedServices() []string { - if h.svc == nil { + if h.svc == nil || len(h.settled) == 0 { return nil } var ids []string for _, eff := range h.inst.StartEffects() { - if sv, ok := eff.(state.StartService); ok && !h.svc.HasPending(sv.ID) { + if sv, ok := eff.(state.StartService); ok && h.settled[sv.ID] { ids = append(ids, sv.ID) } } slices.Sort(ids) - return ids + return slices.Compact(ids) } // declaredActors returns the ids of the actors effects spawn. @@ -1331,6 +1365,17 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // with every still-pending timer's deadline for the next checkpoint. armed := map[string]pendingTimer{} + // mirror tracks, as replay walks the tail, the still-pending timers in armed and the + // services that settled in their state's current activation, starting from the ones + // the checkpoint recorded. + mirror := &armMirror{armed: armed, clock: repClock} + for _, sv := range env.EndedServices { + mirror.settle(sv) + } + // actorArms reports whether the Record replay is at was written by a version that + // arms an actor-driven Fire's timers and services. + actorArms := env.UnstartedActors != nil + // ended is the latest recorded set of the declared actors the live run had ended: // the checkpoint's, then each tail Record's that records one. Nil means none was // recorded, so Recover spawns every actor the configuration declares. @@ -1349,7 +1394,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // The mirror tracks the still-pending timers in armed as replay arms, cancels and // fires them, with deadlines drawn from the recorded clock reads, not the live // wall clock. - did, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, &armMirror{armed: armed, clock: repClock}) + actorArms = armsActorFires(actorArms, rec) + did, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, mirror, actorArms) if err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } @@ -1441,6 +1487,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S timers: armed, svc: svc, svcBuf: &svcBuf, + settled: mirror.settled, actors: actors, actorBuf: &actorBuf, actorFires: actorFires, @@ -1467,7 +1514,9 @@ 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) + restore := actorFires.driving(ctx) respawn(ctx, actors, spawns, unstarted) + restore() } // 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 @@ -1752,7 +1801,8 @@ type replayed[S comparable] struct { // order, with the recorded done-data or error, so the kernel re-derives the same // onDone / onError (or message) transition. A Fire's or settle's absorb-driven // parent Fires, such as a spawned actor's onError, re-fire after its own work. Each -// re-arms the timers and services its state declares, as the live Fire did. +// re-arms the timers and services its state declares, as the live Fire did, when +// actorArms says the version that wrote rec armed them. // - A service settlement re-settles each recorded outcome through the same settle // seam, in settle order; the settle absorbs its own follow-on StartService // effects, so a chained invoke arms its successor for the next entry, and its @@ -1770,6 +1820,7 @@ func replayRecord[S comparable, E comparable, C any]( svc *state.ServiceRunner[S, E, C], rec *Record, mirror *armMirror, + actorArms bool, ) (replayed[S], error) { var out replayed[S] before, rest, err := splitActorEntries(rec) @@ -1777,7 +1828,7 @@ func replayRecord[S comparable, E comparable, C any]( return out, 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); err != nil { + if err := replayActors(ctx, inst, cfg, sched, svc, rec, before, mirror, actorArms); err != nil { return out, err } switch { @@ -1802,20 +1853,23 @@ func replayRecord[S comparable, E comparable, C any]( if err != nil { return out, fmt.Errorf("at step %d: %w", rec.Step, err) } + mirror.settle(entry.CorrelationID) // The settle armed its own services; arm its timers, as RunService did. replayArm(ctx, sched, nil, effects, mirror) } case rec.Tick: out.tick = sched.Tick(ctx) - mirrorTick(mirror, out.tick) + mirrorTick(mirror, sched, out.tick) } // 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 out, replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror) + return out, replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror, actorArms) } -// replayActors re-fires recorded parent transitions, in order, arming the timers and -// services each declares, as the live run did. +// replayActors re-fires recorded parent transitions, in order. When actorArms, the +// version that wrote rec armed the timers and services an actor-driven Fire declares, +// so each one arms them, as the live run did. An older version armed none, and took no +// clock read for them, so they're left alone, as that run left them. func replayActors[S comparable, E comparable, C any]( ctx context.Context, inst *state.Instance[S, E, C], @@ -1825,21 +1879,35 @@ func replayActors[S comparable, E comparable, C any]( rec *Record, entries []state.JournalEntry, mirror *armMirror, + actorArms bool, ) error { for _, entry := range entries { effects, err := replayActor(ctx, inst, cfg.eventCodec, entry) if err != nil { return fmt.Errorf("at step %d: %w", rec.Step, err) } - replayArm(ctx, sched, svc, effects, mirror) + if actorArms { + replayArm(ctx, sched, svc, effects, mirror) + } else { + mirror.forget(effects) + } } return nil } +// armsActorFires reports whether rec was written by a version that arms the timers and +// services an actor-driven parent Fire declares, given whether an earlier Record or the +// checkpoint replay started from was: such a version records the unstarted actors +// with its first step, and in every checkpoint, when an actor palette is wired. +func armsActorFires(earlier bool, rec *Record) bool { + return earlier || rec.UnstartedActors != nil +} + // 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) @@ -1851,10 +1919,33 @@ func replayArm[S comparable, E comparable, C any](ctx context.Context, sched *st // armMirror tracks the timers a Recover's replay leaves pending, with the deadlines the // scheduler computed from the recorded clock reads, so the Handle's timer table starts -// with them. A nil mirror, as a time-travel read uses, tracks nothing. +// with them, and the services that settled in their state's current activation, so the +// Handle's next checkpoint records them. A nil mirror, as a time-travel read uses, +// tracks nothing. type armMirror struct { - armed map[string]pendingTimer - clock *replayClock + armed map[string]pendingTimer + clock *replayClock + settled map[string]bool +} + +// settle notes that a replayed settle settled the service id. +func (m *armMirror) settle(id string) { + if m == nil { + return + } + if m.settled == nil { + m.settled = map[string]bool{} + } + m.settled[id] = true +} + +// forget drops from the settled services each one a replayed Fire's effects start or +// stop, as the live step did. +func (m *armMirror) forget(effects []state.Effect) { + if m == nil { + return + } + forgetSettled(m.settled, effects) } // arm folds a replayed absorb's timer effects into the table, at the reading the @@ -1866,19 +1957,17 @@ func (m *armMirror) arm(effects []state.Effect) { mirrorArmed(m.armed, effects, m.clock.lastRead()) } -// mirrorTick drops from m the timers a replayed tick fired and arms any a chained -// transition scheduled, at the instant the tick read: the tick's reads share one instant. -func mirrorTick[S comparable](m *armMirror, results []state.FireResult[S]) { +// mirrorTick arms in m any timer a replayed tick's chained transition scheduled, at the +// tick's last read, as the live Tick does, then drops the timers the tick fired: the ones +// sched no longer holds. +func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Scheduler[S, E, C], results []state.FireResult[S]) { if m == nil { return } now := m.clock.lastRead() - for id, pt := range m.armed { - if !pt.due.After(now) { - delete(m.armed, id) - } - } for i := range results { mirrorArmed(m.armed, results[i].Effects, now) + m.forget(results[i].Effects) } + dropUnscheduled(m.armed, sched) } diff --git a/durable/service.go b/durable/service.go index 733db64c..2e738290 100644 --- a/durable/service.go +++ b/durable/service.go @@ -122,6 +122,9 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire return state.FireResult[S]{}, false, nil } res := results[0] + // The service settled: unless the settle's own Fire leaves or re-enters the state + // that declares it, which the absorb below notes, a checkpoint records it as settled. + h.noteSettled(id) // The settle re-fired the invocation's onDone / onError, which may enter a state // that arms a timer, starts another service, or spawns an actor. Absorb those @@ -165,6 +168,14 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire return res, true, nil } +// noteSettled records that the service id settled in its state's current activation. +func (h *Handle[S, E, C]) noteSettled(id string) { + if h.settled == nil { + h.settled = map[string]bool{} + } + h.settled[id] = true +} + // recordServiceOutcome builds the JournalServiceResult entry for a just-settled // service. It reads the success result through lastResult (valid only during the // settle's synchronous window) and the error through lastErr, encoding whichever diff --git a/durable/service_test.go b/durable/service_test.go index a13a346f..910ed858 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -839,7 +839,9 @@ func TestService_RefusedByADerivedContext_RecordsNothing(t *testing.T) { // checkpoint taken after the settle, where the compound is still active. func TestRecover_DoesNotRearmASuperstatesSettledService(t *testing.T) { ctx := context.Background() - for _, every := range []int{0, 1} { + // every=-1 runs live with no checkpoint, then checkpoints from each recovered Handle, + // so the checkpoint comes from a replay of the settle. + for _, every := range []int{0, 1, -1} { t.Run(fmt.Sprintf("every=%d", every), func(t *testing.T) { var runs int64 fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { @@ -858,12 +860,17 @@ func TestRecover_DoesNotRearmASuperstatesSettledService(t *testing.T) { Transition("b").On("poke").GoTo("b"). Quench() opts := []stepOption{durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch))} - if every > 0 { + live := opts + switch { + case every > 0: opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + live = opts + case every < 0: + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](1)) } store, id := durable.NewMemStore(), durable.InstanceID("nest-svc") svcID := state.InvokeID("nestSvc", "outer", 0) - h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("a")) + h, err := durable.NewRunner(m, store, live...).Start(ctx, id, stepCtx{}, state.WithInitialState("a")) if err != nil { t.Fatalf("Start: %v", err) } @@ -892,3 +899,96 @@ func TestRecover_DoesNotRearmASuperstatesSettledService(t *testing.T) { }) } } + +// TestRecover_StartsAServiceThatNeverSettled proves a checkpoint records as settled only +// a service that settled, not every declared service that isn't in flight, so Recover +// starts the rest: one whose state a Tick's timer entered (a Tick starts no service), +// and one whose state was re-entered after it settled, which is a new service, whether +// a Fire re-entered it, starting it live, or a Tick did. The checkpoint is the live +// run's, or one a recovered Handle takes after replaying the run. +func TestRecover_StartsAServiceThatNeverSettled(t *testing.T) { + ctx := context.Background() + for _, how := range []string{"timer entered", "Fire re-entered", "timer re-entered"} { + for _, where := range []string{"live checkpoint", "replayed checkpoint"} { + t.Run(how+"/"+where, func(t *testing.T) { + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + m := state.ForgeFor[stepCtx]("unsettled"). + Service("fetch", fetch). + State("idle"). + State("waiting"). + State("fetching").Invoke("fetch", state.WithInvokeOnDone("fetched")). + Initial("idle"). + Transition("idle").On("begin").GoTo("waiting"). + Transition("waiting").On("go").GoTo("fetching"). + Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("fetching"). + Transition("fetching").On("fetched").GoTo("fetching"). + Transition("fetching").On("again").GoTo("fetching").Reenter(). + Transition("fetching").After(10 * time.Second).On("redo").GoTo("fetching").Reenter(). + Transition("fetching").On("poke").GoTo("fetching"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch)), + } + checkpointing := append(opts, durable.WithCheckpointEvery[string, string, stepCtx](1)) + live := checkpointing + if where == "replayed checkpoint" { + live = opts + } + store, id := durable.NewMemStore(), durable.InstanceID("unsettled") + svcID := state.InvokeID("unsettled", "fetching", 0) + h, err := durable.NewRunner(m, store, live...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "begin"); err != nil { + t.Fatalf("Fire(begin): %v", err) + } + switch how { + case "timer entered": + clk.Advance(10 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + default: + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + if _, ran, runErr := h.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v", ran, runErr) + } + if how == "Fire re-entered" { + if _, err = h.Fire(ctx, "again"); err != nil { + t.Fatalf("Fire(again): %v", err) + } + } else { + clk.Advance(10 * time.Second) + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v, want the redo timer to fire", len(results), tickErr) + } + } + } + if got := h.Instance().Current(); got != "fetching" { + t.Fatalf("state = %q, want fetching", got) + } + if where == "replayed checkpoint" { + // Replay the journal, then checkpoint from the recovered Handle's view. + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the journal: %v", err) + } + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, checkpointing...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, runErr := recovered.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService after Recover = %v, %v, want the service in flight: it never settled in this activation of fetching", ran, runErr) + } + }) + } + } +} diff --git a/durable/store.go b/durable/store.go index afccb18a..4dbbbca9 100644 --- a/durable/store.go +++ b/durable/store.go @@ -102,7 +102,11 @@ type Record struct { // drove, so Recover spawns it again without letting those reach the parent. It's // recorded as EndedActors is: with the first step after Start, then when a step // changes it, and an empty set is not nil. When the journal holds none, as on a - // Record from before this field, Recover lets every spawn reach the parent. + // Record from before this field, Recover lets every spawn reach the parent. Replay + // also reads a Record from a journal that has recorded this set, in the checkpoint + // or in that Record or one before it, as written by a version that arms the timers and + // services an actor-driven parent Fire's state declares, and arms them; it arms none + // for an older Record, as the run that wrote it didn't. UnstartedActors *ActorSet `json:",omitempty"` } diff --git a/durable/timer_checkpoint_test.go b/durable/timer_checkpoint_test.go index 3834a216..9d3ac771 100644 --- a/durable/timer_checkpoint_test.go +++ b/durable/timer_checkpoint_test.go @@ -2,6 +2,7 @@ package durable_test import ( "context" + "sync" "testing" "time" @@ -381,3 +382,113 @@ func TestTimerCheckpoint_RecoveryDeterministic(t *testing.T) { t.Fatalf("recovery across checkpoint nondeterministic\n first: %s\n second: %s", first, second) } } + +// steppingClock is a Clock that moves step past each reading it returns, as a wall +// clock moves between the reads of one Tick. +type steppingClock struct { + mu sync.Mutex + now time.Time + step time.Duration +} + +func (c *steppingClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + t := c.now + c.now = c.now.Add(c.step) + return t +} + +func (c *steppingClock) After(d time.Duration) <-chan time.Time { + ch := make(chan time.Time, 1) + ch <- c.Now().Add(d) + return ch +} + +func (c *steppingClock) Advance(d time.Duration) { + c.mu.Lock() + c.now = c.now.Add(d) + c.mu.Unlock() +} + +// TestTick_DropsEachTimerItFired proves the timer table a checkpoint persists after a +// Tick holds none of the timers the Tick fired, so a Recover from it doesn't fire one +// again: not a chained zero-delay timer the Tick armed and fired in the same pass, and +// not a timer that came due between the Tick's first clock read and a later one, as +// a wall clock moves on. Each fired transition stays in its state, so no cancel drops +// the timer. The checkpoint is the live run's, or one a recovered Handle takes after +// replaying the Tick. +func TestTick_DropsEachTimerItFired(t *testing.T) { + ctx := context.Background() + for _, how := range []string{"chained zero delay", "due between reads"} { + for _, where := range []string{"live checkpoint", "replayed checkpoint"} { + t.Run(how+"/"+where, func(t *testing.T) { + b := state.ForgeFor[stepCtx]("fired"). + State("idle"). + State("first"). + State("second"). + Initial("idle"). + Transition("idle").On("arm").GoTo("first"). + Transition("second").On("poke").GoTo("second"). + Transition("first").On("poke").GoTo("first") + var clk interface { + state.Clock + Advance(time.Duration) + } + wantFired := 2 + if how == "chained zero delay" { + // first's timer enters second, whose zero-delay timer is due at once. + b = b.Transition("first").After(10 * time.Second).On("toSecond").GoTo("second"). + Transition("second").After(0).On("zero").GoTo("second") + clk = state.NewFakeClock(epoch) + } else { + // Two timers 1ms apart; each read moves the clock 1ms, so the second + // comes due at the Tick's third read. + b = b.Transition("first").After(10 * time.Second).On("a").GoTo("first"). + Transition("first").After(10*time.Second + time.Millisecond).On("b").GoTo("first") + clk = &steppingClock{now: epoch, step: time.Millisecond} + } + m := b.Quench() + opts := []stepOption{durable.WithRunnerClock[string, string, stepCtx](clk)} + checkpointing := append(opts[:len(opts):len(opts)], durable.WithCheckpointEvery[string, string, stepCtx](1)) + live := checkpointing + if where == "replayed checkpoint" { + live = opts + } + store, id := durable.NewMemStore(), durable.InstanceID("fired") + h, err := durable.NewRunner(m, store, live...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire(arm): %v", err) + } + // The arming read moved a stepping clock 1ms: land the Tick's first read at + // the first timer's deadline. + if how == "due between reads" { + clk.Advance(10*time.Second - time.Millisecond) + } else { + clk.Advance(10 * time.Second) + } + if results, tickErr := h.Tick(ctx); tickErr != nil || len(results) != wantFired { + t.Fatalf("Tick = %d results, %v, want %d", len(results), tickErr, wantFired) + } + if where == "replayed checkpoint" { + if h, err = durable.Recover(ctx, m, store, id, checkpointing...); err != nil { + t.Fatalf("Recover from the journal: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + } + recovered, err := durable.Recover(ctx, m, store, id, checkpointing...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if results, tickErr := recovered.Tick(ctx); tickErr != nil || len(results) != 0 { + t.Fatalf("Tick after Recover = %d results, %v, want none: the Tick before it fired every due timer", len(results), tickErr) + } + }) + } + } +} diff --git a/durable/timetravel.go b/durable/timetravel.go index dd52c14f..b25ecd26 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -138,7 +138,7 @@ func StateAt[S comparable, E comparable, C any]( return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } - if err := replayThrough(ctx, inst, &cfg, bounded); err != nil { + if err := replayThrough(ctx, inst, &cfg, bounded, unmarshalCheckpoint(baseline).UnstartedActors != nil); err != nil { return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } return &TimeTravelView[S, E, C]{inst: inst, step: step}, nil @@ -223,12 +223,14 @@ func restoreBaseline[S comparable, E comparable, C any]( // It is the bounded, read-only analog of Recover's replay loop: it builds its own // service host driver (to settle recorded outcomes) and ticks a scheduler over the // instance's recorded-instant clock, consuming exactly the records the caller bounded -// to the target step. +// to the target step. actorArms reports whether the baseline was written by a version +// that arms an actor-driven Fire's timers and services. func replayThrough[S comparable, E comparable, C any]( ctx context.Context, inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], bounded []Record, + actorArms bool, ) error { sched := state.NewScheduler(inst) @@ -245,7 +247,8 @@ func replayThrough[S comparable, E comparable, C any]( } // A domain effect is never dispatched here: a time-travel read applies no // side effect. - if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil); err != nil { + actorArms = armsActorFires(actorArms, &bounded[i]) + if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, actorArms); err != nil { return err } } From 7d110fed3aafb700739686b8ee08e8f9ac3596d4 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Sun, 15 Nov 2026 11:08:10 -0700 Subject: [PATCH 23/38] fix(durable): keep a tail cancel of a checkpoint timer; record the journal format Recover re-armed a timer the checkpoint recorded even when a later step had canceled it, since the cancel replays before the re-arm. The replay mirror now notes the timers the tail cancels, and the re-arm skips them. Each Record now carries Format, and replay arms an actor-driven Fire's timers and services from it, instead of inferring the format from whether UnstartedActors is nil. The CHANGELOG tells Store authors which fields to keep. Also narrow the CHANGELOG's context-error sentence to Fire callbacks, correct the DeliverToActor godoc for a delivery that drove no parent Fire, and drop dead code: replayed.tick, the unused receivers on stepCanceled and consumedCanceled, and actorEntry's parameters that repeat the ParentFire. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 22 ++++++-- durable/actor.go | 15 +++--- durable/actor_driven_drivers_test.go | 2 +- durable/memstore.go | 2 +- durable/runner.go | 61 +++++++++++++++------- durable/service.go | 2 +- durable/store.go | 13 +++-- durable/timer_cancel_tail_test.go | 75 ++++++++++++++++++++++++++++ durable/timetravel.go | 9 ++-- 9 files changed, 156 insertions(+), 45 deletions(-) create mode 100644 durable/timer_cancel_tail_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 1d50c463..5e98b054 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -15,6 +15,14 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **`Record.UnstartedActors`** records the declared actors that aren't running and haven't ended, because their spawn failed with no onError, so `Recover` can tell them from the actors that were running. A Store must keep an empty set distinct from nil. +- **`Record.Format`** records the journal format of the version that wrote the Record, + which is 1 from this version. Replay arms the timers and services an actor-driven + parent Fire's state declares only for a Record of format 1 or later. + **For Store authors:** a Store must keep `Format`, `EndedActors` and + `UnstartedActors`, and keep an empty set distinct from nil. A Store that drops them, or + maps an empty set to nil as an SQL array column or a protobuf repeated field can, + makes `Recover` spawn ended actors again, and replay arm nothing for a Record without + its `Format`. MemStore and FileStore keep all three. - **Fencing.** `WithFence` on `Store.Append` and `WithCheckpointFence` on `Store.Checkpoint` carry a caller-issued token, and a Store refuses a token lower @@ -148,8 +156,10 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. wrapping the error and records nothing. One rule covers them: a step records nothing once its context ended by the end of the step, or a Fire it drove was refused with a context's error, which catches a context middleware derived from the caller's. A - callback that returns its own context error, such as an HTTP client's timeout, counts - as a context ending too. + guard binding, action or middleware of that Fire that returns its own context error, such as + an HTTP client's timeout, counts as a context ending too. A service function's error + doesn't: a service that returns one settles through its onError, and the step + journals. A Fire refused for another reason, such as a failing guard, is still recorded, and replay now meets the same refusal instead of failing Recover on it. After `Recover` the service stays in flight and must tolerate running again, the timer is re-armed, an @@ -202,12 +212,14 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. `RunService` reported none, and its timer never fired; a checkpoint then recorded the service as settled, so `Recover` didn't start it either. Such a Fire now arms them, live, at `Start` and `Recover`, and on replay, as a host `Fire` does. Replay arms them - only in a journal this version wrote, which records the unstarted actors: one an - older version wrote took no clock read for them, and replays as it did. A service's + only for a Record this version wrote, which records its `Format`: an older version + took no clock read for them, and its Records replay as they did. A service's settle re-arms its state's timers on replay too, and `DeliverToActor` and `RunService` now journal the clock reads their step took, so a checkpoint on that step can't leave a read for the next to replay. `Recover` re-arms a checkpoint's timers before it - spawns the running actors, so a Fire one of theirs drives can cancel one. A `Tick` + spawns the running actors, so a Fire one of theirs drives can cancel one. A timer + the checkpoint recorded and a later step canceled stays canceled: `Recover` used to + re-arm it, since that step's cancel replays before the re-arm. A `Tick` drops from the timers a checkpoint records exactly the ones it fired, live and on replay: one that came due between its clock reads, and a chained one it armed and fired, used to stay, so a `Recover` from a later checkpoint fired it again. diff --git a/durable/actor.go b/durable/actor.go index f5fe03a6..b7a3150e 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -111,8 +111,9 @@ type actorMessagePayload struct { // actor (already settled, stopped, or never spawned), or false and an error when no // palette is wired, the Handle has failed, or ctx ended before the delivery. Once the // actor ran it returns true with any error. A result that won't encode, a ctx that ended -// during the delivery, or a parent Fire refused because a context ended (ctx, or one -// middleware derived from it) returns ErrHandleFailed and records nothing: on a +// during a delivery that drove a parent Fire, or a parent Fire refused because a context +// ended (ctx, or one middleware derived from it) returns ErrHandleFailed and records +// nothing; a delivery that drove no parent Fire records as usual. On a // recovered Handle an InvokeActor actor restarts from its initial state, and a Spawn // actor doesn't return. A failed Append also returns ErrHandleFailed, but the write may // have landed anyway, and Recover finds out which. If another goroutine failed the Handle while this step was @@ -146,7 +147,7 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef // Record nothing. // A delivery that drove no parent Fire changed nothing the journal holds, so an ended // ctx can't have cost it anything. - if err := h.consumedCanceled(ctx, len(fires) > 0, parentFireErrs(fires)...); err != nil { + if err := consumedCanceled(ctx, len(fires) > 0, parentFireErrs(fires)...); err != nil { return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) } @@ -203,7 +204,7 @@ func (h *Handle[S, E, C]) drainActors() []state.JournalEntry { func recordParentFires[S comparable](fires []state.ParentFire[S], before bool) ([]state.JournalEntry, error) { entries := make([]state.JournalEntry, 0, len(fires)) for _, pf := range fires { - entry, err := actorEntry(pf.ActorID, pf.Result.Trace.EventPayload, pf, before) + entry, err := actorEntry(pf, before) if err != nil { return nil, err } @@ -216,9 +217,9 @@ func recordParentFires[S comparable](fires []state.ParentFire[S], before bool) ( // whether the live Fire was refused, and, for a Fire that settled an actor, the // actor's outcome, which it passed as event data, so replay re-fires the same onDone // or onError with it. -func actorEntry[S comparable](id string, event json.RawMessage, pf state.ParentFire[S], before bool) (state.JournalEntry, error) { +func actorEntry[S comparable](pf state.ParentFire[S], before bool) (state.JournalEntry, error) { var mp actorMessagePayload - mp.Event = append(json.RawMessage(nil), event...) + mp.Event = append(json.RawMessage(nil), pf.Result.Trace.EventPayload...) mp.Refused = pf.Result.Err != nil mp.Before = before if pf.Settle { @@ -239,7 +240,7 @@ func actorEntry[S comparable](id string, event json.RawMessage, pf state.ParentF if err != nil { return state.JournalEntry{}, fmt.Errorf("marshaling actor transition: %w", err) } - return state.JournalEntry{Kind: state.JournalActorMessage, CorrelationID: id, Payload: payload}, nil + return state.JournalEntry{Kind: state.JournalActorMessage, CorrelationID: pf.ActorID, Payload: payload}, nil } // splitActorEntries returns a Record's actor entries in recorded order, the ones that diff --git a/durable/actor_driven_drivers_test.go b/durable/actor_driven_drivers_test.go index d72763b6..36f3e3c6 100644 --- a/durable/actor_driven_drivers_test.go +++ b/durable/actor_driven_drivers_test.go @@ -398,7 +398,7 @@ func TestRecover_ReplaysAnOlderJournalsActorFireWithoutArming(t *testing.T) { t.Fatalf("Checkpoint: %v", err) } for i, rec := range tail { - rec.EndedActors, rec.UnstartedActors = nil, nil + rec.EndedActors, rec.UnstartedActors, rec.Format = nil, nil, 0 if i == 0 { // The older version armed nothing for the onDone, so took no read. var entries []state.JournalEntry diff --git a/durable/memstore.go b/durable/memstore.go index 2cd13598..f89a7ecc 100644 --- a/durable/memstore.go +++ b/durable/memstore.go @@ -386,7 +386,7 @@ func cloneBytes(b []byte) []byte { // json.RawMessage payloads within entries/effects are immutable by convention, // so the slice headers are copied without cloning each payload's bytes. func cloneRecord(rec Record) Record { - out := Record{Step: rec.Step, Tick: rec.Tick, TickSteps: rec.TickSteps} + out := Record{Step: rec.Step, Tick: rec.Tick, TickSteps: rec.TickSteps, Format: rec.Format} if rec.Event != nil { out.Event = append([]byte(nil), rec.Event...) } diff --git a/durable/runner.go b/durable/runner.go index 8dc76a13..af86c4e7 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -995,7 +995,7 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro // 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 := h.consumedCanceled(ctx, len(results) > 0, append(resultErrs(results), parentFireErrs(h.actorFires.take())...)...); err != nil { + 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)) } @@ -1142,6 +1142,7 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) } rec.Snapshot = env } + rec.Format = journalFormat if h.ended.changedBy(ended) { rec.EndedActors = ended } @@ -1372,9 +1373,6 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S for _, sv := range env.EndedServices { mirror.settle(sv) } - // actorArms reports whether the Record replay is at was written by a version that - // arms an actor-driven Fire's timers and services. - actorArms := env.UnstartedActors != nil // ended is the latest recorded set of the declared actors the live run had ended: // the checkpoint's, then each tail Record's that records one. Nil means none was @@ -1394,8 +1392,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // The mirror tracks the still-pending timers in armed as replay arms, cancels and // fires them, with deadlines drawn from the recorded clock reads, not the live // wall clock. - actorArms = armsActorFires(actorArms, rec) - did, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, mirror, actorArms) + did, 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) } @@ -1434,6 +1431,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // remaining delay is the persisted deadline minus the recovery clock's now, so // the re-armed timer fires at its recorded instant — an already-elapsed deadline // arms as immediately due and fires on the next Tick. + // A timer the tail canceled stays canceled: its cancel replayed before this re-arm. + persistedTimers = slices.DeleteFunc(persistedTimers, func(w pendingTimerWire) bool { return mirror.canceled[w.ID] }) reEffects, reSeeded, reErr := reArmEffects(r.cfg.eventCodec, persistedTimers, armed, repClock.Now()) if reErr != nil { return nil, fmt.Errorf("durable: re-arming pending timers for %q: %w", id, reErr) @@ -1736,7 +1735,7 @@ func isContextErr(err error) bool { // they consumed can end on it without any Fire reporting it. A refusal with any other // cause, such as a failing guard, is deterministic: the step is journaled, and replay // meets the same refusal. -func (h *Handle[S, E, C]) stepCanceled(ctx context.Context, errs ...error) error { +func stepCanceled(ctx context.Context, errs ...error) error { if err := ctx.Err(); err != nil { return err } @@ -1746,9 +1745,9 @@ func (h *Handle[S, E, C]) 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. -func (h *Handle[S, E, C]) consumedCanceled(ctx context.Context, consumed bool, errs ...error) error { +func consumedCanceled(ctx context.Context, consumed bool, errs ...error) error { if consumed { - return h.stepCanceled(ctx, errs...) + return stepCanceled(ctx, errs...) } return refusedByContext(errs...) } @@ -1786,7 +1785,6 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { // replayed is what replayRecord fired, for a caller that tracks more than the // instance: a tick barrier's timer fires, or a plain event's Fire. type replayed[S comparable] struct { - tick []state.FireResult[S] fired *state.FireResult[S] } @@ -1858,8 +1856,7 @@ func replayRecord[S comparable, E comparable, C any]( replayArm(ctx, sched, nil, effects, mirror) } case rec.Tick: - out.tick = sched.Tick(ctx) - mirrorTick(mirror, sched, out.tick) + mirrorTick(mirror, sched, sched.Tick(ctx)) } // The rest are a delivery's parent Fires, or the ones a Fire's or settle's absorb // drove after it, such as a spawned actor's onError. @@ -1896,13 +1893,19 @@ func replayActors[S comparable, E comparable, C any]( } // armsActorFires reports whether rec was written by a version that arms the timers and -// services an actor-driven parent Fire declares, given whether an earlier Record or the -// checkpoint replay started from was: such a version records the unstarted actors -// with its first step, and in every checkpoint, when an actor palette is wired. -func armsActorFires(earlier bool, rec *Record) bool { - return earlier || rec.UnstartedActors != nil +// services an actor-driven parent Fire declares, from the journal Format it records. +func armsActorFires(rec *Record) bool { + return rec.Format >= actorArmsFormat } +// journalFormat is the format this version writes in every Record. It is +// actorArmsFormat, the first that arms the timers and services an actor-driven parent +// Fire's state declares. +const ( + actorArmsFormat = 1 + journalFormat = actorArmsFormat +) + // replayArm arms the timers and services a replayed Fire's effects declare, as the live // step's absorb did, reading the clock only when they schedule or cancel a timer, as it // did. svc may be nil. @@ -1926,6 +1929,9 @@ type armMirror struct { armed map[string]pendingTimer clock *replayClock settled map[string]bool + // canceled holds the timers replay canceled and didn't arm again, so Recover doesn't + // re-arm one the checkpoint recorded: the tail's cancel replays before that re-arm. + canceled map[string]bool } // settle notes that a replayed settle settled the service id. @@ -1954,7 +1960,24 @@ func (m *armMirror) arm(effects []state.Effect) { if m == nil { return } - mirrorArmed(m.armed, effects, m.clock.lastRead()) + m.track(effects, m.clock.lastRead()) +} + +// track folds a replayed step's timer effects into the table at now, and notes the +// timers they cancel. +func (m *armMirror) track(effects []state.Effect, now time.Time) { + mirrorArmed(m.armed, effects, now) + for _, eff := range effects { + switch e := eff.(type) { + case state.ScheduleAfter: + delete(m.canceled, e.ID) + case state.CancelScheduled: + if m.canceled == nil { + m.canceled = map[string]bool{} + } + m.canceled[e.ID] = true + } + } } // mirrorTick arms in m any timer a replayed tick's chained transition scheduled, at the @@ -1966,7 +1989,7 @@ func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Sc } now := m.clock.lastRead() for i := range results { - mirrorArmed(m.armed, results[i].Effects, now) + m.track(results[i].Effects, now) m.forget(results[i].Effects) } dropUnscheduled(m.armed, sched) diff --git a/durable/service.go b/durable/service.go index 2e738290..66dde8cd 100644 --- a/durable/service.go +++ b/durable/service.go @@ -138,7 +138,7 @@ func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.Fire // The runner has already dropped the service, so this Handle can't run it again; // Recover re-arms it. fires := h.actorFires.take() - if err := h.stepCanceled(ctx, append([]error{res.Err}, parentFireErrs(fires)...)...); err != nil { + 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)) } diff --git a/durable/store.go b/durable/store.go index 4dbbbca9..41dd6adc 100644 --- a/durable/store.go +++ b/durable/store.go @@ -102,12 +102,15 @@ type Record struct { // drove, so Recover spawns it again without letting those reach the parent. It's // recorded as EndedActors is: with the first step after Start, then when a step // changes it, and an empty set is not nil. When the journal holds none, as on a - // Record from before this field, Recover lets every spawn reach the parent. Replay - // also reads a Record from a journal that has recorded this set, in the checkpoint - // or in that Record or one before it, as written by a version that arms the timers and - // services an actor-driven parent Fire's state declares, and arms them; it arms none - // for an older Record, as the run that wrote it didn't. + // Record from before this field, Recover lets every spawn reach the parent. UnstartedActors *ActorSet `json:",omitempty"` + + // Format is the journal format of the durable version that wrote the Record: zero on a + // Record from before this field, and 1 from the version that arms the timers and + // services an actor-driven parent Fire's state declares. Replay arms them only for a + // Record of format 1 or later, since an older run took no clock read for them. A + // Store keeps it as it keeps Step. + Format int `json:",omitempty"` } // ActorSet is a set of child-machine actor ids at a point in a durable instance's diff --git a/durable/timer_cancel_tail_test.go b/durable/timer_cancel_tail_test.go new file mode 100644 index 00000000..942e329e --- /dev/null +++ b/durable/timer_cancel_tail_test.go @@ -0,0 +1,75 @@ +package durable_test + +import ( + "context" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// cancelableTimerMachine arms an `after` timer on entering waiting, and `leave` exits +// waiting, which cancels it. left also takes elapsed, so a timer that wrongly stays +// armed shows when it fires. +func cancelableTimerMachine() *state.Machine[string, string, *timerCtx] { + return state.ForgeFor[*timerCtx]("cancelableTimer"). + Action("markFired", func(c state.ActionCtx[*timerCtx]) (state.Effect, error) { + c.Entity.Fired++ + return nil, nil + }). + State("idle"). + State("waiting"). + State("left"). + State("done").Final(). + Initial("idle"). + Transition("idle").On("arm").GoTo("waiting"). + Transition("waiting").On("poke").GoTo("waiting"). + Transition("waiting").On("leave").GoTo("left"). + Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("done").Do("markFired"). + // A timer left armed past leave would fire elapsed here, where it is visible. + Transition("left").On("elapsed").GoTo("done").Do("markFired"). + Quench() +} + +// TestRecover_KeepsATailCancelOfACheckpointTimer pins that a timer pending at a +// checkpoint and canceled by a later step stays canceled after Recover. The tail's +// cancel replays before Recover re-arms the checkpoint's timers, so the re-arm must +// skip a timer the tail canceled. +func TestRecover_KeepsATailCancelOfACheckpointTimer(t *testing.T) { + ctx := context.Background() + m := cancelableTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("tail-cancel") + clk := state.NewFakeClock(epoch) + h, err := durable.NewRunner(m, store, + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](2)). + Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + // arm and poke land a checkpoint while the timer is pending; leave, in the tail, + // cancels it. + for _, ev := range []string{"arm", "poke", "leave"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire(%q): %v", ev, err) + } + } + + recClock := state.NewFakeClock(epoch.Add(time.Hour)) + recovered, err := durable.Recover(ctx, m, store, id, + durable.WithRunnerClock[string, string, *timerCtx](recClock), + durable.WithCheckpointEvery[string, string, *timerCtx](2)) + if err != nil { + t.Fatalf("Recover: %v", err) + } + recClock.Advance(11 * time.Second) + if _, err = recovered.Tick(ctx); err != nil { + t.Fatalf("recovered Tick: %v", err) + } + snap := recovered.Instance().Snapshot() + if snap.Context.Fired != 0 || snap.Current != "left" { + t.Fatalf("after Recover the canceled timer fired: state %q, fired %d; want left, 0", snap.Current, snap.Context.Fired) + } +} diff --git a/durable/timetravel.go b/durable/timetravel.go index b25ecd26..070da5e0 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -138,7 +138,7 @@ func StateAt[S comparable, E comparable, C any]( return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } - if err := replayThrough(ctx, inst, &cfg, bounded, unmarshalCheckpoint(baseline).UnstartedActors != nil); err != nil { + if err := replayThrough(ctx, inst, &cfg, bounded); err != nil { return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } return &TimeTravelView[S, E, C]{inst: inst, step: step}, nil @@ -223,14 +223,12 @@ func restoreBaseline[S comparable, E comparable, C any]( // It is the bounded, read-only analog of Recover's replay loop: it builds its own // service host driver (to settle recorded outcomes) and ticks a scheduler over the // instance's recorded-instant clock, consuming exactly the records the caller bounded -// to the target step. actorArms reports whether the baseline was written by a version -// that arms an actor-driven Fire's timers and services. +// to the target step. func replayThrough[S comparable, E comparable, C any]( ctx context.Context, inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], bounded []Record, - actorArms bool, ) error { sched := state.NewScheduler(inst) @@ -247,8 +245,7 @@ func replayThrough[S comparable, E comparable, C any]( } // A domain effect is never dispatched here: a time-travel read applies no // side effect. - actorArms = armsActorFires(actorArms, &bounded[i]) - if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, actorArms); err != nil { + if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, armsActorFires(&bounded[i])); err != nil { return err } } From 1224eb263773cc2e27c8259c68efa99266205c15 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Sun, 15 Nov 2026 14:46:25 -0700 Subject: [PATCH 24/38] fix(durable): restore a checkpoint's timers before replay; don't retry a refused onError Recover restored a checkpoint's pending timers only after the tail walk, so a tail Tick that fired one live fired nothing on replay, and the timer was re-armed and fired again. Recover now arms them into the replay scheduler at their persisted deadlines before the walk, through state's new Scheduler.ArmAt, which takes no clock reading. Tail cancels and Ticks then act on them as they did live, which replaces the canceled-timer filter. A spawn whose onError a guard or middleware refused counted as unstarted, so every Recover ran its behavior again. It now counts as handled. A spawn with no onError to route to, or whose onError a context's ending refused, is still retried. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 38 +++++-- durable/checkpoint.go | 60 +++++----- durable/checkpoint_internal_test.go | 161 ++++++++++++++++++++------- durable/clock.go | 9 +- durable/clock_internal_test.go | 2 +- durable/doc.go | 5 +- durable/runner.go | 118 ++++++++++---------- durable/step_rule_test.go | 163 ++++++++++++++++++++++++++-- durable/store.go | 21 ++-- durable/timer_cancel_tail_test.go | 153 ++++++++++++++++++++++++++ state/CHANGELOG.md | 6 + state/driver.go | 14 +++ state/scheduler_test.go | 78 +++++++++++++ 13 files changed, 663 insertions(+), 165 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 5e98b054..136c9ac5 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -13,7 +13,8 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ran and have ended, settled or stopped, so `Recover` doesn't spawn them again. A Store must keep an empty set distinct from nil. - **`Record.UnstartedActors`** records the declared actors that aren't running and - haven't ended, because their spawn failed with no onError, so `Recover` can tell them + haven't ended, because their spawn failed with no onError to route to, or its + onError was refused because a context ended, so `Recover` can tell them from the actors that were running. A Store must keep an empty set distinct from nil. - **`Record.Format`** records the journal format of the version that wrote the Record, which is 1 from this version. Replay arms the timers and services an actor-driven @@ -183,8 +184,11 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. without leaving the state, or an explicit stop. Each step now records the declared actors that ran and ended, in the new `Record.EndedActors`, and a checkpoint keeps the set, so `Recover` spawns the declared actors that aren't in it. An actor whose spawn - failed with no onError never ran, so `Recover` tries it again, as before; one whose - onError applied counts as ended, since the journal holds that onError. A journal from before this + failed with no onError to route to never ran, so `Recover` tries it again, as before, + and so does one whose onError a context's ending refused, since the step that drove + it records nothing; one whose onError applied counts as ended, since the journal + holds that onError, and, from the refused-onError fix below, so does one whose + onError was refused for another reason replay meets again. A journal from before this records no set, and `Recover` spawns every declared actor, as before. - **A failed spawn's onError, and a settle an absorb drove, are journaled.** When an actor a `Fire`, `RunService`, `Start` or `Recover` spawned couldn't start and its @@ -195,6 +199,16 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. `Start`'s and `Recover`'s spawns, with the step after, and replay re-fires each where it ran. An actor output that has no JSON form now fails the Handle here too, as it does for a delivery. +- **A spawn whose onError was refused deterministically isn't retried.** A failed + spawn counted as handled only when its onError Fire applied, so one whose onError + was refused for a reason other than a context ending — a guard returning false — + landed in `UnstartedActors`, and every `Recover` spawned it again: the behavior, + and any side effect it ran, re-executed each time, and each recovery journaled + another refused onError. Such a refusal now counts as handled — the journal + already records it, and replay meets it again — so the actor counts as ended and + `Recover` leaves it alone. A spawn whose onError a context's ending refused still + retries, since the step that drove it records nothing, as does one with no onError + to route to, none declared or none the parent handles, as before. - **A message an actor sends its parent as it spawns applies once.** A `Fire`, `RunService`, `Start` or `Recover` didn't journal it, and `Recover` spawned the actor again to send it again: it landed after the steps that followed it live, or never, if @@ -216,13 +230,23 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. took no clock read for them, and its Records replay as they did. A service's settle re-arms its state's timers on replay too, and `DeliverToActor` and `RunService` now journal the clock reads their step took, so a checkpoint on that step can't leave - a read for the next to replay. `Recover` re-arms a checkpoint's timers before it - spawns the running actors, so a Fire one of theirs drives can cancel one. A timer - the checkpoint recorded and a later step canceled stays canceled: `Recover` used to - re-arm it, since that step's cancel replays before the re-arm. A `Tick` + a read for the next to replay. `Recover` restores a checkpoint's timers before the + replay walk, so a tail step, or a Fire one of the recovered spawns drives, acts on + them as the live run did. A `Tick` drops from the timers a checkpoint records exactly the ones it fired, live and on replay: one that came due between its clock reads, and a chained one it armed and fired, used to stay, so a `Recover` from a later checkpoint fired it again. +- **A checkpoint's timers are restored before the replay walk.** `Recover` armed them + only after replaying the journal's tail, so a tail `Tick` that fired one of them + live fired nothing in replay: the recovered `Handle` kept the pre-tick state, the + timer was then armed and fired a second time on top of it, and a later tail Record + that needed the post-tick state failed replay. The timers are now armed into the + replay scheduler at their recorded absolute deadlines before the walk — taking no + clock reading, so the walk's recorded readings still land in order — and a tail + `Tick` fires one, and a later tail Fire moves on from the state it reached, exactly + as live did. A timer the checkpoint recorded and a later step canceled stays + canceled the same way: its cancel replays against the restored timer, where + `Recover` used to re-arm it after the cancel had replayed. - **A delivery journals each parent Fire under the actor that drove it,** where it used to record every one under the actor delivered to. It no longer copies the instance's history twice per delivery to do it. diff --git a/durable/checkpoint.go b/durable/checkpoint.go index 7377041e..a671cb24 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -23,10 +23,11 @@ import ( // The declared `after` Delay re-arms a fresh timer at now+Delay; a timer pending at // a checkpoint has already burned part of its delay, so the durable layer persists // each armed timer's absolute deadline alongside the checkpoint and, on recovery, -// re-arms the remainder (deadline − resumed now) rather than the full declared -// Delay. The deadline is itself a recorded clock read, so the re-armed timer fires -// at the same recorded instant regardless of the wall clock at recovery time, and -// the recovered run is byte-identical to one that never crashed. +// arms it at that deadline — through the scheduler's ArmAt, which reads no clock — +// before the replay walk, so a tail Tick or cancel acts on it as it did live. The +// deadline is itself a recorded clock read, so the re-armed timer fires at the same +// recorded instant regardless of the wall clock at recovery time, and the recovered +// run is byte-identical to one that never crashed. // pendingTimer is one armed delayed (`after`) timer the durable Handle tracks // alongside the kernel scheduler, so its absolute deadline can be persisted at a @@ -40,7 +41,7 @@ type pendingTimer struct { // scheduler's pending set key identically. id string // due is the timer's absolute fire deadline (the recorded arming clock read plus - // the declared Delay), the value persisted so recovery re-arms the remainder. + // the declared Delay), the value persisted so recovery re-arms it at that deadline. due time.Time // event is the delayed event the timer re-fires through Fire when it elapses, // type-erased for the abstract ScheduleAfter surface and re-typed by the @@ -150,7 +151,7 @@ func unmarshalCheckpoint(b []byte) checkpointEnvelope { // decodeTimerEvent decodes a persisted timer event wire back into the machine's // event type E through the same codec the Runner replays driving events with, so -// the re-armed ScheduleAfter carries a correctly-typed event the scheduler accepts. +// the re-armed timer carries a correctly-typed event the scheduler accepts. func decodeTimerEvent[E comparable](codec EventCodec[E], raw json.RawMessage) (E, error) { return codec.Decode(raw) } @@ -171,38 +172,33 @@ func mirrorArmed(armed map[string]pendingTimer, effects []state.Effect, now time } } -// reArmEffects builds the ScheduleAfter effects that re-arm persisted timers at -// their recorded absolute deadlines, relative to now: each timer's remaining delay -// is its deadline minus now, so absorbing the effects through the live scheduler -// reproduces the same absolute deadline the live run held. A deadline already at or -// before now yields a non-positive delay, which the scheduler arms as immediately -// due, so an elapsed-while-down timer fires on the next Tick. Timers whose id is -// already armed (re-established by tail replay) are skipped, so a timer the tail -// still carries is not double-armed. Returns the effects and the durable-side -// pendingTimer table to seed the Handle, both in scheduleID order. -func reArmEffects[E comparable]( +// armPersistedTimers arms each timer the checkpoint persisted into the replay +// scheduler at its recorded absolute deadline, and seeds the mirror's armed table +// with it, before the replay walk: a tail Tick that fired one of them live fires it +// in replay too, and a tail cancel leaves it canceled, as each acted live. It must +// take no clock reading: during the walk the replay clock hands out the recorded +// readings in order, and a read taken before the walk would consume the reading +// that belongs to the first tail Record and shift every later one. So each timer is +// armed through Scheduler.ArmAt at its persisted deadline, not through Absorb, +// which reads the clock to turn a delay into a deadline. The mirror's table is the +// Handle's timer table after Recover: the walk folds the tail's schedules, cancels +// and fired timers into it, so it ends with each still-pending timer at its +// persisted deadline. A deadline already in the past arms as immediately due, so a +// timer that elapsed while the instance was down fires on the next Tick. +func armPersistedTimers[S comparable, E comparable, C any]( codec EventCodec[E], + sched *state.Scheduler[S, E, C], wires []pendingTimerWire, - already map[string]pendingTimer, - now time.Time, -) ([]state.Effect, map[string]pendingTimer, error) { - var effects []state.Effect - seeded := map[string]pendingTimer{} + armed map[string]pendingTimer, +) error { for _, w := range wires { - if _, armed := already[w.ID]; armed { - continue // tail replay already re-armed this timer; do not double-arm. - } ev, err := decodeTimerEvent(codec, w.Event) if err != nil { - return nil, nil, fmt.Errorf("durable: decoding pending timer %q event: %w", w.ID, err) + return fmt.Errorf("durable: decoding pending timer %q event: %w", w.ID, err) } due := time.Unix(0, w.DueUnixNano).UTC() - effects = append(effects, state.ScheduleAfter{ - ID: w.ID, - Delay: due.Sub(now), - Event: ev, - }) - seeded[w.ID] = pendingTimer{id: w.ID, due: due, event: ev} + sched.ArmAt(w.ID, ev, due) + armed[w.ID] = pendingTimer{id: w.ID, due: due, event: ev} } - return effects, seeded, nil + return nil } diff --git a/durable/checkpoint_internal_test.go b/durable/checkpoint_internal_test.go index 282ee6a3..38660f15 100644 --- a/durable/checkpoint_internal_test.go +++ b/durable/checkpoint_internal_test.go @@ -1,6 +1,7 @@ package durable import ( + "context" "encoding/json" "testing" "time" @@ -81,59 +82,91 @@ func TestUnmarshalCheckpoint_Garbage(t *testing.T) { } } -// TestReArmEffects_SkipsAlreadyArmed confirms a persisted timer already armed by -// tail replay is not re-armed (no double-arm), while an un-armed one is re-armed at -// its remaining delay. -func TestReArmEffects_SkipsAlreadyArmed(t *testing.T) { - now := time.Unix(0, 1_000_000_000).UTC() +// armingMachine is a minimal machine for the arming tests: idle -elapsed-> fired, +// so a Tick that fires an armed timer moves the instance. +func armingMachine() *state.Machine[string, string, int] { + return state.ForgeFor[int]("arming"). + State("idle"). + State("fired"). + Initial("idle"). + Transition("idle").On("elapsed").GoTo("fired"). + // fired keeps a self-loop, so a second armed timer fires cleanly once the + // first has moved the instance there. + Transition("fired").On("elapsed").GoTo("fired"). + Quench() +} + +// readCountClock wraps a Clock and counts its Now() readings, so a test can prove +// an arming took none. +type readCountClock struct { + state.Clock + reads int +} + +func (c *readCountClock) Now() time.Time { + c.reads++ + return c.Clock.Now() +} + +func (c *readCountClock) Advance(d time.Duration) { + c.Clock.(interface{ Advance(time.Duration) }).Advance(d) +} + +// TestArmPersistedTimers_ArmsAtTheDeadlineWithoutReadingTheClock confirms the +// pre-walk arming arms each persisted timer into the scheduler at its recorded +// absolute deadline and seeds the mirror's table, taking no clock reading: a read +// there would consume the recorded reading the first tail Record owns. A deadline +// already in the past fires on the next Tick, and a later one when the clock +// reaches it. +func TestArmPersistedTimers_ArmsAtTheDeadlineWithoutReadingTheClock(t *testing.T) { + base := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC) + clk := &readCountClock{Clock: state.NewFakeClock(base)} + inst := armingMachine().Cast(0, state.WithInitialState("idle"), state.WithClock[string](clk)) + sched := state.NewScheduler(inst) + past := base.Add(-3 * time.Second) + future := base.Add(8 * time.Second) wires := []pendingTimerWire{ - {ID: "armed", DueUnixNano: now.Add(5 * time.Second).UnixNano(), Event: json.RawMessage(`"x"`)}, - {ID: "compacted", DueUnixNano: now.Add(8 * time.Second).UnixNano(), Event: json.RawMessage(`"y"`)}, - } - already := map[string]pendingTimer{"armed": {id: "armed"}} - effects, seeded, err := reArmEffects[string](jsonEventCodec[string]{}, wires, already, now) - if err != nil { - t.Fatalf("reArmEffects: %v", err) - } - if len(effects) != 1 || len(seeded) != 1 { - t.Fatalf("want exactly the compacted timer re-armed, got effects=%d seeded=%d", len(effects), len(seeded)) + {ID: "past", DueUnixNano: past.UnixNano(), Event: json.RawMessage(`"elapsed"`)}, + {ID: "future", DueUnixNano: future.UnixNano(), Event: json.RawMessage(`"elapsed"`)}, } - sa, ok := effects[0].(state.ScheduleAfter) - if !ok || sa.ID != "compacted" { - t.Fatalf("want compacted ScheduleAfter, got %+v", effects[0]) + armed := map[string]pendingTimer{} + if err := armPersistedTimers[string, string, int](jsonEventCodec[string]{}, sched, wires, armed); err != nil { + t.Fatalf("armPersistedTimers: %v", err) } - if sa.Delay != 8*time.Second { - t.Fatalf("remaining delay: want 8s, got %s", sa.Delay) + if clk.reads != 0 { + t.Fatalf("arming took %d clock readings, want none", clk.reads) } -} - -// TestReArmEffects_ElapsedDeadlineImmediate confirms a deadline already at or before -// now yields a non-positive delay (armed as immediately due), so an elapsed-while- -// down timer fires on the next Tick. -func TestReArmEffects_ElapsedDeadlineImmediate(t *testing.T) { - now := time.Unix(0, 10_000_000_000).UTC() - wires := []pendingTimerWire{ - {ID: "past", DueUnixNano: now.Add(-3 * time.Second).UnixNano(), Event: json.RawMessage(`"z"`)}, + for id, due := range map[string]time.Time{"past": past, "future": future} { + if !sched.HasPending(id) { + t.Fatalf("timer %q not armed", id) + } + if got := armed[id]; got.id != id || !got.due.Equal(due) { + t.Fatalf("armed table for %q = %+v, want due %v", id, got, due) + } } - effects, _, err := reArmEffects[string](jsonEventCodec[string]{}, wires, map[string]pendingTimer{}, now) - if err != nil { - t.Fatalf("reArmEffects: %v", err) + // The elapsed deadline fires on the next Tick; the future one stays armed. + fired := sched.Tick(context.Background()) + if len(fired) != 1 || inst.Current() != "fired" { + t.Fatalf("tick fired %d, state %q, want the elapsed timer alone", len(fired), inst.Current()) } - if len(effects) != 1 { - t.Fatalf("want 1 effect, got %d", len(effects)) + if !sched.HasPending("future") { + t.Fatal("the future timer should stay armed") } - if sa := effects[0].(state.ScheduleAfter); sa.Delay > 0 { - t.Fatalf("elapsed deadline should arm non-positive delay, got %s", sa.Delay) + clk.Advance(8 * time.Second) + if fired = sched.Tick(context.Background()); len(fired) != 1 { + t.Fatalf("tick at the deadline fired %d, want the future timer", len(fired)) } } -// TestReArmEffects_BadEventErrors surfaces a decode failure for a corrupt persisted -// timer event rather than silently dropping the timer. -func TestReArmEffects_BadEventErrors(t *testing.T) { +// TestArmPersistedTimers_BadEventErrors surfaces a decode failure for a corrupt +// persisted timer event rather than silently dropping the timer. +func TestArmPersistedTimers_BadEventErrors(t *testing.T) { wires := []pendingTimerWire{ {ID: "bad", DueUnixNano: 1, Event: json.RawMessage(`{not valid`)}, } - _, _, err := reArmEffects[string](jsonEventCodec[string]{}, wires, map[string]pendingTimer{}, time.Unix(0, 0)) + clk := state.NewFakeClock(time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC)) + inst := armingMachine().Cast(0, state.WithInitialState("idle"), state.WithClock[string](clk)) + err := armPersistedTimers[string, string, int](jsonEventCodec[string]{}, state.NewScheduler(inst), wires, map[string]pendingTimer{}) if err == nil { t.Fatal("want decode error for corrupt timer event, got nil") } @@ -171,3 +204,51 @@ func unmarshalCheckpointParts(b []byte) ([]byte, []pendingTimerWire, int) { env := unmarshalCheckpoint(b) return env.Snapshot, env.Timers, env.NextStep } + +// TestRecover_SeedsTheTimerTableWithThePersistedDeadline proves the Handle's timer +// table after a Recover whose tail replays no timer step ends with each +// still-pending timer at its persisted absolute deadline, so the next checkpoint +// persists it again and the recovered scheduler holds it armed. +func TestRecover_SeedsTheTimerTableWithThePersistedDeadline(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[int]("seeded"). + State("idle"). + State("waiting"). + State("done").Final(). + Initial("idle"). + Transition("idle").On("arm").GoTo("waiting"). + Transition("waiting").On("poke").GoTo("waiting"). + Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("done"). + Quench() + base := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC) + store, id := NewMemStore(), InstanceID("seeded") + h, err := NewRunner(m, store, + WithRunnerClock[string, string, int](state.NewFakeClock(base)), + WithCheckpointEvery[string, string, int](2)). + Start(ctx, id, 0, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for _, ev := range []string{"arm", "poke"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire(%q): %v", ev, err) + } + } + rec, err := Recover(ctx, m, store, id, + WithRunnerClock[string, string, int](state.NewFakeClock(base.Add(time.Hour))), + WithCheckpointEvery[string, string, int](2)) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if len(rec.timers) != 1 { + t.Fatalf("recovered timer table = %v, want one pending timer", rec.timers) + } + for id, pt := range rec.timers { + if want := base.Add(10 * time.Second); !pt.due.Equal(want) { + t.Fatalf("timer %q due %v, want the persisted %v", id, pt.due, want) + } + if !rec.sched.HasPending(id) { + t.Fatalf("timer %q is in the table but not armed on the scheduler", id) + } + } +} diff --git a/durable/clock.go b/durable/clock.go index 60682ad9..9d261f38 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -128,9 +128,10 @@ func (c *recordingClock) lastReadingSince(i int) (time.Time, bool) { // readings and returns each once. // // When the cursor is exhausted — a Now() beyond the recorded readings, which -// happens on the live re-arm after replay — it falls through to a real clock so -// post-recovery timing continues against wall time. The fallthrough never affects -// the replayed prefix, which is fully determined by the journal. +// happens once replay is over and the recovered run reads the clock live, as when +// a timer an actor Recover spawns drives arms — it falls through to a real clock +// so post-recovery timing continues against wall time. The fallthrough never +// affects the replayed prefix, which is fully determined by the journal. type replayClock struct { mu sync.Mutex readings []int64 @@ -140,7 +141,7 @@ type replayClock struct { } // newReplayClock builds a replayClock over the recorded readings, falling through -// to fallback once the readings are exhausted (the live re-arm after replay). +// to fallback once the readings are exhausted and the recovered run reads live. func newReplayClock(readings []int64, fallback state.Clock) *replayClock { return &replayClock{readings: readings, fallback: fallback} } diff --git a/durable/clock_internal_test.go b/durable/clock_internal_test.go index a0a01241..b6824946 100644 --- a/durable/clock_internal_test.go +++ b/durable/clock_internal_test.go @@ -54,7 +54,7 @@ func TestRecordingClock_AfterDelegates(t *testing.T) { // TestReplayClock_ReturnsRecordedThenFallsThrough confirms a replay clock returns // the recorded readings in order, then falls through to its fallback once the -// readings are exhausted (the live re-arm after replay). +// readings are exhausted and the recovered run reads the clock live. func TestReplayClock_ReturnsRecordedThenFallsThrough(t *testing.T) { readings := []int64{ clockEpoch.UnixNano(), diff --git a/durable/doc.go b/durable/doc.go index 559ca3b4..9eecd756 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -96,8 +96,9 @@ // instants regardless of the wall clock at recovery time. A timer also survives // checkpoint compaction: each checkpoint persists the absolute deadlines of the // timers armed at that instant; on recovery a timer whose arming ScheduleAfter -// was compacted out of the tail is re-armed from its persisted deadline rather -// than lost. +// was compacted out of the tail is re-armed from its persisted deadline before +// the tail replays — so a tail Tick that fired it live, or a tail cancel, acts on +// it as the live run did — rather than lost. // // Invoked services (WithServiceRegistry): a service (`invoke`) runs on the live path; // its result is journaled as a JournalServiceResult. On recovery the recorded result is diff --git a/durable/runner.go b/durable/runner.go index af86c4e7..efa37379 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -666,7 +666,7 @@ type parentFires[S comparable] struct { fires []state.ParentFire[S] spawned map[string]bool // actors whose latest spawn this step started attempted map[string]bool // actors the system was asked to spawn this step - failed map[string]bool // actors whose latest spawn failed and whose onError applied + failed map[string]bool // actors whose latest spawn failed and whose onError applied, or was refused for a reason other than a context ending or an unroutable onError } // attempt notes the actors effects ask the system to spawn. @@ -719,9 +719,15 @@ func (p *parentFires[S]) inspect(ev state.InspectionEvent) { func (p *parentFires[S]) note(pf state.ParentFire[S]) { p.mu.Lock() p.fires = append(p.fires, pf) - // A spawn whose onError applied is handled: the journal holds the onError, so - // retrying the spawn would apply it twice. - if pf.SpawnFailed && pf.Result.Err == nil { + // A spawn whose onError applied is handled: the journal holds that onError, so + // retrying the spawn would apply it twice. One whose onError was refused for a + // reason other than a context ending — a failing guard, say — is handled too: + // the journal records the refusal, replay meets it again, and a retry would + // re-run the behavior and journal another refusal. One a context's ending + // refused, and one whose parent had no transition for its onError event, are + // not: the first left the step that drove it recording nothing, and the second + // is the spawn's having no onError to route to, so a retry is right for both. + if pf.SpawnFailed && spawnErrorHandled(pf.Result.Err) { if p.failed == nil { p.failed = map[string]bool{} } @@ -1183,9 +1189,13 @@ func (r *recordedSet) note(now *ActorSet) { // keeps a settled actor), or when this step asked the system to spawn it and the latest // of those spawns started it (then something stopped it), or, when this step didn't try // to spawn it, when it was running or ended at the previous step. A spawn whose onError -// applied also counts as ended, since the journal holds that onError. So an actor whose -// spawn failed with no onError, at entry or on a re-entry, hasn't ended: it's unstarted, -// and Recover tries it again. Both are nil with no actor palette. +// applied, or whose onError was refused for a reason other than a context ending and +// other than the parent's having no transition for it, also counts as ended, since the +// journal holds that onError, or the refusal replay meets again. So an actor whose +// spawn failed with no onError to route to — none declared, or none the parent handles +// — or whose onError a context's ending refused, which left the step that drove it +// recording nothing, hasn't ended: it's unstarted, and Recover tries it again. Both are +// nil with no actor palette. func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { if h.actors == nil { return nil, nil @@ -1360,10 +1370,10 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S actorBuf := make([]state.JournalEntry, 0) actors, actorFires := r.newActorSystem(inst) - // armed mirrors the scheduler's pending timers re-established by tail replay, - // with their recorded deadlines, so a persisted-but-compacted timer is re-armed - // only when the tail did not already re-arm it, and the Handle's table is seeded - // with every still-pending timer's deadline for the next checkpoint. + // armed is the Handle's timer table: it starts with the timers the checkpoint + // persisted, armed into the replay scheduler below, and the walk folds the tail's + // schedules, cancels and fired timers into it, so it ends with every still-pending + // timer's deadline for the next checkpoint. armed := map[string]pendingTimer{} // mirror tracks, as replay walks the tail, the still-pending timers in armed and the @@ -1374,6 +1384,16 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S mirror.settle(sv) } + // Arm the checkpoint's persisted timers into the replay scheduler at their + // recorded absolute deadlines, BEFORE the walk, so the tail acts on them as the + // live run did: a tail Tick that fired one fires it in replay, reaching the same + // state, and a tail cancel leaves it canceled. A tail Record that needs the + // post-tick state then replays against it. The arming takes no clock reading, so + // the walk's first tail Record still gets its own recorded reading. + if err := armPersistedTimers(r.cfg.eventCodec, sched, persistedTimers, armed); err != nil { + return nil, fmt.Errorf("durable: re-arming pending timers for %q: %w", id, err) + } + // ended is the latest recorded set of the declared actors the live run had ended: // the checkpoint's, then each tail Record's that records one. Nil means none was // recorded, so Recover spawns every actor the configuration declares. @@ -1418,35 +1438,6 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // readings): they belong to no new step and must not leak into the next Fire. buf = buf[:0] - // Re-arming reads the clock past the journal, and so can arming a timer for a parent - // Fire an actor Recover spawns drives, which the next step records: re-arm before the - // spawns, so the re-arm's read can be dropped while theirs are kept, and so one of - // their Fires can cancel a re-armed timer. - // - // Re-arm any timer that was pending at the checkpoint but whose arming - // ScheduleAfter was compacted out of the tail, so it survives compaction: the - // tail replay could not re-arm it (its arm is gone), so re-arm it here at its - // persisted absolute deadline. Already-armed timers (re-established by the tail) - // are skipped, so a timer the tail still carried is never double-armed. The - // remaining delay is the persisted deadline minus the recovery clock's now, so - // the re-armed timer fires at its recorded instant — an already-elapsed deadline - // arms as immediately due and fires on the next Tick. - // A timer the tail canceled stays canceled: its cancel replayed before this re-arm. - persistedTimers = slices.DeleteFunc(persistedTimers, func(w pendingTimerWire) bool { return mirror.canceled[w.ID] }) - reEffects, reSeeded, reErr := reArmEffects(r.cfg.eventCodec, persistedTimers, armed, repClock.Now()) - if reErr != nil { - return nil, fmt.Errorf("durable: re-arming pending timers for %q: %w", id, reErr) - } - if len(reEffects) > 0 { - sched.Absorb(ctx, reEffects) - } - for id, pt := range reSeeded { - armed[id] = pt - } - // The re-arm reads the recovery clock to compute remaining delays; that reading - // belongs to no recorded step and must not leak into the next Fire's Record. - buf = buf[:0] - // The next step ordinal continues past the highest assigned step. Step ordinals // are assigned monotonically: each Record consumes one ordinal regardless of how // many parent Traces it produced (an actor delivery can drive several), except a @@ -1720,6 +1711,29 @@ func (jsonEventCodec[E]) Decode(payload []byte) (E, error) { return e, err } +// spawnErrorHandled reports whether the onError Fire of a failed spawn leaves the +// spawn handled, so the journal's actor sets count it as ended and Recover doesn't +// retry it: the Fire applied (err is nil), or it was refused for a reason other +// than a context ending — a failing guard, say — which the journal records and +// replay meets again. A context's ending leaves it unhandled: the step that drove +// the Fire records nothing, so a retry is right. So does the parent's having no +// transition for the onError event, the same "no onError to route to" as an +// undeclared one, matching the kernel's own reading of that outcome: the spawn +// stays unstarted, and Recover tries it again, as it always has. +func spawnErrorHandled(err error) bool { + if err == nil { + return true + } + if isContextErr(err) { + return false + } + var it *state.InvalidTransitionError + if errors.As(err, &it) && it.Reason == "no transition declared for this state and event" { + return false + } + return true +} + // isContextErr reports whether err is a context's cancellation or deadline, which a // Store may report for either when the caller's context ends. func isContextErr(err error) bool { @@ -1929,9 +1943,6 @@ type armMirror struct { armed map[string]pendingTimer clock *replayClock settled map[string]bool - // canceled holds the timers replay canceled and didn't arm again, so Recover doesn't - // re-arm one the checkpoint recorded: the tail's cancel replays before that re-arm. - canceled map[string]bool } // settle notes that a replayed settle settled the service id. @@ -1960,24 +1971,7 @@ func (m *armMirror) arm(effects []state.Effect) { if m == nil { return } - m.track(effects, m.clock.lastRead()) -} - -// track folds a replayed step's timer effects into the table at now, and notes the -// timers they cancel. -func (m *armMirror) track(effects []state.Effect, now time.Time) { - mirrorArmed(m.armed, effects, now) - for _, eff := range effects { - switch e := eff.(type) { - case state.ScheduleAfter: - delete(m.canceled, e.ID) - case state.CancelScheduled: - if m.canceled == nil { - m.canceled = map[string]bool{} - } - m.canceled[e.ID] = true - } - } + mirrorArmed(m.armed, effects, m.clock.lastRead()) } // mirrorTick arms in m any timer a replayed tick's chained transition scheduled, at the @@ -1989,7 +1983,7 @@ func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Sc } now := m.clock.lastRead() for i := range results { - m.track(results[i].Effects, now) + mirrorArmed(m.armed, results[i].Effects, now) m.forget(results[i].Effects) } dropUnscheduled(m.armed, sched) diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index dbb98ffc..7f557289 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -765,11 +765,12 @@ func TestRecover_ReplaysASpawnsOnErrorOnce(t *testing.T) { }) } -// TestRecover_RetriesASpawnWhoseLatestOnErrorWasRefused proves the latest spawn attempt -// decides: a failed spawn's onError applies and re-enters the state, the spawn there -// fails too, and the parent refuses that onError, so the actor isn't handled and -// Recover tries it again. -func TestRecover_RetriesASpawnWhoseLatestOnErrorWasRefused(t *testing.T) { +// TestRecover_HandlesASpawnWhoseLatestOnErrorWasRefused proves the latest spawn attempt +// decides, and a refused onError that isn't a context's ending counts as handled: a +// failed spawn's onError applies and re-enters the state, the spawn there fails too, +// and the parent refuses that onError for its guard — so the journal holds the +// refusal, Recover doesn't retry the spawn, and the behavior never runs again. +func TestRecover_HandlesASpawnWhoseLatestOnErrorWasRefused(t *testing.T) { ctx := context.Background() fail := func(in state.AssignCtx[stepCtx]) stepCtx { c := in.Entity @@ -787,20 +788,36 @@ func TestRecover_RetriesASpawnWhoseLatestOnErrorWasRefused(t *testing.T) { Transition("spawning").On("spawnFailed").GoTo("spawning").Reenter().When("firstFailure").Assign("noteFail"). Quench() store, id := durable.NewMemStore(), durable.InstanceID("again") - failing := durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnChild": failingSpawn(nil)}) - h, err := durable.NewRunner(m, store, failing).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + var calls int + palette := durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "spawnChild": func(map[string]any) (state.ActorInstance, error) { + calls++ + return nil, errors.New("the child can't start") + }, + }) + h, err := durable.NewRunner(m, store, palette).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) if err != nil { t.Fatalf("Start: %v", err) } if _, err = h.Fire(ctx, "start"); err != nil { t.Fatalf("Fire(start): %v", err) } - recovered, err := durable.Recover(ctx, m, store, id, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"spawnChild": finishingChild()})) + if calls != 2 { + t.Fatalf("live ran the behavior %d times, want the two failed spawns of one step", calls) + } + liveState, liveNotes := h.Instance().Current(), fmt.Sprint(h.Instance().Entity().Notes) + recovered, err := durable.Recover(ctx, m, store, id, palette) if err != nil { t.Fatalf("Recover: %v", err) } - if _, ok := recovered.ActorRef(state.ActorID("again", "spawning", 0)); !ok { - t.Fatal("Recover didn't retry the spawn whose latest onError the parent refused") + if calls != 2 { + t.Fatalf("Recover ran the behavior again: %d calls, want the two live ones", calls) + } + if got, notes := recovered.Instance().Current(), fmt.Sprint(recovered.Instance().Entity().Notes); got != liveState || notes != liveNotes { + t.Fatalf("recovered %s %s, want the live %s %s", got, notes, liveState, liveNotes) + } + if _, ok := recovered.ActorRef(state.ActorID("again", "spawning", 0)); ok { + t.Fatal("Recover retried the spawn whose latest onError the parent refused") } } @@ -941,3 +958,129 @@ func TestStart_SucceedsWhenItsContextEndsWithNoRefusal(t *testing.T) { }) } } + +// guardedSpawnMachine is idle -start-> spawning, whose actor can't start: its +// onError is guarded false, so the parent refuses it deterministically and the +// spawn stays where it is. +func guardedSpawnMachine() stepMachine { + return state.ForgeFor[stepCtx]("guarded"). + Guard("never", func(state.GuardCtx[stepCtx]) bool { return false }). + Actor("spawnChild"). + State("idle"). + State("spawning").InvokeActor("spawnChild", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed").When("never"). + Transition("spawning").On("poke").GoTo("spawning"). + Quench() +} + +// TestRecover_RunsAGuardedSpawnOnce proves a spawn whose onError was refused for a +// reason other than a context ending, here a guard, is handled: the journal holds +// the refusal and replay meets it again, so the behavior runs once live and no +// Recover runs it again, with or without a checkpoint compacting the step. +func TestRecover_RunsAGuardedSpawnOnce(t *testing.T) { + ctx := context.Background() + for _, every := range []int{0, 1} { + t.Run(fmt.Sprintf("checkpoint every %d", every), func(t *testing.T) { + m := guardedSpawnMachine() + store, id := durable.NewMemStore(), durable.InstanceID("guarded") + var calls int + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "spawnChild": failingSpawn(func() { calls++ }), + })} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if calls != 1 { + t.Fatalf("live ran the behavior %d times, want once", calls) + } + liveState, liveNotes := h.Instance().Current(), fmt.Sprint(h.Instance().Entity().Notes) + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d: %v", round, err) + } + if calls != 1 { + t.Fatalf("Recover %d ran the behavior again: %d calls, want the one live call", round, calls) + } + if got, notes := recovered.Instance().Current(), fmt.Sprint(recovered.Instance().Entity().Notes); got != liveState || notes != liveNotes { + t.Fatalf("Recover %d = %s %s, want the live %s %s", round, got, notes, liveState, liveNotes) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } + }) + } +} + +// TestRecover_RetriesAGuardedSpawnOnlyWhenAContextRefusedItsOnError proves the +// context case keeps its retry: a spawn whose onError a context's ending refused +// was recorded nowhere, so Recover runs the behavior again, and once a live +// context refuses the onError for the guard's reason instead, the next step +// journals it and later Recovers leave the behavior alone. +func TestRecover_RetriesAGuardedSpawnOnlyWhenAContextRefusedItsOnError(t *testing.T) { + ctx := context.Background() + m := guardedSpawnMachine() + store, id := durable.NewMemStore(), durable.InstanceID("guarded-ctx") + var calls int + // countingSpawn counts each run and runs hook, if any, before failing. + countingSpawn := func(hook func()) state.ActorBehavior { + return func(map[string]any) (state.ActorInstance, error) { + calls++ + if hook != nil { + hook() + } + return nil, errors.New("the child can't start") + } + } + palette := func(hook func()) stepOption { + return durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "spawnChild": countingSpawn(hook), + }) + } + turn, cancel := context.WithCancel(ctx) + defer cancel() + h, err := durable.NewRunner(m, store, palette(cancel)).Start(turn, id, stepCtx{}, state.WithInitialState("spawning")) + if h != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("Start = Handle %v, %v, want no Handle and context.Canceled", h != nil, err) + } + if calls != 1 { + t.Fatalf("Start ran the behavior %d times, want once", calls) + } + // Nothing was recorded, so Recover retries the spawn; with a live context the + // parent refuses its onError for the guard's reason, which the next step + // journals. + recovered, err := durable.Recover(ctx, m, store, id, palette(nil)) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if calls != 2 { + t.Fatalf("Recover ran the behavior %d times, want the retry to make two", calls) + } + if got := recovered.Instance().Current(); got != "spawning" { + t.Fatalf("recovered state = %q, want spawning", got) + } + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + again, err := durable.Recover(ctx, m, store, id, palette(nil)) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if calls != 2 { + t.Fatalf("second Recover ran the behavior again: %d calls, want two", calls) + } + if got := again.Instance().Current(); got != recovered.Instance().Current() { + t.Fatalf("second Recover state = %q, want %q", got, recovered.Instance().Current()) + } +} diff --git a/durable/store.go b/durable/store.go index 41dd6adc..28a6c646 100644 --- a/durable/store.go +++ b/durable/store.go @@ -86,9 +86,13 @@ type Record struct { // EndedActors, when set, holds the child-machine actors the instance's state // declared once this step ended that ran and have ended, settled or stopped, or - // whose spawn failed and whose onError applied (the journal holds that onError), so - // Recover doesn't spawn them again. An actor whose spawn failed with no onError to - // route to isn't one, and Recover tries it again. The first step after Start records the + // whose spawn failed and whose onError applied, or was refused for a reason + // other than a context ending and other than the parent's having no transition + // for it (the journal holds that onError, or the refusal replay meets again), so + // Recover doesn't spawn them again. An actor whose spawn failed with no onError + // to route to — none declared, or none the parent handles — isn't one, and + // neither is one whose onError a context's ending refused, since the step that + // drove it records nothing: Recover tries both again. The first step after Start records the // set, and later steps record it when they change it. It is nil otherwise, for a // machine with no actor palette, and on a Record from before this field. An empty // set is not nil: a Store must keep it, though it treats other empty fields as nil. @@ -96,10 +100,13 @@ type Record struct { // UnstartedActors, when set, holds the child-machine actors the instance's state // declared once this step ended that aren't running and haven't ended: their latest - // spawn failed with no onError to route to. Recover spawns them as new, so the - // messages they send the parent as they start apply and are journaled. A declared - // actor in neither set was running, and the journal holds every parent Fire its start - // drove, so Recover spawns it again without letting those reach the parent. It's + // spawn failed with no onError to route to — none was declared, or the parent has + // no transition for it — or its onError was refused because a context ended, which + // left the step that drove it recording nothing. Recover + // spawns them as new, so the messages they send the parent as they start apply and + // are journaled. A declared actor in neither set was running, and the journal holds + // every parent Fire its start drove, so Recover spawns it again without letting + // those reach the parent. It's // recorded as EndedActors is: with the first step after Start, then when a step // changes it, and an empty set is not nil. When the journal holds none, as on a // Record from before this field, Recover lets every spawn reach the parent. diff --git a/durable/timer_cancel_tail_test.go b/durable/timer_cancel_tail_test.go index 942e329e..a7dd8ccd 100644 --- a/durable/timer_cancel_tail_test.go +++ b/durable/timer_cancel_tail_test.go @@ -73,3 +73,156 @@ func TestRecover_KeepsATailCancelOfACheckpointTimer(t *testing.T) { t.Fatalf("after Recover the canceled timer fired: state %q, fired %d; want left, 0", snap.Current, snap.Context.Fired) } } + +// TestRecover_FiresACheckpointTimerInATailTick pins the tail-Tick case: a timer the +// checkpoint recorded fires in a tail Tick, so Recover must fire it in replay too. +// The checkpoint's timers used to be armed only after the replay walk, so the tick's +// replay fired nothing, the recovered Handle kept the pre-tick state, and the timer +// was armed a second time on top of it. +func TestRecover_FiresACheckpointTimerInATailTick(t *testing.T) { + ctx := context.Background() + m := cancelableTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("tail-tick") + clk := state.NewFakeClock(epoch) + h, err := durable.NewRunner(m, store, + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](2)). + Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatal(err) + } + for _, ev := range []string{"arm", "poke"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatal(err) + } + } + clk.Advance(11 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatal(err) + } + live := h.Instance().Snapshot() + rec, err := durable.Recover(ctx, m, store, id, + durable.WithRunnerClock[string, string, *timerCtx](state.NewFakeClock(epoch.Add(time.Hour))), + durable.WithCheckpointEvery[string, string, *timerCtx](2)) + if err != nil { + t.Fatalf("Recover: %v", err) + } + got := rec.Instance().Snapshot() + if got.Current != live.Current || got.Context.Fired != live.Context.Fired { + t.Fatalf("recovered %q fired=%d, live %q fired=%d", got.Current, got.Context.Fired, live.Current, live.Context.Fired) + } +} + +// TestRecover_ATimerFiredInATailTickDoesNotFireAgainAfterRecover pins that the +// timer a tail Tick fired stays fired after Recover: it fired once in the tick's +// replay, so the recovered Handle's own Tick must fire nothing, and the state and +// fired count must stay at the live run's. +func TestRecover_ATimerFiredInATailTickDoesNotFireAgainAfterRecover(t *testing.T) { + ctx := context.Background() + m := cancelableTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("tail-tick-once") + clk := state.NewFakeClock(epoch) + h, err := durable.NewRunner(m, store, + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](2)). + Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatal(err) + } + for _, ev := range []string{"arm", "poke"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatal(err) + } + } + clk.Advance(11 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatal(err) + } + live := h.Instance().Snapshot() + recClock := state.NewFakeClock(epoch.Add(time.Hour)) + rec, err := durable.Recover(ctx, m, store, id, + durable.WithRunnerClock[string, string, *timerCtx](recClock), + durable.WithCheckpointEvery[string, string, *timerCtx](2)) + if err != nil { + t.Fatalf("Recover: %v", err) + } + for round := 1; round <= 2; round++ { + recClock.Advance(11 * time.Second) + results, err := rec.Tick(ctx) + if err != nil { + t.Fatalf("recovered Tick %d: %v", round, err) + } + if len(results) != 0 { + t.Fatalf("recovered Tick %d fired %d timers, want none: the tail Tick already fired it", round, len(results)) + } + got := rec.Instance().Snapshot() + if got.Current != live.Current || got.Context.Fired != live.Context.Fired { + t.Fatalf("after recovered Tick %d: %q fired=%d, live %q fired=%d", round, got.Current, got.Context.Fired, live.Current, live.Context.Fired) + } + } +} + +// tickedMachine is cancelableTimerMachine with a plain target for its timer, so a +// Fire recorded after the tail Tick needs the post-tick state: from the pre-tick +// waiting, the kernel refuses it, and replay fails. +func tickedMachine() *state.Machine[string, string, *timerCtx] { + return state.ForgeFor[*timerCtx]("ticked"). + Action("markFired", func(c state.ActionCtx[*timerCtx]) (state.Effect, error) { + c.Entity.Fired++ + return nil, nil + }). + State("idle"). + State("waiting"). + State("ticked"). + State("done").Final(). + Initial("idle"). + Transition("idle").On("arm").GoTo("waiting"). + Transition("waiting").On("poke").GoTo("waiting"). + Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("ticked").Do("markFired"). + Transition("ticked").On("settle").GoTo("done"). + Quench() +} + +// TestRecover_ReplaysATailFireAfterATailTickFiredACheckpointTimer pins that a tail +// Fire recorded after the tail Tick still replays: its transition is declared only +// in the state the tick entered, so a replay that missed the tick's timer used to +// refuse it and fail Recover. +func TestRecover_ReplaysATailFireAfterATailTickFiredACheckpointTimer(t *testing.T) { + ctx := context.Background() + m := tickedMachine() + store := durable.NewMemStore() + id := durable.InstanceID("tail-tick-fire") + clk := state.NewFakeClock(epoch) + h, err := durable.NewRunner(m, store, + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](2)). + Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatal(err) + } + for _, ev := range []string{"arm", "poke"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatal(err) + } + } + clk.Advance(11 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatal(err) + } + if _, err = h.Fire(ctx, "settle"); err != nil { + t.Fatal(err) + } + live := h.Instance().Snapshot() + rec, err := durable.Recover(ctx, m, store, id, + durable.WithRunnerClock[string, string, *timerCtx](state.NewFakeClock(epoch.Add(time.Hour))), + durable.WithCheckpointEvery[string, string, *timerCtx](2)) + if err != nil { + t.Fatalf("Recover: %v", err) + } + got := rec.Instance().Snapshot() + if got.Current != live.Current || got.Context.Fired != live.Context.Fired { + t.Fatalf("recovered %q fired=%d, live %q fired=%d", got.Current, got.Context.Fired, live.Current, live.Context.Fired) + } +} diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 225ff6ee..c97146e9 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -13,6 +13,12 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Added +- **`Scheduler.ArmAt`** arms one delayed transition at an absolute deadline — the + same timer id, event and firing behavior a `ScheduleAfter` for it would carry — + without reading the clock, where `Absorb` reads one to turn the effect's declared + delay into a deadline. A host that persisted a timer's deadline, as `durable` does + for the timers a checkpoint recorded, re-arms it exactly, so no reading is taken. + It's additive, within v1.1.0. - **`ActorSystem.WithParentFireObserver`** calls a function with each parent Fire the system drives (a `ParentFire`: its result, refused ones included, the actor it came from, whether it settled that actor, with its output or error, and whether it routed diff --git a/state/driver.go b/state/driver.go index 52c7eebc..c407fe51 100644 --- a/state/driver.go +++ b/state/driver.go @@ -89,6 +89,20 @@ func (s *Scheduler[S, E, C]) absorbLocked(effects []Effect) { } } +// ArmAt arms the delayed transition id — the same event a ScheduleAfter for id +// would carry — at the absolute deadline due, without reading the clock. Absorb +// computes a timer's deadline from one clock reading plus the effect's declared +// Delay; a host that persisted the deadline itself, as a durable runtime does for +// the timers a checkpoint recorded, re-arms it exactly through ArmAt instead, so +// no reading is taken. A timer already armed under id is re-armed at due. It fires +// on the Tick whose clock reading reaches due, like any other, and a CancelScheduled +// for id cancels it. +func (s *Scheduler[S, E, C]) ArmAt(id string, event E, due time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + s.pending[id] = pending[E]{event: event, due: due} +} + // Pending reports the number of armed (not-yet-fired, not-canceled) timers. A // test asserts on it to confirm a timer was scheduled or auto-canceled on exit. func (s *Scheduler[S, E, C]) Pending() int { diff --git a/state/scheduler_test.go b/state/scheduler_test.go index 2cc8c615..d2ac669b 100644 --- a/state/scheduler_test.go +++ b/state/scheduler_test.go @@ -249,3 +249,81 @@ func assertCancelEffect(t *testing.T, effects []state.Effect, id string) { } t.Fatalf("no CancelScheduled effect for id %q in %v", id, effects) } + +// readCountingClock wraps a Clock and counts its Now() readings, so a test can +// prove a driver step took none. +type readCountingClock struct { + state.Clock + reads int +} + +func (c *readCountingClock) Now() time.Time { + c.reads++ + return c.Clock.Now() +} + +func (c *readCountingClock) Advance(d time.Duration) { + c.Clock.(interface{ Advance(time.Duration) }).Advance(d) +} + +// TestScheduler_ArmAt_ArmsAtTheDeadlineWithoutReadingTheClock proves ArmAt arms a +// timer at an absolute deadline — a deadline a host persisted and re-arms exactly, +// rather than re-deriving from a fresh reading plus a declared delay — without +// taking the clock reading Absorb would. The armed timer fires when a Tick's +// reading reaches the deadline, and a CancelScheduled drops it as any other. +func TestScheduler_ArmAt_ArmsAtTheDeadlineWithoutReadingTheClock(t *testing.T) { + m := afterMachine() + clk := &readCountingClock{Clock: state.NewFakeClock(time.Unix(0, 0))} + inst := m.Cast(&trec{}, state.WithInitialState("armed"), state.WithClock[string](clk)) + sch := state.NewScheduler(inst) + ctx := context.Background() + + id := state.ScheduleID("timed", "armed", 0) + due := time.Unix(0, 5*time.Second.Nanoseconds()) + sch.ArmAt(id, "elapsed", due) + if clk.reads != 0 { + t.Fatalf("ArmAt took %d clock readings, want none", clk.reads) + } + if !sch.HasPending(id) { + t.Fatalf("ArmAt should arm timer %q", id) + } + + // Before the deadline the timer stays armed; a tick fires nothing and the + // instance stays in armed. + if fired := sch.Tick(ctx); len(fired) != 0 { + t.Fatalf("tick before the deadline fired %d events", len(fired)) + } + if inst.Current() != "armed" { + t.Fatalf("before the deadline, want armed, got %q", inst.Current()) + } + + // Past the deadline the timer fires the delayed event and the instance advances. + clk.Advance(5 * time.Second) + if fired := sch.Tick(ctx); len(fired) != 1 || inst.Current() != "fired" { + t.Fatalf("tick past the deadline: fired=%d state=%q, want 1 and fired", len(fired), inst.Current()) + } + + // A deadline already in the past arms as immediately due, so an elapsed timer + // fires on the next Tick. + inst = m.Cast(&trec{}, state.WithInitialState("armed"), state.WithClock[string](clk)) + sch = state.NewScheduler(inst) + sch.ArmAt(id, "elapsed", time.Unix(0, 0)) + clk.Advance(time.Nanosecond) + if fired := sch.Tick(ctx); len(fired) != 1 || inst.Current() != "fired" { + t.Fatalf("tick past an elapsed deadline: fired=%d state=%q, want 1 and fired", len(fired), inst.Current()) + } + + // A CancelScheduled for an ArmAt-armed timer drops it, as for an Absorb-armed one. + inst = m.Cast(&trec{}, state.WithInitialState("armed"), state.WithClock[string](clk)) + sch = state.NewScheduler(inst) + sch.ArmAt(id, "elapsed", clk.Now().Add(time.Hour)) + leave := inst.Fire(ctx, "leave") + assertCancelEffect(t, leave.Effects, id) + sch.Absorb(ctx, leave.Effects) + if sch.HasPending(id) { + t.Fatalf("cancel should drop the ArmAt-armed timer %q", id) + } + if fired := sch.Tick(ctx); len(fired) != 0 { + t.Fatalf("canceled ArmAt-armed timer fired %d events", len(fired)) + } +} From 233fbb7c5ed13902f137efd04877c42f242889ea Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Sun, 15 Nov 2026 21:21:22 -0700 Subject: [PATCH 25/38] fix(durable): retry a failed spawn only when nothing caught it; leave checkpoint timers to #236 An invoked actor with no onError fires the zero event at the parent when it can't start, so durable could tell "none declared" from "a declared onError was refused" only by matching the refusal's text. That retried a declared onError the parent had no transition for, and a denial worded the same way. state now reports it: SpawnActor.NoOnError and ParentFire.NoOnError, additive. The builder records the declaration, so an onError that is the zero event, such as an iota enum's first constant, still counts as declared. The zero event still fires, as v1 documents. Recover retries a failed spawn only when it declared no onError or a context ending refused its onError. Restoring a checkpoint's timers before the replay walk is #236's, so this takes that change and its tests back out, along with state's Scheduler.ArmAt, and Recover re-arms them after the walk as before. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 23 +-- durable/checkpoint.go | 60 +++---- durable/checkpoint_internal_test.go | 161 +++++------------- durable/clock.go | 9 +- durable/clock_internal_test.go | 2 +- durable/doc.go | 5 +- durable/runner.go | 97 +++++------ durable/spawn_onerror_rule_test.go | 189 +++++++++++++++++++++ durable/store.go | 11 +- durable/timer_cancel_tail_test.go | 228 -------------------------- state/CHANGELOG.md | 14 +- state/actor.go | 20 ++- state/actor_invoke_undeclared_test.go | 90 ++++++++++ state/actor_system.go | 7 +- state/driver.go | 14 -- state/invoke.go | 12 ++ state/kernel.go | 26 +-- state/scheduler_test.go | 78 --------- 18 files changed, 466 insertions(+), 580 deletions(-) create mode 100644 durable/spawn_onerror_rule_test.go delete mode 100644 durable/timer_cancel_tail_test.go create mode 100644 state/actor_invoke_undeclared_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 136c9ac5..be9b4a49 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -13,7 +13,7 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ran and have ended, settled or stopped, so `Recover` doesn't spawn them again. A Store must keep an empty set distinct from nil. - **`Record.UnstartedActors`** records the declared actors that aren't running and - haven't ended, because their spawn failed with no onError to route to, or its + haven't ended, because their spawn failed with no onError declared, or its onError was refused because a context ended, so `Recover` can tell them from the actors that were running. A Store must keep an empty set distinct from nil. - **`Record.Format`** records the journal format of the version that wrote the Record, @@ -184,7 +184,7 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. without leaving the state, or an explicit stop. Each step now records the declared actors that ran and ended, in the new `Record.EndedActors`, and a checkpoint keeps the set, so `Recover` spawns the declared actors that aren't in it. An actor whose spawn - failed with no onError to route to never ran, so `Recover` tries it again, as before, + failed with no onError declared never ran, so `Recover` tries it again, as before, and so does one whose onError a context's ending refused, since the step that drove it records nothing; one whose onError applied counts as ended, since the journal holds that onError, and, from the refused-onError fix below, so does one whose @@ -208,7 +208,8 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. already records it, and replay meets it again — so the actor counts as ended and `Recover` leaves it alone. A spawn whose onError a context's ending refused still retries, since the step that drove it records nothing, as does one with no onError - to route to, none declared or none the parent handles, as before. + declared, as before. A declared onError the parent has no transition for counts as + refused, so the actor is done. - **A message an actor sends its parent as it spawns applies once.** A `Fire`, `RunService`, `Start` or `Recover` didn't journal it, and `Recover` spawned the actor again to send it again: it landed after the steps that followed it live, or never, if @@ -230,23 +231,11 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. took no clock read for them, and its Records replay as they did. A service's settle re-arms its state's timers on replay too, and `DeliverToActor` and `RunService` now journal the clock reads their step took, so a checkpoint on that step can't leave - a read for the next to replay. `Recover` restores a checkpoint's timers before the - replay walk, so a tail step, or a Fire one of the recovered spawns drives, acts on - them as the live run did. A `Tick` + a read for the next to replay. `Recover` re-arms a checkpoint's timers before it + spawns the running actors, so a Fire one of theirs drives can cancel one. A `Tick` drops from the timers a checkpoint records exactly the ones it fired, live and on replay: one that came due between its clock reads, and a chained one it armed and fired, used to stay, so a `Recover` from a later checkpoint fired it again. -- **A checkpoint's timers are restored before the replay walk.** `Recover` armed them - only after replaying the journal's tail, so a tail `Tick` that fired one of them - live fired nothing in replay: the recovered `Handle` kept the pre-tick state, the - timer was then armed and fired a second time on top of it, and a later tail Record - that needed the post-tick state failed replay. The timers are now armed into the - replay scheduler at their recorded absolute deadlines before the walk — taking no - clock reading, so the walk's recorded readings still land in order — and a tail - `Tick` fires one, and a later tail Fire moves on from the state it reached, exactly - as live did. A timer the checkpoint recorded and a later step canceled stays - canceled the same way: its cancel replays against the restored timer, where - `Recover` used to re-arm it after the cancel had replayed. - **A delivery journals each parent Fire under the actor that drove it,** where it used to record every one under the actor delivered to. It no longer copies the instance's history twice per delivery to do it. diff --git a/durable/checkpoint.go b/durable/checkpoint.go index a671cb24..7377041e 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -23,11 +23,10 @@ import ( // The declared `after` Delay re-arms a fresh timer at now+Delay; a timer pending at // a checkpoint has already burned part of its delay, so the durable layer persists // each armed timer's absolute deadline alongside the checkpoint and, on recovery, -// arms it at that deadline — through the scheduler's ArmAt, which reads no clock — -// before the replay walk, so a tail Tick or cancel acts on it as it did live. The -// deadline is itself a recorded clock read, so the re-armed timer fires at the same -// recorded instant regardless of the wall clock at recovery time, and the recovered -// run is byte-identical to one that never crashed. +// re-arms the remainder (deadline − resumed now) rather than the full declared +// Delay. The deadline is itself a recorded clock read, so the re-armed timer fires +// at the same recorded instant regardless of the wall clock at recovery time, and +// the recovered run is byte-identical to one that never crashed. // pendingTimer is one armed delayed (`after`) timer the durable Handle tracks // alongside the kernel scheduler, so its absolute deadline can be persisted at a @@ -41,7 +40,7 @@ type pendingTimer struct { // scheduler's pending set key identically. id string // due is the timer's absolute fire deadline (the recorded arming clock read plus - // the declared Delay), the value persisted so recovery re-arms it at that deadline. + // the declared Delay), the value persisted so recovery re-arms the remainder. due time.Time // event is the delayed event the timer re-fires through Fire when it elapses, // type-erased for the abstract ScheduleAfter surface and re-typed by the @@ -151,7 +150,7 @@ func unmarshalCheckpoint(b []byte) checkpointEnvelope { // decodeTimerEvent decodes a persisted timer event wire back into the machine's // event type E through the same codec the Runner replays driving events with, so -// the re-armed timer carries a correctly-typed event the scheduler accepts. +// the re-armed ScheduleAfter carries a correctly-typed event the scheduler accepts. func decodeTimerEvent[E comparable](codec EventCodec[E], raw json.RawMessage) (E, error) { return codec.Decode(raw) } @@ -172,33 +171,38 @@ func mirrorArmed(armed map[string]pendingTimer, effects []state.Effect, now time } } -// armPersistedTimers arms each timer the checkpoint persisted into the replay -// scheduler at its recorded absolute deadline, and seeds the mirror's armed table -// with it, before the replay walk: a tail Tick that fired one of them live fires it -// in replay too, and a tail cancel leaves it canceled, as each acted live. It must -// take no clock reading: during the walk the replay clock hands out the recorded -// readings in order, and a read taken before the walk would consume the reading -// that belongs to the first tail Record and shift every later one. So each timer is -// armed through Scheduler.ArmAt at its persisted deadline, not through Absorb, -// which reads the clock to turn a delay into a deadline. The mirror's table is the -// Handle's timer table after Recover: the walk folds the tail's schedules, cancels -// and fired timers into it, so it ends with each still-pending timer at its -// persisted deadline. A deadline already in the past arms as immediately due, so a -// timer that elapsed while the instance was down fires on the next Tick. -func armPersistedTimers[S comparable, E comparable, C any]( +// reArmEffects builds the ScheduleAfter effects that re-arm persisted timers at +// their recorded absolute deadlines, relative to now: each timer's remaining delay +// is its deadline minus now, so absorbing the effects through the live scheduler +// reproduces the same absolute deadline the live run held. A deadline already at or +// before now yields a non-positive delay, which the scheduler arms as immediately +// due, so an elapsed-while-down timer fires on the next Tick. Timers whose id is +// already armed (re-established by tail replay) are skipped, so a timer the tail +// still carries is not double-armed. Returns the effects and the durable-side +// pendingTimer table to seed the Handle, both in scheduleID order. +func reArmEffects[E comparable]( codec EventCodec[E], - sched *state.Scheduler[S, E, C], wires []pendingTimerWire, - armed map[string]pendingTimer, -) error { + already map[string]pendingTimer, + now time.Time, +) ([]state.Effect, map[string]pendingTimer, error) { + var effects []state.Effect + seeded := map[string]pendingTimer{} for _, w := range wires { + if _, armed := already[w.ID]; armed { + continue // tail replay already re-armed this timer; do not double-arm. + } ev, err := decodeTimerEvent(codec, w.Event) if err != nil { - return fmt.Errorf("durable: decoding pending timer %q event: %w", w.ID, err) + return nil, nil, fmt.Errorf("durable: decoding pending timer %q event: %w", w.ID, err) } due := time.Unix(0, w.DueUnixNano).UTC() - sched.ArmAt(w.ID, ev, due) - armed[w.ID] = pendingTimer{id: w.ID, due: due, event: ev} + effects = append(effects, state.ScheduleAfter{ + ID: w.ID, + Delay: due.Sub(now), + Event: ev, + }) + seeded[w.ID] = pendingTimer{id: w.ID, due: due, event: ev} } - return nil + return effects, seeded, nil } diff --git a/durable/checkpoint_internal_test.go b/durable/checkpoint_internal_test.go index 38660f15..282ee6a3 100644 --- a/durable/checkpoint_internal_test.go +++ b/durable/checkpoint_internal_test.go @@ -1,7 +1,6 @@ package durable import ( - "context" "encoding/json" "testing" "time" @@ -82,91 +81,59 @@ func TestUnmarshalCheckpoint_Garbage(t *testing.T) { } } -// armingMachine is a minimal machine for the arming tests: idle -elapsed-> fired, -// so a Tick that fires an armed timer moves the instance. -func armingMachine() *state.Machine[string, string, int] { - return state.ForgeFor[int]("arming"). - State("idle"). - State("fired"). - Initial("idle"). - Transition("idle").On("elapsed").GoTo("fired"). - // fired keeps a self-loop, so a second armed timer fires cleanly once the - // first has moved the instance there. - Transition("fired").On("elapsed").GoTo("fired"). - Quench() -} - -// readCountClock wraps a Clock and counts its Now() readings, so a test can prove -// an arming took none. -type readCountClock struct { - state.Clock - reads int -} - -func (c *readCountClock) Now() time.Time { - c.reads++ - return c.Clock.Now() -} - -func (c *readCountClock) Advance(d time.Duration) { - c.Clock.(interface{ Advance(time.Duration) }).Advance(d) -} - -// TestArmPersistedTimers_ArmsAtTheDeadlineWithoutReadingTheClock confirms the -// pre-walk arming arms each persisted timer into the scheduler at its recorded -// absolute deadline and seeds the mirror's table, taking no clock reading: a read -// there would consume the recorded reading the first tail Record owns. A deadline -// already in the past fires on the next Tick, and a later one when the clock -// reaches it. -func TestArmPersistedTimers_ArmsAtTheDeadlineWithoutReadingTheClock(t *testing.T) { - base := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC) - clk := &readCountClock{Clock: state.NewFakeClock(base)} - inst := armingMachine().Cast(0, state.WithInitialState("idle"), state.WithClock[string](clk)) - sched := state.NewScheduler(inst) - past := base.Add(-3 * time.Second) - future := base.Add(8 * time.Second) +// TestReArmEffects_SkipsAlreadyArmed confirms a persisted timer already armed by +// tail replay is not re-armed (no double-arm), while an un-armed one is re-armed at +// its remaining delay. +func TestReArmEffects_SkipsAlreadyArmed(t *testing.T) { + now := time.Unix(0, 1_000_000_000).UTC() wires := []pendingTimerWire{ - {ID: "past", DueUnixNano: past.UnixNano(), Event: json.RawMessage(`"elapsed"`)}, - {ID: "future", DueUnixNano: future.UnixNano(), Event: json.RawMessage(`"elapsed"`)}, + {ID: "armed", DueUnixNano: now.Add(5 * time.Second).UnixNano(), Event: json.RawMessage(`"x"`)}, + {ID: "compacted", DueUnixNano: now.Add(8 * time.Second).UnixNano(), Event: json.RawMessage(`"y"`)}, + } + already := map[string]pendingTimer{"armed": {id: "armed"}} + effects, seeded, err := reArmEffects[string](jsonEventCodec[string]{}, wires, already, now) + if err != nil { + t.Fatalf("reArmEffects: %v", err) + } + if len(effects) != 1 || len(seeded) != 1 { + t.Fatalf("want exactly the compacted timer re-armed, got effects=%d seeded=%d", len(effects), len(seeded)) } - armed := map[string]pendingTimer{} - if err := armPersistedTimers[string, string, int](jsonEventCodec[string]{}, sched, wires, armed); err != nil { - t.Fatalf("armPersistedTimers: %v", err) + sa, ok := effects[0].(state.ScheduleAfter) + if !ok || sa.ID != "compacted" { + t.Fatalf("want compacted ScheduleAfter, got %+v", effects[0]) } - if clk.reads != 0 { - t.Fatalf("arming took %d clock readings, want none", clk.reads) + if sa.Delay != 8*time.Second { + t.Fatalf("remaining delay: want 8s, got %s", sa.Delay) } - for id, due := range map[string]time.Time{"past": past, "future": future} { - if !sched.HasPending(id) { - t.Fatalf("timer %q not armed", id) - } - if got := armed[id]; got.id != id || !got.due.Equal(due) { - t.Fatalf("armed table for %q = %+v, want due %v", id, got, due) - } +} + +// TestReArmEffects_ElapsedDeadlineImmediate confirms a deadline already at or before +// now yields a non-positive delay (armed as immediately due), so an elapsed-while- +// down timer fires on the next Tick. +func TestReArmEffects_ElapsedDeadlineImmediate(t *testing.T) { + now := time.Unix(0, 10_000_000_000).UTC() + wires := []pendingTimerWire{ + {ID: "past", DueUnixNano: now.Add(-3 * time.Second).UnixNano(), Event: json.RawMessage(`"z"`)}, } - // The elapsed deadline fires on the next Tick; the future one stays armed. - fired := sched.Tick(context.Background()) - if len(fired) != 1 || inst.Current() != "fired" { - t.Fatalf("tick fired %d, state %q, want the elapsed timer alone", len(fired), inst.Current()) + effects, _, err := reArmEffects[string](jsonEventCodec[string]{}, wires, map[string]pendingTimer{}, now) + if err != nil { + t.Fatalf("reArmEffects: %v", err) } - if !sched.HasPending("future") { - t.Fatal("the future timer should stay armed") + if len(effects) != 1 { + t.Fatalf("want 1 effect, got %d", len(effects)) } - clk.Advance(8 * time.Second) - if fired = sched.Tick(context.Background()); len(fired) != 1 { - t.Fatalf("tick at the deadline fired %d, want the future timer", len(fired)) + if sa := effects[0].(state.ScheduleAfter); sa.Delay > 0 { + t.Fatalf("elapsed deadline should arm non-positive delay, got %s", sa.Delay) } } -// TestArmPersistedTimers_BadEventErrors surfaces a decode failure for a corrupt -// persisted timer event rather than silently dropping the timer. -func TestArmPersistedTimers_BadEventErrors(t *testing.T) { +// TestReArmEffects_BadEventErrors surfaces a decode failure for a corrupt persisted +// timer event rather than silently dropping the timer. +func TestReArmEffects_BadEventErrors(t *testing.T) { wires := []pendingTimerWire{ {ID: "bad", DueUnixNano: 1, Event: json.RawMessage(`{not valid`)}, } - clk := state.NewFakeClock(time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC)) - inst := armingMachine().Cast(0, state.WithInitialState("idle"), state.WithClock[string](clk)) - err := armPersistedTimers[string, string, int](jsonEventCodec[string]{}, state.NewScheduler(inst), wires, map[string]pendingTimer{}) + _, _, err := reArmEffects[string](jsonEventCodec[string]{}, wires, map[string]pendingTimer{}, time.Unix(0, 0)) if err == nil { t.Fatal("want decode error for corrupt timer event, got nil") } @@ -204,51 +171,3 @@ func unmarshalCheckpointParts(b []byte) ([]byte, []pendingTimerWire, int) { env := unmarshalCheckpoint(b) return env.Snapshot, env.Timers, env.NextStep } - -// TestRecover_SeedsTheTimerTableWithThePersistedDeadline proves the Handle's timer -// table after a Recover whose tail replays no timer step ends with each -// still-pending timer at its persisted absolute deadline, so the next checkpoint -// persists it again and the recovered scheduler holds it armed. -func TestRecover_SeedsTheTimerTableWithThePersistedDeadline(t *testing.T) { - ctx := context.Background() - m := state.ForgeFor[int]("seeded"). - State("idle"). - State("waiting"). - State("done").Final(). - Initial("idle"). - Transition("idle").On("arm").GoTo("waiting"). - Transition("waiting").On("poke").GoTo("waiting"). - Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("done"). - Quench() - base := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC) - store, id := NewMemStore(), InstanceID("seeded") - h, err := NewRunner(m, store, - WithRunnerClock[string, string, int](state.NewFakeClock(base)), - WithCheckpointEvery[string, string, int](2)). - Start(ctx, id, 0, state.WithInitialState("idle")) - if err != nil { - t.Fatalf("Start: %v", err) - } - for _, ev := range []string{"arm", "poke"} { - if _, err = h.Fire(ctx, ev); err != nil { - t.Fatalf("Fire(%q): %v", ev, err) - } - } - rec, err := Recover(ctx, m, store, id, - WithRunnerClock[string, string, int](state.NewFakeClock(base.Add(time.Hour))), - WithCheckpointEvery[string, string, int](2)) - if err != nil { - t.Fatalf("Recover: %v", err) - } - if len(rec.timers) != 1 { - t.Fatalf("recovered timer table = %v, want one pending timer", rec.timers) - } - for id, pt := range rec.timers { - if want := base.Add(10 * time.Second); !pt.due.Equal(want) { - t.Fatalf("timer %q due %v, want the persisted %v", id, pt.due, want) - } - if !rec.sched.HasPending(id) { - t.Fatalf("timer %q is in the table but not armed on the scheduler", id) - } - } -} diff --git a/durable/clock.go b/durable/clock.go index 9d261f38..60682ad9 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -128,10 +128,9 @@ func (c *recordingClock) lastReadingSince(i int) (time.Time, bool) { // readings and returns each once. // // When the cursor is exhausted — a Now() beyond the recorded readings, which -// happens once replay is over and the recovered run reads the clock live, as when -// a timer an actor Recover spawns drives arms — it falls through to a real clock -// so post-recovery timing continues against wall time. The fallthrough never -// affects the replayed prefix, which is fully determined by the journal. +// happens on the live re-arm after replay — it falls through to a real clock so +// post-recovery timing continues against wall time. The fallthrough never affects +// the replayed prefix, which is fully determined by the journal. type replayClock struct { mu sync.Mutex readings []int64 @@ -141,7 +140,7 @@ type replayClock struct { } // newReplayClock builds a replayClock over the recorded readings, falling through -// to fallback once the readings are exhausted and the recovered run reads live. +// to fallback once the readings are exhausted (the live re-arm after replay). func newReplayClock(readings []int64, fallback state.Clock) *replayClock { return &replayClock{readings: readings, fallback: fallback} } diff --git a/durable/clock_internal_test.go b/durable/clock_internal_test.go index b6824946..a0a01241 100644 --- a/durable/clock_internal_test.go +++ b/durable/clock_internal_test.go @@ -54,7 +54,7 @@ func TestRecordingClock_AfterDelegates(t *testing.T) { // TestReplayClock_ReturnsRecordedThenFallsThrough confirms a replay clock returns // the recorded readings in order, then falls through to its fallback once the -// readings are exhausted and the recovered run reads the clock live. +// readings are exhausted (the live re-arm after replay). func TestReplayClock_ReturnsRecordedThenFallsThrough(t *testing.T) { readings := []int64{ clockEpoch.UnixNano(), diff --git a/durable/doc.go b/durable/doc.go index 9eecd756..559ca3b4 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -96,9 +96,8 @@ // instants regardless of the wall clock at recovery time. A timer also survives // checkpoint compaction: each checkpoint persists the absolute deadlines of the // timers armed at that instant; on recovery a timer whose arming ScheduleAfter -// was compacted out of the tail is re-armed from its persisted deadline before -// the tail replays — so a tail Tick that fired it live, or a tail cancel, acts on -// it as the live run did — rather than lost. +// was compacted out of the tail is re-armed from its persisted deadline rather +// than lost. // // Invoked services (WithServiceRegistry): a service (`invoke`) runs on the live path; // its result is journaled as a JournalServiceResult. On recovery the recorded result is diff --git a/durable/runner.go b/durable/runner.go index efa37379..9ba6ade9 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -666,7 +666,7 @@ type parentFires[S comparable] struct { fires []state.ParentFire[S] spawned map[string]bool // actors whose latest spawn this step started attempted map[string]bool // actors the system was asked to spawn this step - failed map[string]bool // actors whose latest spawn failed and whose onError applied, or was refused for a reason other than a context ending or an unroutable onError + 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 } // attempt notes the actors effects ask the system to spawn. @@ -719,15 +719,13 @@ func (p *parentFires[S]) inspect(ev state.InspectionEvent) { func (p *parentFires[S]) note(pf state.ParentFire[S]) { p.mu.Lock() p.fires = append(p.fires, pf) - // A spawn whose onError applied is handled: the journal holds that onError, so - // retrying the spawn would apply it twice. One whose onError was refused for a - // reason other than a context ending — a failing guard, say — is handled too: - // the journal records the refusal, replay meets it again, and a retry would - // re-run the behavior and journal another refusal. One a context's ending - // refused, and one whose parent had no transition for its onError event, are - // not: the first left the step that drove it recording nothing, and the second - // is the spawn's having no onError to route to, so a retry is right for both. - if pf.SpawnFailed && spawnErrorHandled(pf.Result.Err) { + // A spawn whose declared onError applied, or was refused for a reason other than + // a context ending, such as a failing guard, is handled: the journal holds the + // onError or its refusal, and a retry would run the behavior again. One a context's + // ending refused isn't: the step that drove it recorded nothing. Nor is one that + // declared no onError (NoOnError), whose zero event the parent refuses: nothing + // caught the failure, so a retry is right. + if pf.SpawnFailed && !pf.NoOnError && (pf.Result.Err == nil || !isContextErr(pf.Result.Err)) { if p.failed == nil { p.failed = map[string]bool{} } @@ -1189,12 +1187,11 @@ func (r *recordedSet) note(now *ActorSet) { // keeps a settled actor), or when this step asked the system to spawn it and the latest // of those spawns started it (then something stopped it), or, when this step didn't try // to spawn it, when it was running or ended at the previous step. A spawn whose onError -// applied, or whose onError was refused for a reason other than a context ending and -// other than the parent's having no transition for it, also counts as ended, since the -// journal holds that onError, or the refusal replay meets again. So an actor whose -// spawn failed with no onError to route to — none declared, or none the parent handles -// — or whose onError a context's ending refused, which left the step that drove it -// recording nothing, hasn't ended: it's unstarted, and Recover tries it again. Both are +// applied, or whose onError was refused for a reason other than a context ending, +// also counts as ended, since the journal holds that onError, or the refusal replay +// meets again. So an actor whose spawn failed with no onError declared, or whose +// onError a context's ending refused, which left the step that drove it recording +// nothing, hasn't ended: it's unstarted, and Recover tries it again. Both are // nil with no actor palette. func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { if h.actors == nil { @@ -1370,10 +1367,10 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S actorBuf := make([]state.JournalEntry, 0) actors, actorFires := r.newActorSystem(inst) - // armed is the Handle's timer table: it starts with the timers the checkpoint - // persisted, armed into the replay scheduler below, and the walk folds the tail's - // schedules, cancels and fired timers into it, so it ends with every still-pending - // timer's deadline for the next checkpoint. + // armed mirrors the scheduler's pending timers re-established by tail replay, + // with their recorded deadlines, so a persisted-but-compacted timer is re-armed + // only when the tail did not already re-arm it, and the Handle's table is seeded + // with every still-pending timer's deadline for the next checkpoint. armed := map[string]pendingTimer{} // mirror tracks, as replay walks the tail, the still-pending timers in armed and the @@ -1384,16 +1381,6 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S mirror.settle(sv) } - // Arm the checkpoint's persisted timers into the replay scheduler at their - // recorded absolute deadlines, BEFORE the walk, so the tail acts on them as the - // live run did: a tail Tick that fired one fires it in replay, reaching the same - // state, and a tail cancel leaves it canceled. A tail Record that needs the - // post-tick state then replays against it. The arming takes no clock reading, so - // the walk's first tail Record still gets its own recorded reading. - if err := armPersistedTimers(r.cfg.eventCodec, sched, persistedTimers, armed); err != nil { - return nil, fmt.Errorf("durable: re-arming pending timers for %q: %w", id, err) - } - // ended is the latest recorded set of the declared actors the live run had ended: // the checkpoint's, then each tail Record's that records one. Nil means none was // recorded, so Recover spawns every actor the configuration declares. @@ -1438,6 +1425,33 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // readings): they belong to no new step and must not leak into the next Fire. buf = buf[:0] + // Re-arming reads the clock past the journal, and so can arming a timer for a parent + // Fire an actor Recover spawns drives, which the next step records: re-arm before the + // spawns, so the re-arm's read can be dropped while theirs are kept, and so one of + // their Fires can cancel a re-armed timer. + // + // Re-arm any timer that was pending at the checkpoint but whose arming + // ScheduleAfter was compacted out of the tail, so it survives compaction: the + // tail replay could not re-arm it (its arm is gone), so re-arm it here at its + // persisted absolute deadline. Already-armed timers (re-established by the tail) + // are skipped, so a timer the tail still carried is never double-armed. The + // remaining delay is the persisted deadline minus the recovery clock's now, so + // the re-armed timer fires at its recorded instant — an already-elapsed deadline + // arms as immediately due and fires on the next Tick. + reEffects, reSeeded, reErr := reArmEffects(r.cfg.eventCodec, persistedTimers, armed, repClock.Now()) + if reErr != nil { + return nil, fmt.Errorf("durable: re-arming pending timers for %q: %w", id, reErr) + } + if len(reEffects) > 0 { + sched.Absorb(ctx, reEffects) + } + for id, pt := range reSeeded { + armed[id] = pt + } + // The re-arm reads the recovery clock to compute remaining delays; that reading + // belongs to no recorded step and must not leak into the next Fire's Record. + buf = buf[:0] + // The next step ordinal continues past the highest assigned step. Step ordinals // are assigned monotonically: each Record consumes one ordinal regardless of how // many parent Traces it produced (an actor delivery can drive several), except a @@ -1711,29 +1725,6 @@ func (jsonEventCodec[E]) Decode(payload []byte) (E, error) { return e, err } -// spawnErrorHandled reports whether the onError Fire of a failed spawn leaves the -// spawn handled, so the journal's actor sets count it as ended and Recover doesn't -// retry it: the Fire applied (err is nil), or it was refused for a reason other -// than a context ending — a failing guard, say — which the journal records and -// replay meets again. A context's ending leaves it unhandled: the step that drove -// the Fire records nothing, so a retry is right. So does the parent's having no -// transition for the onError event, the same "no onError to route to" as an -// undeclared one, matching the kernel's own reading of that outcome: the spawn -// stays unstarted, and Recover tries it again, as it always has. -func spawnErrorHandled(err error) bool { - if err == nil { - return true - } - if isContextErr(err) { - return false - } - var it *state.InvalidTransitionError - if errors.As(err, &it) && it.Reason == "no transition declared for this state and event" { - return false - } - return true -} - // isContextErr reports whether err is a context's cancellation or deadline, which a // Store may report for either when the caller's context ends. func isContextErr(err error) bool { diff --git a/durable/spawn_onerror_rule_test.go b/durable/spawn_onerror_rule_test.go new file mode 100644 index 00000000..50992245 --- /dev/null +++ b/durable/spawn_onerror_rule_test.go @@ -0,0 +1,189 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// The rule for a spawn that failed to start: Recover retries it only when nothing was +// declared to catch the failure. A spawn whose declared onError the parent refused, +// for any reason but a context ending, is done, since the journal holds the refusal. +// A context-refused onError retries (TestRecover_RetriesAGuardedSpawnOnlyWhenAContext- +// RefusedItsOnError). + +// denyAs is a middleware that refuses event with err, as a policy layer might. +func denyAs(event string, err error) state.Middleware[string, string, stepCtx] { + return func(next state.FireFunc[string, string, stepCtx]) state.FireFunc[string, string, stepCtx] { + return func(ctx context.Context, ev string) state.FireResult[string] { + if ev == event { + return state.FireResult[string]{Err: err} + } + return next(ctx, ev) + } + } +} + +// spawnRuleMachine is idle -start-> spawning, which invokes child with opts. spawning +// handles spawnFailed only when handles, and poke always. +func spawnRuleMachine(handles bool, mw state.Middleware[string, string, stepCtx], opts ...state.InvokeOption) stepMachine { + b := state.ForgeFor[stepCtx]("spawnRule").Actor("child") + if mw != nil { + b = b.Use(mw) + } + b = b.State("idle"). + State("spawning").InvokeActor("child", opts...). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("poke").GoTo("spawning") + if handles { + b = b.Transition("spawning").On("spawnFailed").GoTo("failed") + } + return b.Quench() +} + +// spawnRuleCalls runs start live with a child behavior that fails its first spawn and +// starts after, then Recovers once, and returns how many times the behavior ran. +func spawnRuleCalls(t *testing.T, m stepMachine) int { + t.Helper() + ctx := context.Background() + store, id := durable.NewMemStore(), durable.InstanceID("spawn-rule") + var calls int + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": func(in map[string]any) (state.ActorInstance, error) { + calls++ + if calls == 1 { + return nil, errors.New("the child can't start yet") + } + return finishingChild()(in) + }, + })} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if calls != 1 { + t.Fatalf("live ran the behavior %d times, want once", calls) + } + if _, err = durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("Recover: %v", err) + } + return calls +} + +func TestSpawnRule_NoOnErrorRetries(t *testing.T) { + if got := spawnRuleCalls(t, spawnRuleMachine(false, nil)); got != 2 { + t.Fatalf("behavior ran %d times, want Recover to retry it once", got) + } +} + +func TestSpawnRule_GuardRefusedOnErrorIsDone(t *testing.T) { + m := state.ForgeFor[stepCtx]("spawnRuleGuard"). + Guard("never", func(state.GuardCtx[stepCtx]) bool { return false }). + Actor("child"). + State("idle"). + State("spawning").InvokeActor("child", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed").When("never"). + Transition("spawning").On("poke").GoTo("spawning"). + Quench() + if got := spawnRuleCalls(t, m); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) + } +} + +func TestSpawnRule_DeclaredOnErrorWithNoTransitionIsDone(t *testing.T) { + if got := spawnRuleCalls(t, spawnRuleMachine(false, nil, state.WithInvokeOnError("spawnFailed"))); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) + } +} + +func TestSpawnRule_DenialWordedLikeNoTransitionIsDone(t *testing.T) { + denial := &state.InvalidTransitionError{Event: "spawnFailed", Reason: "no transition declared for this state and event"} + m := spawnRuleMachine(true, denyAs("spawnFailed", denial), state.WithInvokeOnError("spawnFailed")) + if got := spawnRuleCalls(t, m); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) + } +} + +// TestSpawnRule_ActorThatFailsWithNoOnErrorStaysEnded pins that an invoked actor that +// ran and then failed with no onError declared is recorded as ended, so no Recover +// spawns it again. +func TestSpawnRule_ActorThatFailsWithNoOnErrorStaysEnded(t *testing.T) { + ctx := context.Background() + for _, every := range []int{0, 1} { + m := state.ForgeFor[stepCtx]("failsLater"). + Actor("child"). + State("idle"). + State("working").InvokeActor("child", state.WithInvokeID("kid")). + Initial("idle"). + Transition("idle").On("start").GoTo("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + store, id := durable.NewMemStore(), durable.InstanceID("fails-later") + var runs int64 + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"child": failChild(&runs)})} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if ok, err := h.DeliverToActorByID(ctx, "kid", "finish"); !ok || err != nil { + t.Fatalf("DeliverToActorByID = %v, %v, want the actor found", ok, err) + } + for round := 1; round <= 2; round++ { + if _, err := durable.Recover(ctx, m, store, id, opts...); err != nil { + t.Fatalf("every %d, Recover %d: %v", every, round, err) + } + // A respawn would run the behavior again. + if runs != 1 { + t.Fatalf("every %d, Recover %d: behavior ran %d times, want the live run only", every, round, runs) + } + } + } +} + +// spawnActionMachine is idle -start-> spawning, whose start transition spawns child +// with opts; spawning handles spawnFailed only when handles. +func spawnActionMachine(handles bool, opts ...state.SpawnOption) stepMachine { + b := state.ForgeFor[stepCtx]("spawnAction"). + Actor("child"). + State("idle"). + State("spawning"). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning").Spawn("child", "kid", opts...). + Transition("spawning").On("poke").GoTo("spawning") + if handles { + b = b.Transition("spawning").On("spawnFailed").GoTo("failed") + } + return b.Quench() +} + +// An actor a transition spawns, rather than one a state invokes, doesn't return on +// Recover, so its failed spawn isn't retried either, declared onError or not. +func TestSpawnRule_SpawnActionNoOnErrorIsNotRetried(t *testing.T) { + if got := spawnRuleCalls(t, spawnActionMachine(false)); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave a spawned actor alone", got) + } +} + +func TestSpawnRule_SpawnActionDeclaredOnErrorWithNoTransitionIsDone(t *testing.T) { + if got := spawnRuleCalls(t, spawnActionMachine(false, state.WithSpawnOnError("spawnFailed"))); got != 1 { + t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) + } +} diff --git a/durable/store.go b/durable/store.go index 28a6c646..fcbd6c0e 100644 --- a/durable/store.go +++ b/durable/store.go @@ -87,10 +87,9 @@ type Record struct { // EndedActors, when set, holds the child-machine actors the instance's state // declared once this step ended that ran and have ended, settled or stopped, or // whose spawn failed and whose onError applied, or was refused for a reason - // other than a context ending and other than the parent's having no transition - // for it (the journal holds that onError, or the refusal replay meets again), so - // Recover doesn't spawn them again. An actor whose spawn failed with no onError - // to route to — none declared, or none the parent handles — isn't one, and + // other than a context ending (the journal holds that onError, or the refusal + // replay meets again), so Recover doesn't spawn them again. An actor whose spawn + // failed with no onError declared isn't one, and // neither is one whose onError a context's ending refused, since the step that // drove it records nothing: Recover tries both again. The first step after Start records the // set, and later steps record it when they change it. It is nil otherwise, for a @@ -100,8 +99,8 @@ type Record struct { // UnstartedActors, when set, holds the child-machine actors the instance's state // declared once this step ended that aren't running and haven't ended: their latest - // spawn failed with no onError to route to — none was declared, or the parent has - // no transition for it — or its onError was refused because a context ended, which + // spawn failed with no onError declared, or its onError was refused because a + // context ended, which // left the step that drove it recording nothing. Recover // spawns them as new, so the messages they send the parent as they start apply and // are journaled. A declared actor in neither set was running, and the journal holds diff --git a/durable/timer_cancel_tail_test.go b/durable/timer_cancel_tail_test.go deleted file mode 100644 index a7dd8ccd..00000000 --- a/durable/timer_cancel_tail_test.go +++ /dev/null @@ -1,228 +0,0 @@ -package durable_test - -import ( - "context" - "testing" - "time" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// cancelableTimerMachine arms an `after` timer on entering waiting, and `leave` exits -// waiting, which cancels it. left also takes elapsed, so a timer that wrongly stays -// armed shows when it fires. -func cancelableTimerMachine() *state.Machine[string, string, *timerCtx] { - return state.ForgeFor[*timerCtx]("cancelableTimer"). - Action("markFired", func(c state.ActionCtx[*timerCtx]) (state.Effect, error) { - c.Entity.Fired++ - return nil, nil - }). - State("idle"). - State("waiting"). - State("left"). - State("done").Final(). - Initial("idle"). - Transition("idle").On("arm").GoTo("waiting"). - Transition("waiting").On("poke").GoTo("waiting"). - Transition("waiting").On("leave").GoTo("left"). - Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("done").Do("markFired"). - // A timer left armed past leave would fire elapsed here, where it is visible. - Transition("left").On("elapsed").GoTo("done").Do("markFired"). - Quench() -} - -// TestRecover_KeepsATailCancelOfACheckpointTimer pins that a timer pending at a -// checkpoint and canceled by a later step stays canceled after Recover. The tail's -// cancel replays before Recover re-arms the checkpoint's timers, so the re-arm must -// skip a timer the tail canceled. -func TestRecover_KeepsATailCancelOfACheckpointTimer(t *testing.T) { - ctx := context.Background() - m := cancelableTimerMachine() - store := durable.NewMemStore() - id := durable.InstanceID("tail-cancel") - clk := state.NewFakeClock(epoch) - h, err := durable.NewRunner(m, store, - durable.WithRunnerClock[string, string, *timerCtx](clk), - durable.WithCheckpointEvery[string, string, *timerCtx](2)). - Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatalf("Start: %v", err) - } - // arm and poke land a checkpoint while the timer is pending; leave, in the tail, - // cancels it. - for _, ev := range []string{"arm", "poke", "leave"} { - if _, err = h.Fire(ctx, ev); err != nil { - t.Fatalf("Fire(%q): %v", ev, err) - } - } - - recClock := state.NewFakeClock(epoch.Add(time.Hour)) - recovered, err := durable.Recover(ctx, m, store, id, - durable.WithRunnerClock[string, string, *timerCtx](recClock), - durable.WithCheckpointEvery[string, string, *timerCtx](2)) - if err != nil { - t.Fatalf("Recover: %v", err) - } - recClock.Advance(11 * time.Second) - if _, err = recovered.Tick(ctx); err != nil { - t.Fatalf("recovered Tick: %v", err) - } - snap := recovered.Instance().Snapshot() - if snap.Context.Fired != 0 || snap.Current != "left" { - t.Fatalf("after Recover the canceled timer fired: state %q, fired %d; want left, 0", snap.Current, snap.Context.Fired) - } -} - -// TestRecover_FiresACheckpointTimerInATailTick pins the tail-Tick case: a timer the -// checkpoint recorded fires in a tail Tick, so Recover must fire it in replay too. -// The checkpoint's timers used to be armed only after the replay walk, so the tick's -// replay fired nothing, the recovered Handle kept the pre-tick state, and the timer -// was armed a second time on top of it. -func TestRecover_FiresACheckpointTimerInATailTick(t *testing.T) { - ctx := context.Background() - m := cancelableTimerMachine() - store := durable.NewMemStore() - id := durable.InstanceID("tail-tick") - clk := state.NewFakeClock(epoch) - h, err := durable.NewRunner(m, store, - durable.WithRunnerClock[string, string, *timerCtx](clk), - durable.WithCheckpointEvery[string, string, *timerCtx](2)). - Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatal(err) - } - for _, ev := range []string{"arm", "poke"} { - if _, err = h.Fire(ctx, ev); err != nil { - t.Fatal(err) - } - } - clk.Advance(11 * time.Second) - if _, err = h.Tick(ctx); err != nil { - t.Fatal(err) - } - live := h.Instance().Snapshot() - rec, err := durable.Recover(ctx, m, store, id, - durable.WithRunnerClock[string, string, *timerCtx](state.NewFakeClock(epoch.Add(time.Hour))), - durable.WithCheckpointEvery[string, string, *timerCtx](2)) - if err != nil { - t.Fatalf("Recover: %v", err) - } - got := rec.Instance().Snapshot() - if got.Current != live.Current || got.Context.Fired != live.Context.Fired { - t.Fatalf("recovered %q fired=%d, live %q fired=%d", got.Current, got.Context.Fired, live.Current, live.Context.Fired) - } -} - -// TestRecover_ATimerFiredInATailTickDoesNotFireAgainAfterRecover pins that the -// timer a tail Tick fired stays fired after Recover: it fired once in the tick's -// replay, so the recovered Handle's own Tick must fire nothing, and the state and -// fired count must stay at the live run's. -func TestRecover_ATimerFiredInATailTickDoesNotFireAgainAfterRecover(t *testing.T) { - ctx := context.Background() - m := cancelableTimerMachine() - store := durable.NewMemStore() - id := durable.InstanceID("tail-tick-once") - clk := state.NewFakeClock(epoch) - h, err := durable.NewRunner(m, store, - durable.WithRunnerClock[string, string, *timerCtx](clk), - durable.WithCheckpointEvery[string, string, *timerCtx](2)). - Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatal(err) - } - for _, ev := range []string{"arm", "poke"} { - if _, err = h.Fire(ctx, ev); err != nil { - t.Fatal(err) - } - } - clk.Advance(11 * time.Second) - if _, err = h.Tick(ctx); err != nil { - t.Fatal(err) - } - live := h.Instance().Snapshot() - recClock := state.NewFakeClock(epoch.Add(time.Hour)) - rec, err := durable.Recover(ctx, m, store, id, - durable.WithRunnerClock[string, string, *timerCtx](recClock), - durable.WithCheckpointEvery[string, string, *timerCtx](2)) - if err != nil { - t.Fatalf("Recover: %v", err) - } - for round := 1; round <= 2; round++ { - recClock.Advance(11 * time.Second) - results, err := rec.Tick(ctx) - if err != nil { - t.Fatalf("recovered Tick %d: %v", round, err) - } - if len(results) != 0 { - t.Fatalf("recovered Tick %d fired %d timers, want none: the tail Tick already fired it", round, len(results)) - } - got := rec.Instance().Snapshot() - if got.Current != live.Current || got.Context.Fired != live.Context.Fired { - t.Fatalf("after recovered Tick %d: %q fired=%d, live %q fired=%d", round, got.Current, got.Context.Fired, live.Current, live.Context.Fired) - } - } -} - -// tickedMachine is cancelableTimerMachine with a plain target for its timer, so a -// Fire recorded after the tail Tick needs the post-tick state: from the pre-tick -// waiting, the kernel refuses it, and replay fails. -func tickedMachine() *state.Machine[string, string, *timerCtx] { - return state.ForgeFor[*timerCtx]("ticked"). - Action("markFired", func(c state.ActionCtx[*timerCtx]) (state.Effect, error) { - c.Entity.Fired++ - return nil, nil - }). - State("idle"). - State("waiting"). - State("ticked"). - State("done").Final(). - Initial("idle"). - Transition("idle").On("arm").GoTo("waiting"). - Transition("waiting").On("poke").GoTo("waiting"). - Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("ticked").Do("markFired"). - Transition("ticked").On("settle").GoTo("done"). - Quench() -} - -// TestRecover_ReplaysATailFireAfterATailTickFiredACheckpointTimer pins that a tail -// Fire recorded after the tail Tick still replays: its transition is declared only -// in the state the tick entered, so a replay that missed the tick's timer used to -// refuse it and fail Recover. -func TestRecover_ReplaysATailFireAfterATailTickFiredACheckpointTimer(t *testing.T) { - ctx := context.Background() - m := tickedMachine() - store := durable.NewMemStore() - id := durable.InstanceID("tail-tick-fire") - clk := state.NewFakeClock(epoch) - h, err := durable.NewRunner(m, store, - durable.WithRunnerClock[string, string, *timerCtx](clk), - durable.WithCheckpointEvery[string, string, *timerCtx](2)). - Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatal(err) - } - for _, ev := range []string{"arm", "poke"} { - if _, err = h.Fire(ctx, ev); err != nil { - t.Fatal(err) - } - } - clk.Advance(11 * time.Second) - if _, err = h.Tick(ctx); err != nil { - t.Fatal(err) - } - if _, err = h.Fire(ctx, "settle"); err != nil { - t.Fatal(err) - } - live := h.Instance().Snapshot() - rec, err := durable.Recover(ctx, m, store, id, - durable.WithRunnerClock[string, string, *timerCtx](state.NewFakeClock(epoch.Add(time.Hour))), - durable.WithCheckpointEvery[string, string, *timerCtx](2)) - if err != nil { - t.Fatalf("Recover: %v", err) - } - got := rec.Instance().Snapshot() - if got.Current != live.Current || got.Context.Fired != live.Context.Fired { - t.Fatalf("recovered %q fired=%d, live %q fired=%d", got.Current, got.Context.Fired, live.Current, live.Context.Fired) - } -} diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index c97146e9..1763fc8a 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -13,18 +13,20 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Added -- **`Scheduler.ArmAt`** arms one delayed transition at an absolute deadline — the - same timer id, event and firing behavior a `ScheduleAfter` for it would carry — - without reading the clock, where `Absorb` reads one to turn the effect's declared - delay into a deadline. A host that persisted a timer's deadline, as `durable` does - for the timers a checkpoint recorded, re-arms it exactly, so no reading is taken. - It's additive, within v1.1.0. - **`ActorSystem.WithParentFireObserver`** calls a function with each parent Fire the system drives (a `ParentFire`: its result, refused ones included, the actor it came from, whether it settled that actor, with its output or error, and whether it routed the onError of a spawn that couldn't start), so a host that records a delivery or spawn can tell a parent transition refused because its context ended from one that applied, and which Fire carried the actor's output. It's additive, within v1.1.0. +- **`SpawnActor.NoOnError` and `ParentFire.NoOnError`** report that an invoked actor + declared no onError. Such an actor's `OnError` holds the zero event, which the system + still fires at the parent when the actor can't start, as before, so its refusal looks + like a declared onError the parent refused. The flags tell them apart without + matching the refusal's reason. An onError that is itself the zero event, such as the + first constant of an `iota` enum, counts as declared when the machine was built with + `WithInvokeOnError`; an invocation loaded from JSON counts one as declared only when + it isn't the zero event. It's additive, within v1.1.0. - **`ActorSystem.AbsorbRespawn`** is `Absorb` for actors a host spawns again after rebuilding the parent from a record that already holds every parent Fire their earlier start drove: an actor it spawns starts as under `Absorb`, but its start diff --git a/state/actor.go b/state/actor.go index b7b4b6ee..f9ff0919 100644 --- a/state/actor.go +++ b/state/actor.go @@ -87,6 +87,11 @@ type SpawnActor struct { // under in the ActorSystem (its systemId), so a sibling can address it // by a well-known name rather than by ref. Empty when unset. SystemID string `json:"systemId,omitempty"` + // NoOnError reports that an invoked actor declared no onError, so OnError holds the + // zero event, which the system still fires at the parent when the actor can't start. + // A host that must tell a refused onError from an absent one reads it. A dynamic + // spawn with no onError leaves OnError nil instead, and escalates. + NoOnError bool `json:"noOnError,omitempty"` } // StopActor is the effect the kernel emits when an instance exits a state that @@ -237,13 +242,14 @@ func (i *Instance[S, E, C]) actorEffectsOnEntry(entries []S, tr *Trace) []Effect } id := actorInvocationID(m.name, s, ix, inv) out = append(out, SpawnActor{ - ID: id, - Src: inv.Src, - Input: inv.Input, - OnDone: inv.OnDone, - OnError: inv.OnError, - State: fmtState(s), - SystemID: inv.SystemID, + ID: id, + Src: inv.Src, + Input: inv.Input, + OnDone: inv.OnDone, + OnError: inv.OnError, + State: fmtState(s), + SystemID: inv.SystemID, + NoOnError: !inv.declaresOnError(), }) tr.note("actor.spawn." + id) } diff --git a/state/actor_invoke_undeclared_test.go b/state/actor_invoke_undeclared_test.go new file mode 100644 index 00000000..f4d72a57 --- /dev/null +++ b/state/actor_invoke_undeclared_test.go @@ -0,0 +1,90 @@ +package state_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// spawnEffect returns the SpawnActor entering supervising emits for m. +func spawnEffect[E comparable](t *testing.T, m *state.Machine[string, E, *trec], start E) state.SpawnActor { + t.Helper() + res := m.Cast(&trec{}, state.WithInitialState("idle")).Fire(context.Background(), start) + for _, eff := range res.Effects { + if sp, ok := eff.(state.SpawnActor); ok { + return sp + } + } + t.Fatal("entering supervising spawned no actor") + return state.SpawnActor{} +} + +func invokeParent(opts ...state.InvokeOption) *state.Machine[string, string, *trec] { + return state.ForgeFor[*trec]("parent"). + Actor("child"). + State("idle"). + State("supervising").InvokeActor("child", opts...). + Initial("idle"). + Transition("idle").On("start").GoTo("supervising"). + Quench() +} + +// TestInvokeActor_NoOnError_Flags pins SpawnActor.NoOnError: set when the invoke +// declared no onError, clear when it declared one. +func TestInvokeActor_NoOnError_Flags(t *testing.T) { + if sp := spawnEffect(t, invokeParent(), "start"); !sp.NoOnError { + t.Fatal("NoOnError = false for an invoke with no onError") + } + if sp := spawnEffect(t, invokeParent(state.WithInvokeOnError("failed")), "start"); sp.NoOnError { + t.Fatal("NoOnError = true for an invoke with an onError") + } +} + +// TestInvokeActor_ZeroValueOnError_IsDeclared pins that an onError that is the zero +// event, as the first constant of an iota enum is, still counts as declared. +func TestInvokeActor_ZeroValueOnError_IsDeclared(t *testing.T) { + const ( + failed = iota + start + ) + m := state.Forge[string, int, *trec]("parent"). + Actor("child"). + State("idle"). + State("supervising").InvokeActor("child", state.WithInvokeOnError(failed)). + Initial("idle"). + CurrentStateFn(func(*trec) string { return "idle" }). + Transition("idle").On(start).GoTo("supervising"). + Quench() + if sp := spawnEffect(t, m, start); sp.NoOnError { + t.Fatal("NoOnError = true for an onError that is the zero event") + } +} + +// TestInvokeActor_NoOnError_ParentFireReportsIt pins that the parent Fire routing a +// failed spawn's onError reports NoOnError as its SpawnActor did, while the zero event +// still fires at the parent, as v1 documents. +func TestInvokeActor_NoOnError_ParentFireReportsIt(t *testing.T) { + for _, declared := range []bool{false, true} { + var opts []state.InvokeOption + if declared { + opts = append(opts, state.WithInvokeOnError("failed")) + } + parent := invokeParent(opts...).Cast(&trec{}, state.WithInitialState("idle")) + var fires []state.ParentFire[string] + sys := state.NewActorSystem(parent). + Register("child", func(map[string]any) (state.ActorInstance, error) { + return nil, errors.New("the child can't start") + }). + WithParentFireObserver(func(pf state.ParentFire[string]) { fires = append(fires, pf) }) + ctx := context.Background() + sys.Absorb(ctx, parent.Fire(ctx, "start").Effects) + if len(fires) != 1 || !fires[0].SpawnFailed { + t.Fatalf("declared=%v: parent Fires = %+v, want the failed spawn's onError", declared, fires) + } + if fires[0].NoOnError == declared { + t.Fatalf("declared=%v: ParentFire.NoOnError = %v", declared, fires[0].NoOnError) + } + } +} diff --git a/state/actor_system.go b/state/actor_system.go index 87ea6ddd..73e12ff4 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -490,7 +490,7 @@ func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err defer s.setQuiet(prev) } res := s.parent.Fire(ctx, ev) - s.noteParentFire(ParentFire[S]{Result: res, ActorID: e.ID, SpawnFailed: true}) + s.noteParentFire(ParentFire[S]{Result: res, ActorID: e.ID, SpawnFailed: true, NoOnError: e.NoOnError}) s.Absorb(ctx, res.Effects) } @@ -918,6 +918,11 @@ type ParentFire[S comparable] struct { // SpawnFailed reports that the Fire routed the onError of a spawn that couldn't // start (an unbound Src, or a behavior that returned an error). SpawnFailed bool + // NoOnError reports, with SpawnFailed, that the spawn declared no onError: the Fire + // carried the zero event an invoked actor with no WithInvokeOnError routes (see + // SpawnActor.NoOnError), so its refusal says nothing was declared to catch the + // failure, not that a declared onError was refused. + NoOnError bool // Settle reports that the Fire routed a settled actor's onDone or onError, which // carried the actor's outcome as its event data (WithEventData): Err for an onError, // Output for an onDone. A message the actor sent the parent, or the onError of a diff --git a/state/driver.go b/state/driver.go index c407fe51..52c7eebc 100644 --- a/state/driver.go +++ b/state/driver.go @@ -89,20 +89,6 @@ func (s *Scheduler[S, E, C]) absorbLocked(effects []Effect) { } } -// ArmAt arms the delayed transition id — the same event a ScheduleAfter for id -// would carry — at the absolute deadline due, without reading the clock. Absorb -// computes a timer's deadline from one clock reading plus the effect's declared -// Delay; a host that persisted the deadline itself, as a durable runtime does for -// the timers a checkpoint recorded, re-arms it exactly through ArmAt instead, so -// no reading is taken. A timer already armed under id is re-armed at due. It fires -// on the Tick whose clock reading reaches due, like any other, and a CancelScheduled -// for id cancels it. -func (s *Scheduler[S, E, C]) ArmAt(id string, event E, due time.Time) { - s.mu.Lock() - defer s.mu.Unlock() - s.pending[id] = pending[E]{event: event, due: due} -} - // Pending reports the number of armed (not-yet-fired, not-canceled) timers. A // test asserts on it to confirm a timer was scheduled or auto-canceled on exit. func (s *Scheduler[S, E, C]) Pending() int { diff --git a/state/invoke.go b/state/invoke.go index 95994b30..39aa4fad 100644 --- a/state/invoke.go +++ b/state/invoke.go @@ -79,6 +79,18 @@ type Invocation[S comparable, E comparable, C any] struct { // extra preserves unknown JSON keys a newer producer emitted so they survive a // load -> save cycle (forward-compat). Never inspected by the kernel. extra map[string]json.RawMessage + // hasOnError records that the builder was given WithInvokeOnError, since OnError + // holds the zero event either way. It doesn't serialize, so an invocation loaded + // from JSON falls back to OnError not being the zero event (declaresOnError). + hasOnError bool +} + +// declaresOnError reports whether the invocation declared an onError: the builder +// was given WithInvokeOnError, or, for one loaded from JSON, OnError isn't the zero +// event. +func (inv *Invocation[S, E, C]) declaresOnError() bool { + var zero E + return inv.hasOnError || inv.OnError != zero } // invocationKnownKeys is the set of JSON keys Invocation models; anything else is diff --git a/state/kernel.go b/state/kernel.go index bb4e43e1..d6cf127e 100644 --- a/state/kernel.go +++ b/state/kernel.go @@ -995,11 +995,12 @@ func (b *Builder[S, E, C]) Invoke(src string, opts ...InvokeOption) *Builder[S, o(&cfg) } b.curState.state.Invoke = append(b.curState.state.Invoke, Invocation[S, E, C]{ - ID: cfg.id, - Src: Ref{Name: src, Params: cfg.params}, - Input: cfg.input, - OnDone: invokeOutcome[E](cfg.onDone, cfg.hasOnDone), - OnError: invokeOutcome[E](cfg.onError, cfg.hasOnError), + ID: cfg.id, + Src: Ref{Name: src, Params: cfg.params}, + Input: cfg.input, + OnDone: invokeOutcome[E](cfg.onDone, cfg.hasOnDone), + OnError: invokeOutcome[E](cfg.onError, cfg.hasOnError), + hasOnError: cfg.hasOnError, }) return b } @@ -1039,13 +1040,14 @@ func (b *Builder[S, E, C]) InvokeActor(src string, opts ...InvokeOption) *Builde o(&cfg) } b.curState.state.Invoke = append(b.curState.state.Invoke, Invocation[S, E, C]{ - ID: cfg.id, - Src: Ref{Name: src, Params: cfg.params}, - Input: cfg.input, - OnDone: invokeOutcome[E](cfg.onDone, cfg.hasOnDone), - OnError: invokeOutcome[E](cfg.onError, cfg.hasOnError), - Kind: ActorKindMachine, - SystemID: cfg.systemID, + ID: cfg.id, + Src: Ref{Name: src, Params: cfg.params}, + Input: cfg.input, + OnDone: invokeOutcome[E](cfg.onDone, cfg.hasOnDone), + OnError: invokeOutcome[E](cfg.onError, cfg.hasOnError), + Kind: ActorKindMachine, + SystemID: cfg.systemID, + hasOnError: cfg.hasOnError, }) return b } diff --git a/state/scheduler_test.go b/state/scheduler_test.go index d2ac669b..2cc8c615 100644 --- a/state/scheduler_test.go +++ b/state/scheduler_test.go @@ -249,81 +249,3 @@ func assertCancelEffect(t *testing.T, effects []state.Effect, id string) { } t.Fatalf("no CancelScheduled effect for id %q in %v", id, effects) } - -// readCountingClock wraps a Clock and counts its Now() readings, so a test can -// prove a driver step took none. -type readCountingClock struct { - state.Clock - reads int -} - -func (c *readCountingClock) Now() time.Time { - c.reads++ - return c.Clock.Now() -} - -func (c *readCountingClock) Advance(d time.Duration) { - c.Clock.(interface{ Advance(time.Duration) }).Advance(d) -} - -// TestScheduler_ArmAt_ArmsAtTheDeadlineWithoutReadingTheClock proves ArmAt arms a -// timer at an absolute deadline — a deadline a host persisted and re-arms exactly, -// rather than re-deriving from a fresh reading plus a declared delay — without -// taking the clock reading Absorb would. The armed timer fires when a Tick's -// reading reaches the deadline, and a CancelScheduled drops it as any other. -func TestScheduler_ArmAt_ArmsAtTheDeadlineWithoutReadingTheClock(t *testing.T) { - m := afterMachine() - clk := &readCountingClock{Clock: state.NewFakeClock(time.Unix(0, 0))} - inst := m.Cast(&trec{}, state.WithInitialState("armed"), state.WithClock[string](clk)) - sch := state.NewScheduler(inst) - ctx := context.Background() - - id := state.ScheduleID("timed", "armed", 0) - due := time.Unix(0, 5*time.Second.Nanoseconds()) - sch.ArmAt(id, "elapsed", due) - if clk.reads != 0 { - t.Fatalf("ArmAt took %d clock readings, want none", clk.reads) - } - if !sch.HasPending(id) { - t.Fatalf("ArmAt should arm timer %q", id) - } - - // Before the deadline the timer stays armed; a tick fires nothing and the - // instance stays in armed. - if fired := sch.Tick(ctx); len(fired) != 0 { - t.Fatalf("tick before the deadline fired %d events", len(fired)) - } - if inst.Current() != "armed" { - t.Fatalf("before the deadline, want armed, got %q", inst.Current()) - } - - // Past the deadline the timer fires the delayed event and the instance advances. - clk.Advance(5 * time.Second) - if fired := sch.Tick(ctx); len(fired) != 1 || inst.Current() != "fired" { - t.Fatalf("tick past the deadline: fired=%d state=%q, want 1 and fired", len(fired), inst.Current()) - } - - // A deadline already in the past arms as immediately due, so an elapsed timer - // fires on the next Tick. - inst = m.Cast(&trec{}, state.WithInitialState("armed"), state.WithClock[string](clk)) - sch = state.NewScheduler(inst) - sch.ArmAt(id, "elapsed", time.Unix(0, 0)) - clk.Advance(time.Nanosecond) - if fired := sch.Tick(ctx); len(fired) != 1 || inst.Current() != "fired" { - t.Fatalf("tick past an elapsed deadline: fired=%d state=%q, want 1 and fired", len(fired), inst.Current()) - } - - // A CancelScheduled for an ArmAt-armed timer drops it, as for an Absorb-armed one. - inst = m.Cast(&trec{}, state.WithInitialState("armed"), state.WithClock[string](clk)) - sch = state.NewScheduler(inst) - sch.ArmAt(id, "elapsed", clk.Now().Add(time.Hour)) - leave := inst.Fire(ctx, "leave") - assertCancelEffect(t, leave.Effects, id) - sch.Absorb(ctx, leave.Effects) - if sch.HasPending(id) { - t.Fatalf("cancel should drop the ArmAt-armed timer %q", id) - } - if fired := sch.Tick(ctx); len(fired) != 0 { - t.Fatalf("canceled ArmAt-armed timer fired %d events", len(fired)) - } -} From 3fd5b9bc83879d740edd517a607f6dfa9bc50521 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Sun, 15 Nov 2026 23:07:00 -0700 Subject: [PATCH 26/38] fix(durable): don't retry a spawn whose zero-event onError applied; pin review questions with tests A spawn that failed with no onError declared counted as uncaught even when the parent handled the zero event it routes, so Recover retried it, running the behavior again. An onError Fire that applied now always counts as caught; NoOnError only decides what a refused zero event means. Tests that settle questions from the review: - a re-entry spawn retried at Recover doesn't repeat the first start's message; - a lifted Fire that re-enters a state during AbsorbRespawn starts its actor once; - a timer leaving a service state, and a timer entering an actor state, leave the drivers as live does. Skipped: Tick hands a timer transition's effects only to the scheduler, which #236 fixes. Signed-off-by: Ray Karnes --- durable/reentry_respawn_test.go | 77 ++++++++++++++++++++++ durable/runner.go | 15 +++-- durable/spawn_zero_event_test.go | 59 +++++++++++++++++ durable/tick_drivers_test.go | 108 +++++++++++++++++++++++++++++++ state/actor_respawn_lift_test.go | 50 ++++++++++++++ 5 files changed, 302 insertions(+), 7 deletions(-) create mode 100644 durable/reentry_respawn_test.go create mode 100644 durable/spawn_zero_event_test.go create mode 100644 durable/tick_drivers_test.go create mode 100644 state/actor_respawn_lift_test.go diff --git a/durable/reentry_respawn_test.go b/durable/reentry_respawn_test.go new file mode 100644 index 00000000..1aff23ec --- /dev/null +++ b/durable/reentry_respawn_test.go @@ -0,0 +1,77 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// reentryGreeter is an actor that sends its parent "hello" as it starts. +type reentryGreeter struct{ sent bool } + +func (g *reentryGreeter) DeliverFire(context.Context, any) (bool, any) { return false, nil } +func (g *reentryGreeter) ChildEffects() []state.Effect { + if g.sent { + return nil + } + g.sent = true + return []state.Effect{state.SendParent{Event: "hello"}} +} +func (g *reentryGreeter) Output() any { return nil } + +// TestRecover_ARetriedReentrySpawnDoesNotRepeatTheFirstStartsMessage pins that when an +// actor started, sent its parent a message, and then failed to start again on a +// re-entry with no onError, Recover's retry doesn't apply that first message again: the +// journal already holds it, and a retry that still fails sends nothing. +func TestRecover_ARetriedReentrySpawnDoesNotRepeatTheFirstStartsMessage(t *testing.T) { + ctx := context.Background() + note := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, fmt.Sprint(in.Event)) + return c + } + m := state.ForgeFor[stepCtx]("reentryRespawn"). + Reducer("note", note). + Actor("greeter"). + State("greeting").InvokeActor("greeter"). + Initial("greeting"). + Transition("greeting").On("hello").GoTo("greeting").Assign("note"). + Transition("greeting").On("re").GoTo("greeting").Reenter().Assign("note"). + Transition("greeting").On("poke").GoTo("greeting").Assign("note"). + Quench() + var calls int + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { + calls++ + if calls > 1 { + return nil, errors.New("the greeter can't start again") + } + return &reentryGreeter{}, nil + }, + })} + store, id := durable.NewMemStore(), durable.InstanceID("reentry-respawn") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("greeting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for _, ev := range []string{"poke", "re", "poke"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire(%s): %v", ev, err) + } + } + live := fmt.Sprint(h.Instance().Entity().Notes) + if live != "[hello poke re poke]" { + t.Fatalf("live notes = %s, want the first start's hello, then poke, re and poke", live) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != live { + t.Fatalf("recovered notes = %s, want the live %s (behavior ran %d times)", got, live, calls) + } +} diff --git a/durable/runner.go b/durable/runner.go index 9ba6ade9..42f2bb54 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -719,13 +719,14 @@ func (p *parentFires[S]) inspect(ev state.InspectionEvent) { func (p *parentFires[S]) note(pf state.ParentFire[S]) { p.mu.Lock() p.fires = append(p.fires, pf) - // A spawn whose declared onError applied, or was refused for a reason other than - // a context ending, such as a failing guard, is handled: the journal holds the - // onError or its refusal, and a retry would run the behavior again. One a context's - // ending refused isn't: the step that drove it recorded nothing. Nor is one that - // declared no onError (NoOnError), whose zero event the parent refuses: nothing - // caught the failure, so a retry is right. - if pf.SpawnFailed && !pf.NoOnError && (pf.Result.Err == nil || !isContextErr(pf.Result.Err)) { + // A spawn whose onError Fire applied is handled: the journal holds it, and a retry + // would run the behavior and apply it again. That holds for the zero event a spawn + // with no onError declared routes, when the parent handles it. A declared onError + // refused for a reason other than a context ending, such as a failing guard, is + // handled too: the journal holds the refusal. One a context's ending refused isn't: + // the step that drove it recorded nothing. Nor is a refused zero event (NoOnError): + // nothing caught the failure, so a retry is right. + if pf.SpawnFailed && (pf.Result.Err == nil || (!pf.NoOnError && !isContextErr(pf.Result.Err))) { if p.failed == nil { p.failed = map[string]bool{} } diff --git a/durable/spawn_zero_event_test.go b/durable/spawn_zero_event_test.go new file mode 100644 index 00000000..69b27405 --- /dev/null +++ b/durable/spawn_zero_event_test.go @@ -0,0 +1,59 @@ +package durable_test + +import ( + "context" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestRecover_DoesNotReapplyAnAppliedZeroEventOnError pins a failed spawn with no +// onError declared whose zero event the parent handles: the zero event applied live, +// and the journal holds it, so Recover must not retry the spawn and apply it again. +func TestRecover_DoesNotReapplyAnAppliedZeroEventOnError(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("zeroOnError"). + Reducer("note", func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "caught") + return c + }). + Actor("child"). + State("idle"). + SuperState("spawning").InvokeActor("child"). + SubState("waiting"). + SubState("caught"). + Initial("waiting"). + EndSuperState(). + Initial("idle"). + Transition("idle").On("start").GoTo("waiting"). + // The zero event moves between children, so spawning, and its actor, stay. + Transition("waiting").On("").GoTo("caught").Assign("note"). + Transition("caught").On("poke").GoTo("caught"). + Quench() + store, id := durable.NewMemStore(), durable.InstanceID("zero-onerror") + var calls int + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": failingSpawn(func() { calls++ }), + })} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + live := fmt.Sprint(h.Instance().Entity().Notes) + if live != "[caught]" { + t.Fatalf("live notes = %s, want the zero event to apply once", live) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != live || calls != 1 { + t.Fatalf("recovered notes = %s after %d behavior runs, want the live %s and one run", got, calls, live) + } +} diff --git a/durable/tick_drivers_test.go b/durable/tick_drivers_test.go new file mode 100644 index 00000000..4c8cd73b --- /dev/null +++ b/durable/tick_drivers_test.go @@ -0,0 +1,108 @@ +package durable_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestTick_ATimerThatLeavesAServiceStateStopsTheService pins that a timer-driven +// transition out of a state stops the service that state invokes, as a host Fire's +// exit does: after the Tick, RunService reports no service in flight. +func TestTick_ATimerThatLeavesAServiceStateStopsTheService(t *testing.T) { + t.Skip("Tick hands a timer transition's effects only to the scheduler, not the service and actor drivers; #236 fixes it") + ctx := context.Background() + var runs int + fetch := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { runs++; return "ok", nil } + m := state.ForgeFor[stepCtx]("tickExit"). + Service("fetch", fetch). + State("idle"). + State("fetching").Invoke("fetch", state.WithInvokeOnDone("fetched")). + State("timedOut"). + Initial("idle"). + Transition("idle").On("begin").GoTo("fetching"). + Transition("fetching").On("fetched").GoTo("fetching"). + Transition("fetching").After(5 * time.Second).On("timeout").GoTo("timedOut"). + Quench() + clk := state.NewFakeClock(epoch) + h, err := durable.NewRunner(m, durable.NewMemStore(), + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fetch)), + ).Start(ctx, "tick-exit", stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "begin"); err != nil { + t.Fatalf("Fire(begin): %v", err) + } + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := h.Instance().Current(); got != "timedOut" { + t.Fatalf("state = %q, want timedOut", got) + } + if _, ran, err := h.RunService(ctx, state.InvokeID("tickExit", "fetching", 0)); ran || err != nil { + t.Fatalf("RunService after the timer left fetching = ran %v, %v (runs %d), want no service in flight", ran, err, runs) + } +} + +// TestRecover_ATickEnteredStatesActorMatchesLive pins that Recover leaves a state a +// timer entered with the actors the live run had: live, a Tick that enters greeting +// spawns its greeter, whose hello applies once; Recover then applies it no more and no +// less than live. +func TestRecover_ATickEnteredStatesActorMatchesLive(t *testing.T) { + t.Skip("Tick hands a timer transition's effects only to the scheduler, not the service and actor drivers; #236 fixes it") + ctx := context.Background() + note := func(in state.AssignCtx[stepCtx]) stepCtx { + c := in.Entity + c.Notes = append(c.Notes, "hello") + return c + } + m := state.ForgeFor[stepCtx]("tickEnter"). + Reducer("note", note). + Actor("greeter"). + State("idle"). + State("waiting"). + State("greeting").InvokeActor("greeter"). + Initial("idle"). + Transition("idle").On("go").GoTo("waiting"). + Transition("waiting").After(5 * time.Second).On("due").GoTo("greeting"). + Transition("greeting").On("hello").GoTo("greeting").Assign("note"). + Transition("greeting").On("poke").GoTo("greeting"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { return &reentryGreeter{}, nil }, + }), + } + store, id := durable.NewMemStore(), durable.InstanceID("tick-enter") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + live := fmt.Sprint(h.Instance().Entity().Notes) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != live || live != "[hello]" { + t.Fatalf("live notes %s, recovered %s; want [hello] for both: the Tick's state spawns its greeter once", live, got) + } +} diff --git a/state/actor_respawn_lift_test.go b/state/actor_respawn_lift_test.go new file mode 100644 index 00000000..bde2d662 --- /dev/null +++ b/state/actor_respawn_lift_test.go @@ -0,0 +1,50 @@ +package state_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestActorSystem_AbsorbRespawn_ALiftedFireReenteringAStateStartsItsActorOnce pins +// what a lifted parent Fire does to an actor AbsorbRespawn hasn't respawned yet. outer's +// actor fails to start now, which it didn't before, so its onError is a new Fire and is +// heard; that Fire re-enters inner, whose greeter starts there as a new start, and its +// hello reaches the parent once. AbsorbRespawn's own spawn of the greeter then finds it +// running, and doesn't start it, or send its hello, a second time. +func TestActorSystem_AbsorbRespawn_ALiftedFireReenteringAStateStartsItsActorOnce(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("lift"). + Actor("broken"). + Actor("greeter"). + SuperState("outer").InvokeActor("broken", state.WithInvokeOnError("brokenFailed")). + SubState("inner").InvokeActor("greeter"). + Initial("inner"). + EndSuperState(). + Initial("outer"). + Transition("inner").On("brokenFailed").GoTo("inner").Reenter(). + Transition("inner").On("hello").GoTo("inner"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("inner")) + var fired []string + sys := state.NewActorSystem(inst). + WithParentFireObserver(func(pf state.ParentFire[string]) { fired = append(fired, pf.Result.Trace.Event) }) + sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("can't start now") }) + starts := 0 + sys.Register("greeter", func(map[string]any) (state.ActorInstance, error) { + starts++ + return &startGreeter{}, nil + }) + sys.AbsorbRespawn(ctx, inst.StartEffects()) + hellos := 0 + for _, ev := range fired { + if ev == "hello" { + hellos++ + } + } + if starts != 1 || hellos != 1 { + t.Fatalf("greeter started %d times and its hello reached the parent %d times (parent Fires %q), want once each", starts, hellos, fired) + } +} From e60701e8f19dc80ee1eb9f93fb8ceeaafd060dd8 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Sun, 15 Nov 2026 23:12:36 -0700 Subject: [PATCH 27/38] fix(durable): record a chained timer's deadline from the read the scheduler armed it at Tick recorded a chained timer's deadline from the tick's last clock read, later than the absorb read the scheduler armed it at, so a checkpoint persisted a later deadline and the timer fired late after Recover. Scheduler.Tick reads the clock once to find each due timer and once to absorb its effects; Tick and its replay now take the i-th fire's absorb read. A state test pins that order of reads, so a change to it fails there rather than drifting deadlines silently. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 10 ++ durable/chained_deadline_internal_test.go | 159 ++++++++++++++++++++++ durable/clock.go | 19 +++ durable/runner.go | 37 ++++- state/scheduler_clock_reads_test.go | 72 ++++++++++ 5 files changed, 291 insertions(+), 6 deletions(-) create mode 100644 durable/chained_deadline_internal_test.go create mode 100644 state/scheduler_clock_reads_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index be9b4a49..16bede24 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -142,6 +142,16 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Fixed +- **A chained timer's deadline is the one the scheduler armed it at.** A `Tick` recorded + the deadline of a timer its fired transition chained from the tick's last clock read, + which is later than the read the scheduler armed it at. With a real clock, a checkpoint + persisted the later deadline, so after `Recover` the timer fired late, and the drift + grew along an `after` chain. `Tick` and its replay now take each fired timer's absorb + read, and `state` pins the order of reads a `Tick` takes. +- **A spawn whose zero-event onError applied isn't retried.** A spawn that failed with no + onError declared counted as uncaught even when the parent handled the zero event it + routes, so `Recover` ran the behavior again. An onError Fire that applied now always + counts as caught. - **A failed checkpoint no longer makes the next step conflict.** `Tick`, `RunService` and `DeliverToActor` now advance the next step as soon as the append lands. - **A deferred checkpoint survives an unrelated caller's cancel.** A checkpoint that diff --git a/durable/chained_deadline_internal_test.go b/durable/chained_deadline_internal_test.go new file mode 100644 index 00000000..65c15e20 --- /dev/null +++ b/durable/chained_deadline_internal_test.go @@ -0,0 +1,159 @@ +package durable + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/stablekernel/crucible/state" +) + +// steppingClock advances one millisecond on every read while stepping, so each read in a +// Tick is a distinct instant, as a real clock's are; with stepping off it holds still. +type steppingClock struct { + mu sync.Mutex + now time.Time + stepping bool +} + +func (c *steppingClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + t := c.now + if c.stepping { + c.now = c.now.Add(time.Millisecond) + } + return t +} + +func (c *steppingClock) After(time.Duration) <-chan time.Time { return make(chan time.Time) } + +func (c *steppingClock) set(t time.Time, stepping bool) { + c.mu.Lock() + c.now, c.stepping = t, stepping + c.mu.Unlock() +} + +// TestTick_RecordsAChainedTimersDeadlineAsTheSchedulerArmedIt pins that the deadline the +// Handle records for a chained timer, which a checkpoint persists and Recover re-arms, +// is the one the scheduler armed it at: the scheduler must not fire the timer before the +// recorded deadline. +func TestTick_RecordsAChainedTimersDeadlineAsTheSchedulerArmedIt(t *testing.T) { + ctx := context.Background() + type cx struct{} + m := state.ForgeFor[cx]("chain"). + State("idle"). + State("a"). + State("b"). + State("c"). + Initial("idle"). + Transition("idle").On("go").GoTo("a"). + Transition("a").After(time.Second).On("toB").GoTo("b"). + Transition("b").After(time.Second).On("toC").GoTo("c"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := &steppingClock{now: base} + h, err := NewRunner(m, NewMemStore(), WithRunnerClock[string, string, cx](clk)). + Start(ctx, "chain", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + // Tick with a moving clock: the timer into b fires, and b's timer is chained. + clk.set(base.Add(2*time.Second), true) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := h.inst.Current(); got != "b" { + t.Fatalf("state = %q, want b", got) + } + var recorded time.Time + for _, pt := range h.timers { + recorded = pt.due + } + if len(h.timers) != 1 { + t.Fatalf("timer table holds %d timers, want b's alone", len(h.timers)) + } + // Just before the recorded deadline, the scheduler must not consider b's timer due. + clk.set(recorded.Add(-time.Millisecond), false) + if fired := h.sched.Tick(ctx); len(fired) != 0 { + t.Fatalf("the scheduler fired b's timer at %v, before the recorded deadline %v: a checkpoint would re-arm it later than live", recorded.Add(-time.Millisecond), recorded) + } +} + +// TestTick_RecordsEachChainedDeadlineInATwoTimerTick pins the same for two timers that +// fire in one Tick, each chaining another, and that Recover's replay of that Tick ends +// with the same timer table as the live Handle. +func TestTick_RecordsEachChainedDeadlineInATwoTimerTick(t *testing.T) { + ctx := context.Background() + type cx struct{} + m := state.ForgeFor[cx]("pair"). + State("idle"). + SuperState("both"). + Region("left"). + Initial("l1"). + SubState("l1"). + SubState("l2"). + EndRegion(). + Region("right"). + Initial("r1"). + SubState("r1"). + SubState("r2"). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("both"). + Transition("l1").After(time.Second).On("toL2").GoTo("l2"). + Transition("l2").After(time.Second).On("lDone").GoTo("l2"). + Transition("r1").After(time.Second).On("toR2").GoTo("r2"). + Transition("r2").After(time.Second).On("rDone").GoTo("r2"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := &steppingClock{now: base} + store := NewMemStore() + opts := []Option[string, string, cx]{WithRunnerClock[string, string, cx](clk)} + h, err := NewRunner(m, store, opts...).Start(ctx, "pair", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + clk.set(base.Add(2*time.Second), true) + fired, err := h.Tick(ctx) + if err != nil || len(fired) != 2 { + t.Fatalf("Tick fired %d timers, err %v; want both", len(fired), err) + } + if len(h.timers) != 2 { + t.Fatalf("timer table holds %d timers, want the two chained ones", len(h.timers)) + } + earliest := time.Time{} + for _, pt := range h.timers { + if earliest.IsZero() || pt.due.Before(earliest) { + earliest = pt.due + } + } + clk.set(earliest.Add(-time.Millisecond), false) + if got := h.sched.Tick(ctx); len(got) != 0 { + t.Fatalf("the scheduler fired a chained timer before its recorded deadline %v", earliest) + } + live := map[string]time.Time{} + for id, pt := range h.timers { + live[id] = pt.due + } + recovered, err := Recover(ctx, m, store, "pair", WithRunnerClock[string, string, cx](state.NewFakeClock(base.Add(time.Hour)))) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if len(recovered.timers) != len(live) { + t.Fatalf("recovered timer table holds %d timers, want %d", len(recovered.timers), len(live)) + } + for id, due := range live { + if got := recovered.timers[id].due; !got.Equal(due) { + t.Fatalf("recovered deadline for %s = %v, want the live %v", id, got, due) + } + } +} diff --git a/durable/clock.go b/durable/clock.go index 60682ad9..5f37899c 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -159,6 +159,25 @@ func (c *replayClock) Now() time.Time { return c.last } +// mark returns how many recorded readings Now has handed out, so a caller can find +// the readings a step took after it. +func (c *replayClock) mark() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.cursor +} + +// readingAt returns the recorded reading at index i, ok false when Now hasn't handed it +// out, or the recorded readings ran out before it. +func (c *replayClock) readingAt(i int) (time.Time, bool) { + c.mu.Lock() + defer c.mu.Unlock() + if i < 0 || i >= c.cursor || i >= len(c.readings) { + return time.Time{}, false + } + return time.Unix(0, c.readings[i]).UTC(), true +} + // lastRead returns the reading Now last returned: the instant a replayed timer arming // or tick computed its deadlines against. func (c *replayClock) lastRead() time.Time { diff --git a/durable/runner.go b/durable/runner.go index 42f2bb54..cda348cb 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -995,6 +995,16 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro mark := h.recClock.markBuf() results := h.sched.Tick(h.stepContext(ctx)) now, haveNow := h.recClock.lastReadingSince(mark) + // Each fired timer's chained timers were armed at its absorb read (tickArmRead); + // take those reads now, before the Record drains the buffer. + armAt := make([]time.Time, len(results)) + for i := range results { + at, ok := h.recClock.armReadingAt(mark + tickArmRead(i)) + if !ok { + at = now + } + armAt[i] = at + } // 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. @@ -1009,11 +1019,11 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro // Reconcile the Handle's timer table with the tick: arm any timer a chained // transition scheduled, then drop the ones the tick fired, by id, so a checkpoint // after the tick persists exactly the still-pending deadlines. A chained timer's - // deadline counts from the tick's last read, as replay's does (a SystemClock's - // intra-tick drift is sub-timer). + // deadline counts from the read the scheduler armed it at (tickArmRead), as + // replay's does. if haveNow { for i := range results { - h.armTimersFrom(results[i].Effects, now) + h.armTimersFrom(results[i].Effects, armAt[i]) forgetSettled(h.settled, results[i].Effects) } h.dropFiredTimers() @@ -1862,7 +1872,11 @@ func replayRecord[S comparable, E comparable, C any]( replayArm(ctx, sched, nil, effects, mirror) } case rec.Tick: - mirrorTick(mirror, sched, sched.Tick(ctx)) + var mark int + if mirror != nil { + mark = mirror.clock.mark() + } + mirrorTick(mirror, sched, sched.Tick(ctx), mark) } // 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. @@ -1969,14 +1983,25 @@ func (m *armMirror) arm(effects []state.Effect) { // mirrorTick arms in m any timer a replayed tick's chained transition scheduled, at the // tick's last read, as the live Tick does, then drops the timers the tick fired: the ones // sched no longer holds. -func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Scheduler[S, E, C], results []state.FireResult[S]) { +func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Scheduler[S, E, C], results []state.FireResult[S], mark int) { if m == nil { return } now := m.clock.lastRead() for i := range results { - mirrorArmed(m.armed, results[i].Effects, now) + at, ok := m.clock.readingAt(mark + tickArmRead(i)) + if !ok { + at = now + } + mirrorArmed(m.armed, results[i].Effects, at) m.forget(results[i].Effects) } dropUnscheduled(m.armed, sched) } + +// tickArmRead is the index, past the tick's first read, of the clock read the +// scheduler armed the timers of the i-th timer a Tick fired at: Scheduler.Tick reads +// the clock to find each due timer, fires it, and reads again to absorb its effects, +// so the i-th fire's absorb read is the (2i+1)th. state pins that order +// (TestScheduler_Tick_ReadsTheClockOncePerCheckAndAbsorb). +func tickArmRead(i int) int { return 2*i + 1 } diff --git a/state/scheduler_clock_reads_test.go b/state/scheduler_clock_reads_test.go new file mode 100644 index 00000000..4659589b --- /dev/null +++ b/state/scheduler_clock_reads_test.go @@ -0,0 +1,72 @@ +package state_test + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/stablekernel/crucible/state" +) + +// readLog is a Clock that logs who read it: each read gets the next instant. +type readLog struct { + mu sync.Mutex + now time.Time + reads int +} + +func (c *readLog) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + c.reads++ + t := c.now + c.now = c.now.Add(time.Millisecond) + return t +} +func (c *readLog) After(time.Duration) <-chan time.Time { return make(chan time.Time) } + +// TestScheduler_Tick_ReadsTheClockOncePerCheckAndAbsorb pins the order of clock reads +// a Tick takes, which durable relies on to record a chained timer's deadline: one read +// to find each due timer, one to absorb that timer's effects, and a last read that +// finds none due. A chained timer is armed at its fire's absorb read. +func TestScheduler_Tick_ReadsTheClockOncePerCheckAndAbsorb(t *testing.T) { + m := state.ForgeFor[*trec]("reads"). + State("idle"). + State("a"). + State("b"). + State("c"). + Initial("idle"). + Transition("idle").On("go").GoTo("a"). + Transition("a").After(time.Second).On("toB").GoTo("b"). + Transition("b").After(time.Second).On("toC").GoTo("c"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := &readLog{now: base} + inst := m.Cast(&trec{}, state.WithInitialState("idle"), state.WithClock[string](clk)) + sch := state.NewScheduler(inst) + sch.Absorb(context.Background(), inst.Fire(context.Background(), "go").Effects) // arms a's timer at base+1s + clk.mu.Lock() + clk.now, clk.reads = base.Add(2*time.Second), 0 + clk.mu.Unlock() + // Reads, from 2s: 2.000 finds a's timer due, 2.001 absorbs its effects (arming b's + // timer at 3.001), 2.002 finds nothing due. + if fired := sch.Tick(context.Background()); len(fired) != 1 { + t.Fatalf("Tick fired %d timers, want a's", len(fired)) + } + if clk.reads != 3 { + t.Fatalf("Tick read the clock %d times, want 3: a check, the absorb, a last check", clk.reads) + } + clk.mu.Lock() + clk.now = base.Add(3*time.Second + 1*time.Millisecond - time.Nanosecond) + clk.mu.Unlock() + if fired := sch.Tick(context.Background()); len(fired) != 0 { + t.Fatal("b's timer fired before 3.001s: it wasn't armed at the absorb read") + } + clk.mu.Lock() + clk.now = base.Add(3*time.Second + time.Millisecond) + clk.mu.Unlock() + if fired := sch.Tick(context.Background()); len(fired) != 1 { + t.Fatal("b's timer didn't fire at 3.001s, the absorb read plus its delay") + } +} From 9a8c110c0ccae3911022a9e2502c81038f7d0db5 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Sun, 15 Nov 2026 23:32:25 -0700 Subject: [PATCH 28/38] fix(state): escalate an invoked actor's failure when it declared no onError An InvokeActor actor with no WithInvokeOnError fired the zero event at the parent when it couldn't start or failed after running, and a wildcard, a forbid or a transition on that event could take it as a declared onError. Durable then counted the spawn as caught and never retried it. The actor system now reads SpawnActor.NoOnError and escalates, as it does for a Spawn with no onError, firing nothing; durable retries such a spawn at Recover. ParentFire.NoOnError, which no Fire could set any more, is removed. Tick and its replay now fail when a fired timer's arming read is missing, instead of falling back to another read, so a change to the scheduler's order of reads surfaces. Two comments describing the old deadline rule are corrected. A parent Fire an actor drove doesn't have its domain effects dispatched; its test is skipped for #235. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 4 -- durable/actor_fire_effects_test.go | 47 ++++++++++++ durable/chained_deadline_internal_test.go | 21 ++++++ durable/clock.go | 11 --- durable/runner.go | 88 +++++++++++++---------- durable/spawn_zero_event_test.go | 42 ++++++++--- state/CHANGELOG.md | 19 ++--- state/actor.go | 8 +-- state/actor_invoke_undeclared_test.go | 60 ++++++++++------ state/actor_system.go | 15 ++-- state/options.go | 4 +- 11 files changed, 216 insertions(+), 103 deletions(-) create mode 100644 durable/actor_fire_effects_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 16bede24..d9b613f6 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -148,10 +148,6 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. persisted the later deadline, so after `Recover` the timer fired late, and the drift grew along an `after` chain. `Tick` and its replay now take each fired timer's absorb read, and `state` pins the order of reads a `Tick` takes. -- **A spawn whose zero-event onError applied isn't retried.** A spawn that failed with no - onError declared counted as uncaught even when the parent handled the zero event it - routes, so `Recover` ran the behavior again. An onError Fire that applied now always - counts as caught. - **A failed checkpoint no longer makes the next step conflict.** `Tick`, `RunService` and `DeliverToActor` now advance the next step as soon as the append lands. - **A deferred checkpoint survives an unrelated caller's cancel.** A checkpoint that diff --git a/durable/actor_fire_effects_test.go b/durable/actor_fire_effects_test.go new file mode 100644 index 00000000..d9e4612b --- /dev/null +++ b/durable/actor_fire_effects_test.go @@ -0,0 +1,47 @@ +package durable_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestFire_DispatchesTheEffectsOfAParentFireAnActorDrove pins that a domain effect a +// parent Fire emits, where an actor drove that Fire, is dispatched like the event +// Fire's own: here a failed spawn's onError transition emits a notify. +func TestFire_DispatchesTheEffectsOfAParentFireAnActorDrove(t *testing.T) { + t.Skip("a parent Fire an actor drove has its timers and services armed, but its domain effects aren't dispatched; #235 fixes it") + ctx := context.Background() + type cx struct{} + m := state.ForgeFor[cx]("actorEffects"). + Action("notify", func(state.ActionCtx[cx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + Actor("child"). + State("idle"). + State("spawning").InvokeActor("child", state.WithInvokeOnError("spawnFailed")). + State("failed"). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed").Do("notify"). + Quench() + rec := newEffectRecorder() + h, err := durable.NewRunner(m, durable.NewMemStore(), + durable.WithEffectHandler[string, string, cx](rec.handler()), + durable.WithActorPalette[string, string, cx](map[string]state.ActorBehavior{"child": failingSpawn(nil)}), + ).Start(ctx, "actor-effects", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + if got := h.Instance().Current(); got != "failed" { + t.Fatalf("state = %q, want failed by the onError", got) + } + if got := len(rec.values); got != 1 { + t.Fatalf("dispatched %d effects, want the onError transition's notify", got) + } +} diff --git a/durable/chained_deadline_internal_test.go b/durable/chained_deadline_internal_test.go index 65c15e20..58ce54ab 100644 --- a/durable/chained_deadline_internal_test.go +++ b/durable/chained_deadline_internal_test.go @@ -157,3 +157,24 @@ func TestTick_RecordsEachChainedDeadlineInATwoTimerTick(t *testing.T) { } } } + +// TestTickArmReads_FailsOnAMissingRead pins that Tick and its replay fail, rather than +// fall back to another read, when a fired timer's arming read is missing: the +// scheduler's order of reads changed, and any other deadline would be wrong. +func TestTickArmReads_FailsOnAMissingRead(t *testing.T) { + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + reads := []time.Time{base, base.Add(time.Millisecond), base.Add(2 * time.Millisecond)} + reading := func(i int) (time.Time, bool) { + if i < 0 || i >= len(reads) { + return time.Time{}, false + } + return reads[i], true + } + got, err := tickArmReads(reading, 0, 1) + if err != nil || len(got) != 1 || !got[0].Equal(reads[1]) { + t.Fatalf("one fired timer = %v, %v; want the absorb read %v", got, err, reads[1]) + } + if _, err := tickArmReads(reading, 0, 2); err == nil { + t.Fatal("two fired timers with three reads: want an error for the second timer's missing arming read") + } +} diff --git a/durable/clock.go b/durable/clock.go index 5f37899c..9cc1c451 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -110,17 +110,6 @@ func (c *recordingClock) armReadingAt(i int) (time.Time, bool) { return time.Unix(0, (*c.buf)[i].ClockUnixNano).UTC(), true } -// lastReadingSince returns the last clock reading recorded at or past index i, ok false -// when none was. Taken under the clock mutex, like armReadingAt. -func (c *recordingClock) lastReadingSince(i int) (time.Time, bool) { - c.mu.Lock() - defer c.mu.Unlock() - if i < 0 || i >= len(*c.buf) { - return time.Time{}, false - } - return time.Unix(0, (*c.buf)[len(*c.buf)-1].ClockUnixNano).UTC(), true -} - // replayClock returns recorded clock readings in order instead of reading any // real clock, so a recovered instance's scheduler re-derives identical timer // deadlines without consulting the wall clock. It is the inverse of diff --git a/durable/runner.go b/durable/runner.go index cda348cb..d6680590 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -431,10 +431,10 @@ func (h *Handle[S, E, C]) armNow(before int) time.Time { } // armTimersFrom mirrors the ScheduleAfter/CancelScheduled effects a chained timer -// transition emitted into the Handle's timer table at the tick instant now, so a -// timer a fired transition re-armed (the next link in an `after` chain) is tracked -// for the next checkpoint. It is the Tick-side analog of absorbTimers, using the -// tick's last recorded read rather than reading the clock again. +// transition emitted into the Handle's timer table at now, the read the scheduler armed +// them at (tickArmRead), so a timer a fired transition re-armed (the next link in an +// `after` chain) is tracked for the next checkpoint. It is the Tick-side analog of +// absorbTimers, reading no clock itself. func (h *Handle[S, E, C]) armTimersFrom(effects []state.Effect, now time.Time) { for _, eff := range effects { switch e := eff.(type) { @@ -719,14 +719,13 @@ func (p *parentFires[S]) inspect(ev state.InspectionEvent) { func (p *parentFires[S]) note(pf state.ParentFire[S]) { p.mu.Lock() p.fires = append(p.fires, pf) - // A spawn whose onError Fire applied is handled: the journal holds it, and a retry - // would run the behavior and apply it again. That holds for the zero event a spawn - // with no onError declared routes, when the parent handles it. A declared onError - // refused for a reason other than a context ending, such as a failing guard, is - // handled too: the journal holds the refusal. One a context's ending refused isn't: - // the step that drove it recorded nothing. Nor is a refused zero event (NoOnError): - // nothing caught the failure, so a retry is right. - if pf.SpawnFailed && (pf.Result.Err == nil || (!pf.NoOnError && !isContextErr(pf.Result.Err))) { + // A failed spawn routes an onError only when one was declared; with none, the system + // escalates and no Fire is noted, so the spawn stays unstarted and Recover retries it. + // A spawn whose onError applied, or was refused for a reason other than a context + // ending, such as a failing guard, is handled: the journal holds the onError or its + // refusal, and a retry would run the behavior again. One a context's ending refused + // isn't: the step that drove it recorded nothing. + if pf.SpawnFailed && (pf.Result.Err == nil || !isContextErr(pf.Result.Err)) { if p.failed == nil { p.failed = map[string]bool{} } @@ -994,16 +993,12 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro // earlier Start's or Recover's spawns, recorded with this step. mark := h.recClock.markBuf() results := h.sched.Tick(h.stepContext(ctx)) - now, haveNow := h.recClock.lastReadingSince(mark) // Each fired timer's chained timers were armed at its absorb read (tickArmRead); - // take those reads now, before the Record drains the buffer. - armAt := make([]time.Time, len(results)) - for i := range results { - at, ok := h.recClock.armReadingAt(mark + tickArmRead(i)) - if !ok { - at = now - } - armAt[i] = at + // take those reads now, before the Record drains the buffer. A missing one means the + // scheduler's order of reads changed, and any deadline taken would be wrong. + armAt, err := tickArmReads(h.recClock.armReadingAt, mark, len(results)) + if err != nil { + return results, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, err)) } // 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 @@ -1021,11 +1016,11 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro // after the tick persists exactly the still-pending deadlines. A chained timer's // deadline counts from the read the scheduler armed it at (tickArmRead), as // replay's does. - if haveNow { - for i := range results { - h.armTimersFrom(results[i].Effects, armAt[i]) - forgetSettled(h.settled, results[i].Effects) - } + for i := range results { + h.armTimersFrom(results[i].Effects, armAt[i]) + forgetSettled(h.settled, results[i].Effects) + } + if len(results) > 0 { h.dropFiredTimers() } // A tick that read no clock and fired nothing records nothing: there is no @@ -1876,7 +1871,9 @@ func replayRecord[S comparable, E comparable, C any]( if mirror != nil { mark = mirror.clock.mark() } - mirrorTick(mirror, sched, sched.Tick(ctx), mark) + if err := mirrorTick(mirror, sched, sched.Tick(ctx), mark); err != nil { + return out, fmt.Errorf("at step %d: %w", rec.Step, err) + } } // 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. @@ -1981,22 +1978,23 @@ func (m *armMirror) arm(effects []state.Effect) { } // mirrorTick arms in m any timer a replayed tick's chained transition scheduled, at the -// tick's last read, as the live Tick does, then drops the timers the tick fired: the ones -// sched no longer holds. -func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Scheduler[S, E, C], results []state.FireResult[S], mark int) { +// read the scheduler armed it at (tickArmRead), as the live Tick does, then drops the +// timers the tick fired: the ones sched no longer holds. A missing read means the +// journal and the scheduler's order of reads disagree. +func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Scheduler[S, E, C], results []state.FireResult[S], mark int) error { if m == nil { - return + return nil + } + armAt, err := tickArmReads(m.clock.readingAt, mark, len(results)) + if err != nil { + return err } - now := m.clock.lastRead() for i := range results { - at, ok := m.clock.readingAt(mark + tickArmRead(i)) - if !ok { - at = now - } - mirrorArmed(m.armed, results[i].Effects, at) + mirrorArmed(m.armed, results[i].Effects, armAt[i]) m.forget(results[i].Effects) } dropUnscheduled(m.armed, sched) + return nil } // tickArmRead is the index, past the tick's first read, of the clock read the @@ -2005,3 +2003,19 @@ func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Sc // so the i-th fire's absorb read is the (2i+1)th. state pins that order // (TestScheduler_Tick_ReadsTheClockOncePerCheckAndAbsorb). func tickArmRead(i int) int { return 2*i + 1 } + +// tickArmReads returns, for each of the n timers a Tick fired, the clock read the +// scheduler armed its chained timers at, from the reads at index mark on, as +// reading reports them. It fails when one is missing: the scheduler's order of reads +// changed, and a deadline taken from any other read would be wrong. +func tickArmReads(reading func(int) (time.Time, bool), mark, n int) ([]time.Time, error) { + out := make([]time.Time, n) + for i := range out { + at, ok := reading(mark + tickArmRead(i)) + if !ok { + return nil, fmt.Errorf("no clock read for fired timer %d's arming", i) + } + out[i] = at + } + return out, nil +} diff --git a/durable/spawn_zero_event_test.go b/durable/spawn_zero_event_test.go index 69b27405..84302441 100644 --- a/durable/spawn_zero_event_test.go +++ b/durable/spawn_zero_event_test.go @@ -9,10 +9,11 @@ import ( "github.com/stablekernel/crucible/state" ) -// TestRecover_DoesNotReapplyAnAppliedZeroEventOnError pins a failed spawn with no -// onError declared whose zero event the parent handles: the zero event applied live, -// and the journal holds it, so Recover must not retry the spawn and apply it again. -func TestRecover_DoesNotReapplyAnAppliedZeroEventOnError(t *testing.T) { +// TestRecover_RetriesANoOnErrorSpawnEvenWhenTheZeroEventHasATransition pins that a +// failed spawn with no onError declared escalates rather than firing the zero event, so +// a transition the parent declares on that event never runs, live or after Recover, +// and Recover retries the spawn: nothing declared for the failure caught it. +func TestRecover_RetriesANoOnErrorSpawnEvenWhenTheZeroEventHasATransition(t *testing.T) { ctx := context.Background() m := state.ForgeFor[stepCtx]("zeroOnError"). Reducer("note", func(in state.AssignCtx[stepCtx]) stepCtx { @@ -46,14 +47,39 @@ func TestRecover_DoesNotReapplyAnAppliedZeroEventOnError(t *testing.T) { t.Fatalf("Fire(start): %v", err) } live := fmt.Sprint(h.Instance().Entity().Notes) - if live != "[caught]" { - t.Fatalf("live notes = %s, want the zero event to apply once", live) + if live != "[]" { + t.Fatalf("live notes = %s, want none: the failure escalates, firing no zero event", live) } recovered, err := durable.Recover(ctx, m, store, id, opts...) if err != nil { t.Fatalf("Recover: %v", err) } - if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != live || calls != 1 { - t.Fatalf("recovered notes = %s after %d behavior runs, want the live %s and one run", got, calls, live) + if got := fmt.Sprint(recovered.Instance().Entity().Notes); got != live || calls != 2 { + t.Fatalf("recovered notes = %s after %d behavior runs, want the live %s and the retry's second run", got, calls, live) + } +} + +// TestRecover_RetriesANoOnErrorSpawnAWildcardSwallowed pins that a spawn with no onError +// declared is retried at Recover when the parent's state swallows its zero event with a +// catch-all or a forbid: nothing declared for the failure caught it. +func TestRecover_RetriesANoOnErrorSpawnAWildcardSwallowed(t *testing.T) { + for _, how := range []string{"forbid any", "on any"} { + t.Run(how, func(t *testing.T) { + b := state.ForgeFor[stepCtx]("wildcard"). + Actor("child"). + State("idle"). + State("spawning").InvokeActor("child"). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning") + if how == "forbid any" { + b = b.State("spawning").ForbidAny() + } else { + b = b.Transition("spawning").OnAny().GoTo("spawning") + } + m := b.Quench() + if got := spawnRuleCalls(t, m); got != 2 { + t.Fatalf("behavior ran %d times, want Recover to retry it once", got) + } + }) } } diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 1763fc8a..aaf85e21 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -19,14 +19,11 @@ counts as an additive (minor) versus breaking (major) change. Use the the onError of a spawn that couldn't start), so a host that records a delivery or spawn can tell a parent transition refused because its context ended from one that applied, and which Fire carried the actor's output. It's additive, within v1.1.0. -- **`SpawnActor.NoOnError` and `ParentFire.NoOnError`** report that an invoked actor - declared no onError. Such an actor's `OnError` holds the zero event, which the system - still fires at the parent when the actor can't start, as before, so its refusal looks - like a declared onError the parent refused. The flags tell them apart without - matching the refusal's reason. An onError that is itself the zero event, such as the - first constant of an `iota` enum, counts as declared when the machine was built with - `WithInvokeOnError`; an invocation loaded from JSON counts one as declared only when - it isn't the zero event. It's additive, within v1.1.0. +- **`SpawnActor.NoOnError`** reports that an invoked actor declared no onError, so its + `OnError` holds only the zero event. An onError that is itself the zero event, such as + the first constant of an `iota` enum, counts as declared when the machine was built + with `WithInvokeOnError`; an invocation loaded from JSON counts one as declared only + when it isn't the zero event. It's additive, within v1.1.0. - **`ActorSystem.AbsorbRespawn`** is `Absorb` for actors a host spawns again after rebuilding the parent from a record that already holds every parent Fire their earlier start drove: an actor it spawns starts as under `Absorb`, but its start @@ -69,6 +66,12 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Fixed +- **An invoked actor with no onError escalates its failure.** When an `InvokeActor` + actor with no `WithInvokeOnError` couldn't start, or failed after it ran, the actor + system fired the zero event at the parent, which a wildcard or a transition on that + event could take as if an onError had been declared. It now escalates, as a `Spawn` + with no onError always has (the G3 default), and fires nothing. A machine that relied + on that zero-event Fire changes behavior. - **`StartEffects` includes a compound state's invokes.** It looked only at the active leaves, so a service or actor declared on a compound state wasn't started while one of its children was active: not at a durable `Start` or `Recover`, and not for a child diff --git a/state/actor.go b/state/actor.go index f9ff0919..268dc473 100644 --- a/state/actor.go +++ b/state/actor.go @@ -87,10 +87,10 @@ type SpawnActor struct { // under in the ActorSystem (its systemId), so a sibling can address it // by a well-known name rather than by ref. Empty when unset. SystemID string `json:"systemId,omitempty"` - // NoOnError reports that an invoked actor declared no onError, so OnError holds the - // zero event, which the system still fires at the parent when the actor can't start. - // A host that must tell a refused onError from an absent one reads it. A dynamic - // spawn with no onError leaves OnError nil instead, and escalates. + // NoOnError reports that an invoked actor declared no onError, so OnError holds only + // the zero event. The actor system then escalates the actor's failure, to start or + // after it ran, as it does for a dynamic spawn with no onError, which leaves OnError + // nil, rather than firing the zero event at the parent. NoOnError bool `json:"noOnError,omitempty"` } diff --git a/state/actor_invoke_undeclared_test.go b/state/actor_invoke_undeclared_test.go index f4d72a57..1c5bbe38 100644 --- a/state/actor_invoke_undeclared_test.go +++ b/state/actor_invoke_undeclared_test.go @@ -62,29 +62,45 @@ func TestInvokeActor_ZeroValueOnError_IsDeclared(t *testing.T) { } } -// TestInvokeActor_NoOnError_ParentFireReportsIt pins that the parent Fire routing a -// failed spawn's onError reports NoOnError as its SpawnActor did, while the zero event -// still fires at the parent, as v1 documents. -func TestInvokeActor_NoOnError_ParentFireReportsIt(t *testing.T) { +// TestInvokeActor_NoOnError_FailuresEscalate pins that an invoked actor with no onError +// declared escalates its failure, to start or after it ran, as a spawned actor with none +// does (G3), and fires nothing at the parent; one with an onError routes it. +func TestInvokeActor_NoOnError_FailuresEscalate(t *testing.T) { + ctx := context.Background() for _, declared := range []bool{false, true} { - var opts []state.InvokeOption - if declared { - opts = append(opts, state.WithInvokeOnError("failed")) - } - parent := invokeParent(opts...).Cast(&trec{}, state.WithInitialState("idle")) - var fires []state.ParentFire[string] - sys := state.NewActorSystem(parent). - Register("child", func(map[string]any) (state.ActorInstance, error) { - return nil, errors.New("the child can't start") - }). - WithParentFireObserver(func(pf state.ParentFire[string]) { fires = append(fires, pf) }) - ctx := context.Background() - sys.Absorb(ctx, parent.Fire(ctx, "start").Effects) - if len(fires) != 1 || !fires[0].SpawnFailed { - t.Fatalf("declared=%v: parent Fires = %+v, want the failed spawn's onError", declared, fires) - } - if fires[0].NoOnError == declared { - t.Fatalf("declared=%v: ParentFire.NoOnError = %v", declared, fires[0].NoOnError) + for _, when := range []string{"at spawn", "after it ran"} { + var opts []state.InvokeOption + if declared { + opts = append(opts, state.WithInvokeOnError("failed")) + } + parent := invokeParent(opts...).Cast(&trec{}, state.WithInitialState("idle")) + var fires []state.ParentFire[string] + cause := errors.New("the child failed") + sys := state.NewActorSystem(parent). + WithParentFireObserver(func(pf state.ParentFire[string]) { fires = append(fires, pf) }) + if when == "at spawn" { + sys.Register("child", func(map[string]any) (state.ActorInstance, error) { return nil, cause }) + } else { + sys.Register("child", childBehavior()) + } + sys.Absorb(ctx, parent.Fire(ctx, "start").Effects) + if when == "after it ran" { + ids := sys.IDs() + if len(ids) != 1 { + t.Fatalf("declared=%v %s: running %v, want the child", declared, when, ids) + } + sys.SettleError(ctx, ids[0], cause) + } + esc := sys.LastEscalation() + if declared { + if len(fires) != 1 || esc != nil { + t.Fatalf("declared=%v %s: parent Fires %d, escalation %v; want the onError routed, no escalation", declared, when, len(fires), esc) + } + continue + } + if len(fires) != 0 || esc == nil || !errors.Is(esc, cause) { + t.Fatalf("declared=%v %s: parent Fires %d, escalation %v; want no Fire and the failure escalated", declared, when, len(fires), esc) + } } } } diff --git a/state/actor_system.go b/state/actor_system.go index 73e12ff4..a1d19629 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -446,7 +446,9 @@ func (s *ActorSystem[S, E, C]) spawn(ctx context.Context, e SpawnActor) { ra.onDone = d ra.hasDone = true } - if er, ok := e.OnError.(E); ok { + // An invoked actor that declared no onError carries the zero event; its failure + // escalates, as a spawned actor's with none does (G3). + if er, ok := e.OnError.(E); ok && !e.NoOnError { ra.onError = er ra.hasError = true } @@ -481,7 +483,9 @@ func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err return } ev, ok := e.OnError.(E) - if !ok { + // An invoked actor with no onError declared carries the zero event in OnError; it + // escalates, as a spawn with none does (G3), rather than firing that event. + if !ok || e.NoOnError { s.escalate(ctx, &runningActor[E]{ref: ActorRef{ID: e.ID, SystemID: e.SystemID, Src: e.Src.Name}}, "", err) return } @@ -490,7 +494,7 @@ func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err defer s.setQuiet(prev) } res := s.parent.Fire(ctx, ev) - s.noteParentFire(ParentFire[S]{Result: res, ActorID: e.ID, SpawnFailed: true, NoOnError: e.NoOnError}) + s.noteParentFire(ParentFire[S]{Result: res, ActorID: e.ID, SpawnFailed: true}) s.Absorb(ctx, res.Effects) } @@ -918,11 +922,6 @@ type ParentFire[S comparable] struct { // SpawnFailed reports that the Fire routed the onError of a spawn that couldn't // start (an unbound Src, or a behavior that returned an error). SpawnFailed bool - // NoOnError reports, with SpawnFailed, that the spawn declared no onError: the Fire - // carried the zero event an invoked actor with no WithInvokeOnError routes (see - // SpawnActor.NoOnError), so its refusal says nothing was declared to catch the - // failure, not that a declared onError was refused. - NoOnError bool // Settle reports that the Fire routed a settled actor's onDone or onError, which // carried the actor's outcome as its event data (WithEventData): Err for an onError, // Output for an onDone. A message the actor sent the parent, or the onError of a diff --git a/state/options.go b/state/options.go index 74d01403..e4d22288 100644 --- a/state/options.go +++ b/state/options.go @@ -105,7 +105,9 @@ func WithInvokeOnDone[E comparable](onDone E) InvokeOption { // WithInvokeOnError sets the event the host re-fires through Fire when an invoked // service fails (or, for InvokeActor, when the child machine fails), routing the // error through an ordinary transition from the owning state. Omitting it leaves -// the invocation's OnError at the zero event. It mirrors WithSpawnOnError. +// the invocation's OnError at the zero event; for InvokeActor, the child's failure then +// escalates, as a Spawn with no onError does, and no event is fired. It mirrors +// WithSpawnOnError. func WithInvokeOnError[E comparable](onError E) InvokeOption { return func(c *invokeConfig) { c.onError = onError From c400913ea994399f5ad8ed9e678502ed8fbd6d61 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Sun, 15 Nov 2026 23:55:15 -0700 Subject: [PATCH 29/38] fix(durable): take a chained timer's deadline from the scheduler Working the deadline out from the order of the Tick's clock reads breaks when a fired transition reads the instance's clock itself: the extra read moves the index, and the recorded deadline silently differs from the scheduler's. state's Scheduler now reports a pending timer's deadline (Scheduler.Due, additive), and Tick and its replay take each chained timer's deadline from it. The read-order helpers go. Tests: Scheduler.Due; a chained deadline when the fired transition reads the clock; an uncomparable event in a JSON-loaded onError doesn't panic declaresOnError. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 5 +- durable/chained_deadline_internal_test.go | 59 ++++++++++---- durable/clock.go | 19 ----- durable/runner.go | 96 +++++++---------------- state/CHANGELOG.md | 4 + state/driver.go | 11 +++ state/invoke_declares_internal_test.go | 23 ++++++ state/scheduler_clock_reads_test.go | 72 ----------------- state/scheduler_test.go | 31 ++++++++ 9 files changed, 143 insertions(+), 177 deletions(-) create mode 100644 state/invoke_declares_internal_test.go delete mode 100644 state/scheduler_clock_reads_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index d9b613f6..5e6e7044 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -146,8 +146,9 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. the deadline of a timer its fired transition chained from the tick's last clock read, which is later than the read the scheduler armed it at. With a real clock, a checkpoint persisted the later deadline, so after `Recover` the timer fired late, and the drift - grew along an `after` chain. `Tick` and its replay now take each fired timer's absorb - read, and `state` pins the order of reads a `Tick` takes. + grew along an `after` chain. `Tick` and its replay now take each chained timer's + deadline from the scheduler, with `state`'s new `Scheduler.Due`, so a fired + transition that reads the clock itself doesn't move it. - **A failed checkpoint no longer makes the next step conflict.** `Tick`, `RunService` and `DeliverToActor` now advance the next step as soon as the append lands. - **A deferred checkpoint survives an unrelated caller's cancel.** A checkpoint that diff --git a/durable/chained_deadline_internal_test.go b/durable/chained_deadline_internal_test.go index 58ce54ab..06c62739 100644 --- a/durable/chained_deadline_internal_test.go +++ b/durable/chained_deadline_internal_test.go @@ -158,23 +158,52 @@ func TestTick_RecordsEachChainedDeadlineInATwoTimerTick(t *testing.T) { } } -// TestTickArmReads_FailsOnAMissingRead pins that Tick and its replay fail, rather than -// fall back to another read, when a fired timer's arming read is missing: the -// scheduler's order of reads changed, and any other deadline would be wrong. -func TestTickArmReads_FailsOnAMissingRead(t *testing.T) { +// TestTick_AChainedDeadlineHoldsWhenAFiredTransitionReadsTheClock pins that the +// recorded deadline of a chained timer is still the scheduler's when the fired +// transition's own action reads the instance's clock, adding a read to the Tick. +func TestTick_AChainedDeadlineHoldsWhenAFiredTransitionReadsTheClock(t *testing.T) { + ctx := context.Background() + type cx struct{} + var h *Handle[string, string, cx] + m := state.ForgeFor[cx]("readingAction"). + Action("look", func(state.ActionCtx[cx]) (state.Effect, error) { + _ = h.inst.Clock().Now() + return nil, nil + }). + State("idle"). + State("a"). + State("b"). + State("c"). + Initial("idle"). + Transition("idle").On("go").GoTo("a"). + Transition("a").After(time.Second).On("toB").GoTo("b").Do("look"). + Transition("b").After(time.Second).On("toC").GoTo("c"). + Quench() base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - reads := []time.Time{base, base.Add(time.Millisecond), base.Add(2 * time.Millisecond)} - reading := func(i int) (time.Time, bool) { - if i < 0 || i >= len(reads) { - return time.Time{}, false - } - return reads[i], true + clk := &steppingClock{now: base} + var err error + h, err = NewRunner(m, NewMemStore(), WithRunnerClock[string, string, cx](clk)). + Start(ctx, "reading-action", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) } - got, err := tickArmReads(reading, 0, 1) - if err != nil || len(got) != 1 || !got[0].Equal(reads[1]) { - t.Fatalf("one fired timer = %v, %v; want the absorb read %v", got, err, reads[1]) + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + clk.set(base.Add(2*time.Second), true) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + var recorded time.Time + for _, pt := range h.timers { + recorded = pt.due + } + clk.set(recorded.Add(-time.Millisecond), false) + if fired := h.sched.Tick(ctx); len(fired) != 0 { + t.Fatalf("the scheduler fired b's timer before the recorded deadline %v", recorded) } - if _, err := tickArmReads(reading, 0, 2); err == nil { - t.Fatal("two fired timers with three reads: want an error for the second timer's missing arming read") + clk.set(recorded, false) + if fired := h.sched.Tick(ctx); len(fired) != 1 { + t.Fatalf("the scheduler didn't fire b's timer at the recorded deadline %v: it holds a different one", recorded) } } diff --git a/durable/clock.go b/durable/clock.go index 9cc1c451..7351d69f 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -148,25 +148,6 @@ func (c *replayClock) Now() time.Time { return c.last } -// mark returns how many recorded readings Now has handed out, so a caller can find -// the readings a step took after it. -func (c *replayClock) mark() int { - c.mu.Lock() - defer c.mu.Unlock() - return c.cursor -} - -// readingAt returns the recorded reading at index i, ok false when Now hasn't handed it -// out, or the recorded readings ran out before it. -func (c *replayClock) readingAt(i int) (time.Time, bool) { - c.mu.Lock() - defer c.mu.Unlock() - if i < 0 || i >= c.cursor || i >= len(c.readings) { - return time.Time{}, false - } - return time.Unix(0, c.readings[i]).UTC(), true -} - // lastRead returns the reading Now last returned: the instant a replayed timer arming // or tick computed its deadlines against. func (c *replayClock) lastRead() time.Time { diff --git a/durable/runner.go b/durable/runner.go index d6680590..a7083bf6 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -430,25 +430,6 @@ func (h *Handle[S, E, C]) armNow(before int) time.Time { return h.runner.cfg.clock.Now() } -// armTimersFrom mirrors the ScheduleAfter/CancelScheduled effects a chained timer -// transition emitted into the Handle's timer table at now, the read the scheduler armed -// them at (tickArmRead), so a timer a fired transition re-armed (the next link in an -// `after` chain) is tracked for the next checkpoint. It is the Tick-side analog of -// absorbTimers, reading no clock itself. -func (h *Handle[S, E, C]) armTimersFrom(effects []state.Effect, now time.Time) { - for _, eff := range effects { - switch e := eff.(type) { - case state.ScheduleAfter: - if h.timers == nil { - h.timers = map[string]pendingTimer{} - } - h.timers[e.ID] = pendingTimer{id: e.ID, due: now.Add(e.Delay), event: e.Event} - case state.CancelScheduled: - delete(h.timers, e.ID) - } - } -} - // dropFiredTimers removes from the Handle's timer table the timers a Tick fired, so // a checkpoint taken after the tick does not persist an already-fired timer. The // scheduler removes a due timer before re-firing it, so a timer the table holds that the @@ -989,17 +970,7 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro if err := h.refuse(ctx); err != nil { return nil, err } - // The tick's reads land past what the buffer holds now, which can include reads of an - // earlier Start's or Recover's spawns, recorded with this step. - mark := h.recClock.markBuf() results := h.sched.Tick(h.stepContext(ctx)) - // Each fired timer's chained timers were armed at its absorb read (tickArmRead); - // take those reads now, before the Record drains the buffer. A missing one means the - // scheduler's order of reads changed, and any deadline taken would be wrong. - armAt, err := tickArmReads(h.recClock.armReadingAt, mark, len(results)) - if err != nil { - return results, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, err)) - } // 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. @@ -1014,10 +985,12 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro // Reconcile the Handle's timer table with the tick: arm any timer a chained // transition scheduled, then drop the ones the tick fired, by id, so a checkpoint // after the tick persists exactly the still-pending deadlines. A chained timer's - // deadline counts from the read the scheduler armed it at (tickArmRead), as - // replay's does. + // deadline is the one the scheduler holds, as replay's is. for i := range results { - h.armTimersFrom(results[i].Effects, armAt[i]) + if h.timers == nil { + h.timers = map[string]pendingTimer{} + } + mirrorScheduled(h.timers, h.sched, results[i].Effects) forgetSettled(h.settled, results[i].Effects) } if len(results) > 0 { @@ -1867,13 +1840,7 @@ func replayRecord[S comparable, E comparable, C any]( replayArm(ctx, sched, nil, effects, mirror) } case rec.Tick: - var mark int - if mirror != nil { - mark = mirror.clock.mark() - } - if err := mirrorTick(mirror, sched, sched.Tick(ctx), mark); err != nil { - return out, fmt.Errorf("at step %d: %w", rec.Step, err) - } + mirrorTick(mirror, sched, sched.Tick(ctx)) } // The rest are a delivery's parent Fires, or the ones a Fire's or settle's absorb // drove after it, such as a spawned actor's onError. @@ -1978,44 +1945,35 @@ func (m *armMirror) arm(effects []state.Effect) { } // mirrorTick arms in m any timer a replayed tick's chained transition scheduled, at the -// read the scheduler armed it at (tickArmRead), as the live Tick does, then drops the -// timers the tick fired: the ones sched no longer holds. A missing read means the -// journal and the scheduler's order of reads disagree. -func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Scheduler[S, E, C], results []state.FireResult[S], mark int) error { +// deadline the scheduler holds, as the live Tick does, then drops the timers the tick +// fired: the ones sched no longer holds. +func mirrorTick[S comparable, E comparable, C any](m *armMirror, sched *state.Scheduler[S, E, C], results []state.FireResult[S]) { if m == nil { - return nil - } - armAt, err := tickArmReads(m.clock.readingAt, mark, len(results)) - if err != nil { - return err + return } for i := range results { - mirrorArmed(m.armed, results[i].Effects, armAt[i]) + mirrorScheduled(m.armed, sched, results[i].Effects) m.forget(results[i].Effects) } dropUnscheduled(m.armed, sched) - return nil } -// tickArmRead is the index, past the tick's first read, of the clock read the -// scheduler armed the timers of the i-th timer a Tick fired at: Scheduler.Tick reads -// the clock to find each due timer, fires it, and reads again to absorb its effects, -// so the i-th fire's absorb read is the (2i+1)th. state pins that order -// (TestScheduler_Tick_ReadsTheClockOncePerCheckAndAbsorb). -func tickArmRead(i int) int { return 2*i + 1 } - -// tickArmReads returns, for each of the n timers a Tick fired, the clock read the -// scheduler armed its chained timers at, from the reads at index mark on, as -// reading reports them. It fails when one is missing: the scheduler's order of reads -// changed, and a deadline taken from any other read would be wrong. -func tickArmReads(reading func(int) (time.Time, bool), mark, n int) ([]time.Time, error) { - out := make([]time.Time, n) - for i := range out { - at, ok := reading(mark + tickArmRead(i)) - if !ok { - return nil, fmt.Errorf("no clock read for fired timer %d's arming", i) +// mirrorScheduled folds a fired timer's ScheduleAfter and CancelScheduled effects into +// table, taking each scheduled timer's deadline from sched (Scheduler.Due), so the table +// holds what the scheduler armed whatever clock reads the tick and its transitions took. +// A timer scheduled and then fired or canceled within the tick isn't pending, and isn't +// kept. +func mirrorScheduled[S comparable, E comparable, C any](table map[string]pendingTimer, sched *state.Scheduler[S, E, C], effects []state.Effect) { + for _, eff := range effects { + switch e := eff.(type) { + case state.ScheduleAfter: + if due, ok := sched.Due(e.ID); ok { + table[e.ID] = pendingTimer{id: e.ID, due: due, event: e.Event} + } else { + delete(table, e.ID) + } + case state.CancelScheduled: + delete(table, e.ID) } - out[i] = at } - return out, nil } diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index aaf85e21..39cc6bb3 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -19,6 +19,10 @@ counts as an additive (minor) versus breaking (major) change. Use the the onError of a spawn that couldn't start), so a host that records a delivery or spawn can tell a parent transition refused because its context ended from one that applied, and which Fire carried the actor's output. It's additive, within v1.1.0. +- **`Scheduler.Due`** reports when a pending timer is due, so a host that keeps its own + record of armed timers' deadlines, as `durable` does for a checkpoint, reads the one + the scheduler holds rather than working it out from a clock read of its own. It's + additive, within v1.1.0. - **`SpawnActor.NoOnError`** reports that an invoked actor declared no onError, so its `OnError` holds only the zero event. An onError that is itself the zero event, such as the first constant of an `iota` enum, counts as declared when the machine was built diff --git a/state/driver.go b/state/driver.go index 52c7eebc..a4179eb5 100644 --- a/state/driver.go +++ b/state/driver.go @@ -105,6 +105,17 @@ func (s *Scheduler[S, E, C]) HasPending(id string) bool { return ok } +// Due reports when the pending timer id is due, and false when no timer is pending +// under id. A host that keeps its own record of armed timers' deadlines, as a durable +// runtime does for a checkpoint, reads it after Absorb or Tick, rather than working the +// deadline out from a clock reading of its own. +func (s *Scheduler[S, E, C]) Due(id string) (time.Time, bool) { + s.mu.Lock() + defer s.mu.Unlock() + p, ok := s.pending[id] + return p.due, ok +} + // Tick fires every timer whose due time is at or before the Scheduler clock's // current time, in due-time order (ties broken by id for determinism). Each due // timer is removed, then its delayed event is fired through the instance and the diff --git a/state/invoke_declares_internal_test.go b/state/invoke_declares_internal_test.go new file mode 100644 index 00000000..5772631f --- /dev/null +++ b/state/invoke_declares_internal_test.go @@ -0,0 +1,23 @@ +package state + +import "testing" + +// TestDeclaresOnError_NoPanicOnAnUncomparableEvent pins that declaresOnError, for an +// invocation loaded from JSON (no builder flag), doesn't panic when its event type is an +// interface holding an uncomparable value, as a JSON array decodes to, and reads such +// an onError as declared and the zero event as not. +func TestDeclaresOnError_NoPanicOnAnUncomparableEvent(t *testing.T) { + loaded := Invocation[string, any, int]{OnError: []any{1.0}} + if !loaded.declaresOnError() { + t.Fatal("an onError holding a JSON array reads as not declared") + } + if zero := (Invocation[string, any, int]{}); zero.declaresOnError() { + t.Fatal("a nil onError reads as declared") + } + if typed := (Invocation[string, int, int]{OnError: 0}); typed.declaresOnError() { + t.Fatal("a loaded int onError of 0 reads as declared") + } + if built := (Invocation[string, int, int]{OnError: 0, hasOnError: true}); !built.declaresOnError() { + t.Fatal("a built onError of 0 reads as not declared") + } +} diff --git a/state/scheduler_clock_reads_test.go b/state/scheduler_clock_reads_test.go deleted file mode 100644 index 4659589b..00000000 --- a/state/scheduler_clock_reads_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package state_test - -import ( - "context" - "sync" - "testing" - "time" - - "github.com/stablekernel/crucible/state" -) - -// readLog is a Clock that logs who read it: each read gets the next instant. -type readLog struct { - mu sync.Mutex - now time.Time - reads int -} - -func (c *readLog) Now() time.Time { - c.mu.Lock() - defer c.mu.Unlock() - c.reads++ - t := c.now - c.now = c.now.Add(time.Millisecond) - return t -} -func (c *readLog) After(time.Duration) <-chan time.Time { return make(chan time.Time) } - -// TestScheduler_Tick_ReadsTheClockOncePerCheckAndAbsorb pins the order of clock reads -// a Tick takes, which durable relies on to record a chained timer's deadline: one read -// to find each due timer, one to absorb that timer's effects, and a last read that -// finds none due. A chained timer is armed at its fire's absorb read. -func TestScheduler_Tick_ReadsTheClockOncePerCheckAndAbsorb(t *testing.T) { - m := state.ForgeFor[*trec]("reads"). - State("idle"). - State("a"). - State("b"). - State("c"). - Initial("idle"). - Transition("idle").On("go").GoTo("a"). - Transition("a").After(time.Second).On("toB").GoTo("b"). - Transition("b").After(time.Second).On("toC").GoTo("c"). - Quench() - base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - clk := &readLog{now: base} - inst := m.Cast(&trec{}, state.WithInitialState("idle"), state.WithClock[string](clk)) - sch := state.NewScheduler(inst) - sch.Absorb(context.Background(), inst.Fire(context.Background(), "go").Effects) // arms a's timer at base+1s - clk.mu.Lock() - clk.now, clk.reads = base.Add(2*time.Second), 0 - clk.mu.Unlock() - // Reads, from 2s: 2.000 finds a's timer due, 2.001 absorbs its effects (arming b's - // timer at 3.001), 2.002 finds nothing due. - if fired := sch.Tick(context.Background()); len(fired) != 1 { - t.Fatalf("Tick fired %d timers, want a's", len(fired)) - } - if clk.reads != 3 { - t.Fatalf("Tick read the clock %d times, want 3: a check, the absorb, a last check", clk.reads) - } - clk.mu.Lock() - clk.now = base.Add(3*time.Second + 1*time.Millisecond - time.Nanosecond) - clk.mu.Unlock() - if fired := sch.Tick(context.Background()); len(fired) != 0 { - t.Fatal("b's timer fired before 3.001s: it wasn't armed at the absorb read") - } - clk.mu.Lock() - clk.now = base.Add(3*time.Second + time.Millisecond) - clk.mu.Unlock() - if fired := sch.Tick(context.Background()); len(fired) != 1 { - t.Fatal("b's timer didn't fire at 3.001s, the absorb read plus its delay") - } -} diff --git a/state/scheduler_test.go b/state/scheduler_test.go index 2cc8c615..1892e1bd 100644 --- a/state/scheduler_test.go +++ b/state/scheduler_test.go @@ -249,3 +249,34 @@ func assertCancelEffect(t *testing.T, effects []state.Effect, id string) { } t.Fatalf("no CancelScheduled effect for id %q in %v", id, effects) } + +// TestScheduler_Due_ReportsAPendingTimersDeadline pins Due: the deadline Absorb armed a +// timer at, and false once it fired or for an unknown id. +func TestScheduler_Due_ReportsAPendingTimersDeadline(t *testing.T) { + m := state.ForgeFor[*trec]("due"). + State("idle"). + State("a"). + State("b"). + Initial("idle"). + Transition("idle").On("go").GoTo("a"). + Transition("a").After(5 * time.Second).On("toB").GoTo("b"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := state.NewFakeClock(base) + inst := m.Cast(&trec{}, state.WithInitialState("idle"), state.WithClock[string](clk)) + sch := state.NewScheduler(inst) + sch.Absorb(context.Background(), inst.Fire(context.Background(), "go").Effects) + id := state.ScheduleID("due", "a", 0) + due, ok := sch.Due(id) + if !ok || !due.Equal(base.Add(5*time.Second)) { + t.Fatalf("Due(%q) = %v, %v; want %v", id, due, ok, base.Add(5*time.Second)) + } + if _, ok := sch.Due("nope"); ok { + t.Fatal("Due of an unknown id reports a timer") + } + clk.Advance(5 * time.Second) + sch.Tick(context.Background()) + if _, ok := sch.Due(id); ok { + t.Fatal("Due still reports the timer after it fired") + } +} From 26985c30a21463af2e41f522c1c628f7d06e5751 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Mon, 16 Nov 2026 00:34:04 -0700 Subject: [PATCH 30/38] fix: scope AbsorbRespawn's quiet, keep a declared onError in the IR, fail on a lost Format - state: AbsorbRespawn's quiet rides the call chain that spawns each actor, rather than one flag for the whole system, so a delivery another goroutine makes while it runs is heard. It ends when AbsorbRespawn returns. - state: an Invocation writes the onError key only when one was declared and reads a present key as declared, so a zero-valued onError survives the JSON IR. IR written before this always has the key and keeps routing as it did. - durable: the Start baseline and checkpoints record the journal format, and replay fails on a Record whose format is lower, instead of silently replaying a Store that lost Record.Format as an older journal. - durable: the actor sets are reused while the configuration, the running actors and the step's spawns are unchanged. - durable: actor entries are decoded once on replay; actorBuf, the dropFiredTimers wrapper, the replayed struct and a redundant nil check are gone. Tests confirm each: a delivery during AbsorbRespawn is heard; a zero-valued onError survives JSON; Recover fails on a Store that drops Format; a step that touches no actor allocates about as much with actors as without. A host read of the instance clock mid-step is journaled but can't be replayed; its test is skipped pending an issue, as it isn't this PR's. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 7 ++ durable/actor.go | 55 +++++------- durable/actor_driven_drivers_test.go | 10 +++ durable/actor_sets_cost_test.go | 48 ++++++++++ durable/chained_deadline_internal_test.go | 94 +++++++++++++++++++ durable/checkpoint.go | 4 + durable/runner.go | 93 +++++++++++-------- durable/store_format_test.go | 47 ++++++++++ durable/timetravel.go | 6 +- state/CHANGELOG.md | 9 ++ state/actor_invoke_undeclared_test.go | 30 +++++++ state/actor_respawn_lift_test.go | 32 +++++++ state/actor_system.go | 105 +++++++++++----------- state/invoke.go | 43 +++++++-- 14 files changed, 447 insertions(+), 136 deletions(-) create mode 100644 durable/actor_sets_cost_test.go create mode 100644 durable/store_format_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 5e6e7044..58dfbec4 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -142,6 +142,13 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Fixed +- **`Recover` and `StateAt` fail when a Store loses `Record.Format`.** The Start baseline + and every checkpoint record the journal format too, and a Record after one with a lower + format fails replay, where it used to replay as an older journal's and silently skip + the timers and services an actor-driven Fire armed. +- **A step that touches no actor doesn't recompute the actor sets.** Each append rebuilt + the declared actors from every active state; it now reuses the last sets while the + configuration, the running actors and the step's spawns are unchanged. - **A chained timer's deadline is the one the scheduler armed it at.** A `Tick` recorded the deadline of a timer its fired transition chained from the tick's last clock read, which is later than the read the scheduler armed it at. With a real clock, a checkpoint diff --git a/durable/actor.go b/durable/actor.go index b7a3150e..6ad7d1fe 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -155,13 +155,10 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef if err != nil { return true, h.fail(fmt.Errorf("durable: recording actor %q result for %q: %w", ref.ID, h.id, err)) } - if h.actorBuf != nil { - *h.actorBuf = append(*h.actorBuf, entries...) - } step := h.nextStep // A parent Fire the delivery drove can arm a timer, which reads the clock. - rec := Record{Step: step, Entries: append(h.drainClock(), h.drainActors()...)} + rec := Record{Step: step, Entries: append(h.drainClock(), entries...)} if err := h.persistStep(ctx, step, &rec); err != nil { return true, err } @@ -185,19 +182,6 @@ func (h *Handle[S, E, C]) ActorRef(id string) (state.ActorRef, bool) { return h.actors.Ref(id) } -// drainActors returns and clears the actor transitions recorded since the last -// drain, so each persisted step carries exactly the transitions that resolved -// during it, in fire order. -func (h *Handle[S, E, C]) drainActors() []state.JournalEntry { - if h.actorBuf == nil || len(*h.actorBuf) == 0 { - return nil - } - out := make([]state.JournalEntry, len(*h.actorBuf)) - copy(out, *h.actorBuf) - *h.actorBuf = (*h.actorBuf)[:0] - return out -} - // recordParentFires builds the JournalActorMessage entries for the parent Fires an // actor system drove, in fire order, each under the actor it came from. before marks // Fires that ran before the step's own work. @@ -243,18 +227,24 @@ func actorEntry[S comparable](pf state.ParentFire[S], before bool) (state.Journa return state.JournalEntry{Kind: state.JournalActorMessage, CorrelationID: pf.ActorID, Payload: payload}, nil } -// splitActorEntries returns a Record's actor entries in recorded order, the ones that -// ran before the step's own work apart from the rest. -func splitActorEntries(rec *Record) (before, rest []state.JournalEntry, err error) { +// decodedActorEntry is a recorded actor entry with its payload decoded once. +type decodedActorEntry struct { + actorID string + mp actorMessagePayload +} + +// splitActorEntries decodes a Record's actor entries, in recorded order, and returns the +// ones that ran before the step's own work apart from the rest. +func splitActorEntries(rec *Record) (before, rest []decodedActorEntry, err error) { for _, e := range actorEntries(rec) { - var mp actorMessagePayload - if err := json.Unmarshal(e.Payload, &mp); err != nil { + d := decodedActorEntry{actorID: e.CorrelationID} + if err := json.Unmarshal(e.Payload, &d.mp); err != nil { return nil, nil, fmt.Errorf("durable: decoding recorded actor %q transition: %w", e.CorrelationID, err) } - if mp.Before { - before = append(before, e) + if d.mp.Before { + before = append(before, d) } else { - rest = append(rest, e) + rest = append(rest, d) } } return before, rest, nil @@ -269,11 +259,8 @@ func splitActorEntries(rec *Record) (before, rest []state.JournalEntry, err erro // arms the timers and services it declares, as the live run did. It reports an error // only when the recorded entry cannot be decoded or the re-fired transition fails (a // corrupt or mis-ordered journal). -func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry state.JournalEntry) ([]state.Effect, error) { - var mp actorMessagePayload - if err := json.Unmarshal(entry.Payload, &mp); err != nil { - return nil, fmt.Errorf("durable: decoding recorded actor %q transition: %w", entry.CorrelationID, err) - } +func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], entry decodedActorEntry) ([]state.Effect, error) { + mp := entry.mp // A Fire refused before the kernel saw it (middleware that denied it) has no event // to re-fire; replay is refused the same way. if mp.Refused && len(mp.Event) == 0 { @@ -281,13 +268,13 @@ func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *s } event, err := codec.Decode(mp.Event) if err != nil { - return nil, fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.CorrelationID, err) + return nil, fmt.Errorf("durable: decoding recorded actor %q event: %w", entry.actorID, err) } var res state.FireResult[S] if mp.HasData { data, derr := replayActorData(mp) if derr != nil { - return nil, fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.CorrelationID, derr) + return nil, fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.actorID, derr) } res = inst.Fire(ctx, event, state.WithEventData(data)) } else { @@ -299,9 +286,9 @@ func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *s case res.Err != nil && mp.Refused: return nil, nil // the live run was refused the same way case res.Err != nil: - return nil, fmt.Errorf("durable: replaying actor %q transition: %w", entry.CorrelationID, res.Err) + return nil, fmt.Errorf("durable: replaying actor %q transition: %w", entry.actorID, res.Err) case mp.Refused: - return nil, fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.CorrelationID) + return nil, fmt.Errorf("durable: replaying actor %q transition: it applied, but the live run's was refused", entry.actorID) } return res.Effects, nil } diff --git a/durable/actor_driven_drivers_test.go b/durable/actor_driven_drivers_test.go index 36f3e3c6..269d10f2 100644 --- a/durable/actor_driven_drivers_test.go +++ b/durable/actor_driven_drivers_test.go @@ -2,6 +2,7 @@ package durable_test import ( "context" + "encoding/json" "fmt" "testing" "time" @@ -394,6 +395,15 @@ func TestRecover_ReplaysAnOlderJournalsActorFireWithoutArming(t *testing.T) { t.Fatalf("journal holds %d Records, want the delivery, the leave and the tick", len(tail)) } older := durable.NewMemStore() + // An older version's baseline records no journal format. + var env map[string]json.RawMessage + if err = json.Unmarshal(baseline, &env); err != nil { + t.Fatalf("decoding the baseline: %v", err) + } + delete(env, "format") + if baseline, err = json.Marshal(env); err != nil { + t.Fatalf("encoding the baseline: %v", err) + } if err = older.Checkpoint(ctx, id, baseline, durable.BaselineStep); err != nil { t.Fatalf("Checkpoint: %v", err) } diff --git a/durable/actor_sets_cost_test.go b/durable/actor_sets_cost_test.go new file mode 100644 index 00000000..c9d55622 --- /dev/null +++ b/durable/actor_sets_cost_test.go @@ -0,0 +1,48 @@ +package durable_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestFire_AStepThatTouchesNoActorCostsLittleExtra pins that a machine declaring actors +// pays little extra on a step that touches no actor: a Fire that only moves within the +// state allocates about as much with an actor palette as without one. +func TestFire_AStepThatTouchesNoActorCostsLittleExtra(t *testing.T) { + ctx := context.Background() + allocs := func(withActors bool) float64 { + b := state.ForgeFor[stepCtx]("cost") + if withActors { + b = b.Actor("a").Actor("b").Actor("c") + } + b = b.State("working") + if withActors { + b = b.InvokeActor("a").InvokeActor("b").InvokeActor("c") + } + m := b.Initial("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + var opts []stepOption + if withActors { + beh := func(map[string]any) (state.ActorInstance, error) { return &reentryGreeter{sent: true}, nil } + opts = append(opts, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"a": beh, "b": beh, "c": beh})) + } + h, err := durable.NewRunner(m, durable.NewMemStore(), opts...).Start(ctx, "cost", stepCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + return testing.AllocsPerRun(50, func() { + if _, err := h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire: %v", err) + } + }) + } + without, with := allocs(false), allocs(true) + t.Logf("allocations per Fire: %.0f without actors, %.0f with three", without, with) + if with > without+10 { + t.Fatalf("a Fire that touches no actor allocates %.0f with three declared actors, %.0f without: the actor sets are recomputed every step", with, without) + } +} diff --git a/durable/chained_deadline_internal_test.go b/durable/chained_deadline_internal_test.go index 06c62739..8d311e66 100644 --- a/durable/chained_deadline_internal_test.go +++ b/durable/chained_deadline_internal_test.go @@ -207,3 +207,97 @@ func TestTick_AChainedDeadlineHoldsWhenAFiredTransitionReadsTheClock(t *testing. t.Fatalf("the scheduler didn't fire b's timer at the recorded deadline %v: it holds a different one", recorded) } } + +// TestFire_ADeadlineHoldsWhenTheTransitionReadsTheClock pins that a timer a Fire arms is +// recorded at the scheduler's deadline when the transition's action reads the instance +// clock first, live and after Recover's replay. +func TestFire_ADeadlineHoldsWhenTheTransitionReadsTheClock(t *testing.T) { + ctx := context.Background() + type cx struct{} + var h *Handle[string, string, cx] + look := func(state.ActionCtx[cx]) (state.Effect, error) { + if h != nil { + _ = h.inst.Clock().Now() + } + return nil, nil + } + m := state.ForgeFor[cx]("fireReads"). + Action("look", look). + State("idle"). + State("a"). + State("b"). + Initial("idle"). + Transition("idle").On("go").GoTo("a").Do("look"). + Transition("a").After(time.Second).On("toB").GoTo("b"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clk := &steppingClock{now: base, stepping: true} + store := NewMemStore() + var err error + h, err = NewRunner(m, store, WithRunnerClock[string, string, cx](clk)). + Start(ctx, "fire-reads", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + id := state.ScheduleID("fireReads", "a", 0) + want, ok := h.sched.Due(id) + if !ok { + t.Fatalf("no timer pending under %s", id) + } + if got := h.timers[id].due; !got.Equal(want) { + t.Fatalf("live recorded deadline %v, scheduler %v", got, want) + } +} + +// TestRecover_ReplaysAStepWhoseHostCodeReadTheInstanceClock pins what Recover does with +// a step whose host code read the Handle's instance clock: the read is journaled with +// the step's own, but Recover can't run that host read against the replay clock, so +// replay's reads shift by one and the timer comes back at another deadline. +func TestRecover_ReplaysAStepWhoseHostCodeReadTheInstanceClock(t *testing.T) { + t.Skip("a host read of Instance().Clock() during a step is journaled but can't be replayed; awaiting a ruling") + ctx := context.Background() + type cx struct{} + var h *Handle[string, string, cx] + look := func(state.ActionCtx[cx]) (state.Effect, error) { + if h != nil { + _ = h.inst.Clock().Now() + } + return nil, nil + } + m := state.ForgeFor[cx]("fireReads"). + Action("look", look). + State("idle"). + State("a"). + State("b"). + Initial("idle"). + Transition("idle").On("go").GoTo("a").Do("look"). + Transition("a").After(time.Second).On("toB").GoTo("b"). + Quench() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + store := NewMemStore() + var err error + h, err = NewRunner(m, store, WithRunnerClock[string, string, cx](&steppingClock{now: base, stepping: true})). + Start(ctx, "fire-reads", cx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + id := state.ScheduleID("fireReads", "a", 0) + want, _ := h.sched.Due(id) + h = nil + recovered, err := Recover(ctx, m, store, "fire-reads", WithRunnerClock[string, string, cx](&steppingClock{now: base.Add(time.Hour)})) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.timers[id].due; !got.Equal(want) { + t.Fatalf("recovered deadline %v, want the live %v", got, want) + } + if got, _ := recovered.sched.Due(id); !got.Equal(want) { + t.Fatalf("recovered scheduler holds %v, want the live %v", got, want) + } +} diff --git a/durable/checkpoint.go b/durable/checkpoint.go index 7377041e..1239204d 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -98,6 +98,10 @@ type checkpointEnvelope struct { // settled isn't one. None, as in a Start baseline or an older checkpoint, means // Recover starts every declared service. EndedServices []string `json:"endedServices,omitempty"` + // Format is the journal format of the version that wrote the checkpoint, as + // Record.Format is. Zero means a checkpoint from before this field. A Record after + // it with a lower Format means the Store lost the field, and replay fails. + Format int `json:"format,omitempty"` } // marshalCheckpoint adds the armed pending timers to env, which carries the marshaled diff --git a/durable/runner.go b/durable/runner.go index a7083bf6..56e1784a 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -144,8 +144,8 @@ type Handle[S comparable, E comparable, C any] struct { ended recordedSet // the ended actors the journal last recorded unstarted recordedSet // the unstarted actors the journal last recorded seen map[string]bool // declared actors seen running, so a stopped one counts as ended + sets actorSetsCache // the last actorSets result, reused while nothing it reads changed pending []state.ParentFire[S] // parent Fires Start's or Recover's spawns drove, journaled with the next step - actorBuf *[]state.JournalEntry // recording actor-transition accumulator, flushed per step actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step out outbox // what a step leaves behind once it releases the step lock @@ -430,16 +430,6 @@ func (h *Handle[S, E, C]) armNow(before int) time.Time { return h.runner.cfg.clock.Now() } -// dropFiredTimers removes from the Handle's timer table the timers a Tick fired, so -// a checkpoint taken after the tick does not persist an already-fired timer. The -// scheduler removes a due timer before re-firing it, so a timer the table holds that the -// scheduler no longer does fired, or a fired transition canceled it. That covers a timer -// that came due between the tick's clock reads, and a chained timer the tick armed and -// then fired. -func (h *Handle[S, E, C]) dropFiredTimers() { - dropUnscheduled(h.timers, h.sched) -} - // dropUnscheduled removes from timers each one sched no longer holds. func dropUnscheduled[S comparable, E comparable, C any](timers map[string]pendingTimer, sched *state.Scheduler[S, E, C]) { for id := range timers { @@ -535,7 +525,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt } // Wrap the baseline snapshot in a checkpoint envelope (no timers armed yet) so // every checkpoint a recover loads carries the same durable envelope shape. - baseEnv, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap}, nil) + baseEnv, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap, Format: journalFormat}, nil) if err != nil { return nil, fmt.Errorf("durable: marshaling start checkpoint envelope for %q: %w", id, err) } @@ -560,7 +550,6 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // transition a delivery drives for replay. A machine with no actor palette wired // spawns no actor and records no actor entries. A parent Fire a starting actor // drives arms its state's timers and services on the Handle's drivers. - actorBuf := make([]state.JournalEntry, 0) actors, actorFires := r.newActorSystem(inst) h := &Handle[S, E, C]{ runner: r, @@ -573,7 +562,6 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt svc: svc, svcBuf: &svcBuf, actors: actors, - actorBuf: &actorBuf, actorFires: actorFires, lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, @@ -706,7 +694,7 @@ func (p *parentFires[S]) note(pf state.ParentFire[S]) { // ending, such as a failing guard, is handled: the journal holds the onError or its // refusal, and a retry would run the behavior again. One a context's ending refused // isn't: the step that drove it recorded nothing. - if pf.SpawnFailed && (pf.Result.Err == nil || !isContextErr(pf.Result.Err)) { + if pf.SpawnFailed && !isContextErr(pf.Result.Err) { if p.failed == nil { p.failed = map[string]bool{} } @@ -994,7 +982,10 @@ func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], erro forgetSettled(h.settled, results[i].Effects) } if len(results) > 0 { - h.dropFiredTimers() + // Drop from the table the timers the tick fired, the ones the scheduler no longer + // holds: one that came due between the tick's reads, and a chained one it armed + // and fired, so a checkpoint after the tick doesn't persist a fired timer. + dropUnscheduled(h.timers, h.sched) } // A tick that read no clock and fired nothing records nothing: there is no // nondeterminism to journal and no step was produced. @@ -1119,6 +1110,7 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) EndedActors: ended, UnstartedActors: unstarted, EndedServices: h.endedServices(), + Format: journalFormat, }, h.timers) if err != nil { return fmt.Errorf("durable: marshaling checkpoint envelope at step %d for %q: %w", step, h.id, err) @@ -1178,6 +1170,17 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { } spawned, attempted, failed := h.actorFires.takeLifecycle() running := h.actors.IDs() + // The sets depend on the declared actors, so on the configuration, on which are + // running, and on this step's spawns. A step that changed none of them, as most + // steps that touch no actor don't, gets the last result back. + config := fmt.Sprint(h.inst.Configuration()) + if h.sets.valid && len(attempted) == 0 && len(spawned) == 0 && len(failed) == 0 && + config == h.sets.config && slices.Equal(running, h.sets.running) { + return h.sets.ended, h.sets.unstarted + } + defer func() { + h.sets = actorSetsCache{valid: true, config: config, running: running, ended: ended, unstarted: unstarted} + }() endedIDs, unstartedIDs := []string{}, []string{} for _, id := range declaredActors(h.inst.StartEffects()) { if slices.Contains(running, id) { @@ -1208,6 +1211,15 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { return &ActorSet{IDs: endedIDs}, &ActorSet{IDs: unstartedIDs} } +// actorSetsCache is the last result actorSets computed, with what it read: the +// configuration and the running actors. +type actorSetsCache struct { + valid bool + config string + running []string + ended, unstarted *ActorSet +} + // endedServices returns the invoked services the active states declare that settled // while the state that declares them stayed active, sorted. A declared service that // isn't in flight but never settled, such as one a Tick's timer entered, which a Tick @@ -1343,7 +1355,6 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // behavior. Spawning here would re-instantiate an actor the recorded run already // settled. The live actors at the resume point are armed once, after replay, // from the final configuration's StartEffects. - actorBuf := make([]state.JournalEntry, 0) actors, actorFires := r.newActorSystem(inst) // armed mirrors the scheduler's pending timers re-established by tail replay, @@ -1378,7 +1389,10 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // The mirror tracks the still-pending timers in armed as replay arms, cancels and // fires them, with deadlines drawn from the recorded clock reads, not the live // wall clock. - did, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, mirror, armsActorFires(rec)) + if err := checkFormat(env.Format, rec); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } + fired, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, mirror, armsActorFires(rec)) if err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } @@ -1388,12 +1402,12 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S if rec.UnstartedActors != nil { unstarted = rec.UnstartedActors } - if did.fired != nil { + 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, did.fired.Effects); err != nil { + if err := r.dispatchReplayEffects(ctx, id, rec.Step, fired.Effects); err != nil { return nil, err } } @@ -1472,7 +1486,6 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S svcBuf: &svcBuf, settled: mirror.settled, actors: actors, - actorBuf: &actorBuf, actorFires: actorFires, lock: make(chan struct{}, 1), out: outbox{dispatching: map[int]struct{}{}, checkpointed: baselineStep}, @@ -1766,12 +1779,6 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { return errs } -// replayed is what replayRecord fired, for a caller that tracks more than the -// instance: a tick barrier's timer fires, or a plain event's Fire. -type replayed[S comparable] struct { - fired *state.FireResult[S] -} - // 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 @@ -1803,37 +1810,37 @@ func replayRecord[S comparable, E comparable, C any]( rec *Record, mirror *armMirror, actorArms bool, -) (replayed[S], error) { - var out replayed[S] +) (*state.FireResult[S], error) { + var fired *state.FireResult[S] before, rest, err := splitActorEntries(rec) if err != nil { - return out, fmt.Errorf("at step %d: %w", rec.Step, err) + return fired, fmt.Errorf("at step %d: %w", rec.Step, err) } // Parent Fires a Start's or Recover's spawns drove ran before the step's own work. if err := replayActors(ctx, inst, cfg, sched, svc, rec, before, mirror, actorArms); err != nil { - return out, err + return fired, err } switch { case len(rec.Event) > 0: event, err := cfg.eventCodec.Decode(rec.Event) if err != nil { - return out, fmt.Errorf("decoding recorded event at step %d: %w", rec.Step, err) + return fired, fmt.Errorf("decoding recorded event at step %d: %w", rec.Step, err) } fireOpts, err := replayFireOptions(rec, event, cfg.eventDataDecoder) if err != nil { - return out, fmt.Errorf("decoding recorded event data at step %d: %w", rec.Step, err) + return fired, fmt.Errorf("decoding recorded event data at step %d: %w", rec.Step, err) } res := inst.Fire(ctx, event, fireOpts...) if res.Err != nil { - return out, fmt.Errorf("replaying step %d: %w", rec.Step, res.Err) + return fired, fmt.Errorf("replaying step %d: %w", rec.Step, res.Err) } replayArm(ctx, sched, svc, res.Effects, mirror) - out.fired = &res + fired = &res case hasServiceEntry(rec): for _, entry := range serviceEntries(rec) { effects, err := replayService(ctx, svc, entry) if err != nil { - return out, fmt.Errorf("at step %d: %w", rec.Step, err) + return fired, fmt.Errorf("at step %d: %w", rec.Step, err) } mirror.settle(entry.CorrelationID) // The settle armed its own services; arm its timers, as RunService did. @@ -1844,7 +1851,7 @@ func replayRecord[S comparable, E comparable, C any]( } // 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 out, replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror, actorArms) + return fired, replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror, actorArms) } // replayActors re-fires recorded parent transitions, in order. When actorArms, the @@ -1858,7 +1865,7 @@ func replayActors[S comparable, E comparable, C any]( sched *state.Scheduler[S, E, C], svc *state.ServiceRunner[S, E, C], rec *Record, - entries []state.JournalEntry, + entries []decodedActorEntry, mirror *armMirror, actorArms bool, ) error { @@ -1876,6 +1883,16 @@ func replayActors[S comparable, E comparable, C any]( return nil } +// checkFormat fails when rec's journal Format is lower than the checkpoint's that replay +// started from: a version doesn't write an older format than it did, so the Store lost +// the field, and replaying the Record as an older format's would recover wrong. +func checkFormat(checkpoint int, rec *Record) error { + if rec.Format < checkpoint { + return fmt.Errorf("durable: step %d records journal format %d after a checkpoint of format %d: the Store didn't keep Record.Format", rec.Step, rec.Format, checkpoint) + } + return nil +} + // armsActorFires reports whether rec was written by a version that arms the timers and // services an actor-driven parent Fire declares, from the journal Format it records. func armsActorFires(rec *Record) bool { diff --git a/durable/store_format_test.go b/durable/store_format_test.go new file mode 100644 index 00000000..d4de30be --- /dev/null +++ b/durable/store_format_test.go @@ -0,0 +1,47 @@ +package durable_test + +import ( + "context" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// formatDroppingStore is a Store that keeps every Record field but Format, as a +// custom backend with a schema from before that field would. +type formatDroppingStore struct{ *durable.MemStore } + +func (s formatDroppingStore) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { + rec.Format = 0 + return s.MemStore.Append(ctx, id, rec, opts...) +} + +// TestRecover_FromAStoreThatDropsFormat pins that Recover fails when a Store loses +// Record.Format, rather than replay the Records as an older format's and silently +// skip the timer an actor-driven Fire armed live. +func TestRecover_FromAStoreThatDropsFormat(t *testing.T) { + ctx := context.Background() + m := armedMachine() + clk := state.NewFakeClock(epoch) + opts := armedOptions(clk, true) + store, id := formatDroppingStore{durable.NewMemStore()}, durable.InstanceID("armed") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if found, deliverErr := h.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("armed", "working", 0)}, "finish"); !found || deliverErr != nil { + t.Fatalf("DeliverToActor = %v, %v", found, deliverErr) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + clk.Advance(10 * time.Second) + if _, err := durable.Recover(ctx, m, store, id, opts...); err == nil { + t.Fatal("Recover from a Store that dropped Format succeeded; want it to fail rather than recover without the timer the live run armed") + } +} diff --git a/durable/timetravel.go b/durable/timetravel.go index 070da5e0..82518afc 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -138,7 +138,7 @@ func StateAt[S comparable, E comparable, C any]( return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } - if err := replayThrough(ctx, inst, &cfg, bounded); err != nil { + if err := replayThrough(ctx, inst, &cfg, bounded, unmarshalCheckpoint(baseline).Format); err != nil { return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } return &TimeTravelView[S, E, C]{inst: inst, step: step}, nil @@ -229,6 +229,7 @@ func replayThrough[S comparable, E comparable, C any]( inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], bounded []Record, + format int, ) error { sched := state.NewScheduler(inst) @@ -245,6 +246,9 @@ func replayThrough[S comparable, E comparable, C any]( } // A domain effect is never dispatched here: a time-travel read applies no // side effect. + if err := checkFormat(format, &bounded[i]); err != nil { + return err + } if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, armsActorFires(&bounded[i])); err != nil { return err } diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 39cc6bb3..00501423 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -70,6 +70,15 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Fixed +- **`AbsorbRespawn` quiets only the actors it spawns.** Its quiet was one flag for the + whole system, so a message another goroutine's delivery sent the parent while it ran + was dropped. The quiet now rides the call chain that spawns each actor, and ends when + `AbsorbRespawn` returns. +- **An invocation's declared onError survives its JSON IR.** An onError that is the + zero event, such as an `iota` enum's first constant, read back as undeclared, and now + escalated. The IR writes the `onError` key only when one was declared and reads a + present key as declared, so IR written before this, which always has the key, keeps + routing the zero event as it did. - **An invoked actor with no onError escalates its failure.** When an `InvokeActor` actor with no `WithInvokeOnError` couldn't start, or failed after it ran, the actor system fired the zero event at the parent, which a wildcard or a transition on that diff --git a/state/actor_invoke_undeclared_test.go b/state/actor_invoke_undeclared_test.go index 1c5bbe38..1065448c 100644 --- a/state/actor_invoke_undeclared_test.go +++ b/state/actor_invoke_undeclared_test.go @@ -104,3 +104,33 @@ func TestInvokeActor_NoOnError_FailuresEscalate(t *testing.T) { } } } + +// TestInvokeActor_ZeroValueOnError_SurvivesJSON pins that an InvokeActor whose onError is +// the zero event, such as an iota enum's first constant, still counts as declared after +// the machine goes through its JSON IR, as it does when built. +func TestInvokeActor_ZeroValueOnError_SurvivesJSON(t *testing.T) { + const ( + failed = iota + start + ) + built := state.Forge[string, int, *trec]("parent"). + Actor("child"). + State("idle"). + State("supervising").InvokeActor("child", state.WithInvokeOnError(failed)). + Initial("idle"). + CurrentStateFn(func(*trec) string { return "idle" }). + Transition("idle").On(start).GoTo("supervising"). + Quench() + raw, err := built.ToJSON() + if err != nil { + t.Fatalf("ToJSON: %v", err) + } + ir, err := state.LoadFromJSON[string, int, *trec](raw) + if err != nil { + t.Fatalf("LoadFromJSON: %v", err) + } + loaded := ir.Provide(state.NewRegistry[*trec]()).CurrentStateFn(func(*trec) string { return "idle" }).Quench() + if sp := spawnEffect(t, loaded, start); sp.NoOnError { + t.Fatal("NoOnError = true after the JSON round trip, for an onError that is the zero event") + } +} diff --git a/state/actor_respawn_lift_test.go b/state/actor_respawn_lift_test.go index bde2d662..62346e78 100644 --- a/state/actor_respawn_lift_test.go +++ b/state/actor_respawn_lift_test.go @@ -48,3 +48,35 @@ func TestActorSystem_AbsorbRespawn_ALiftedFireReenteringAStateStartsItsActorOnce t.Fatalf("greeter started %d times and its hello reached the parent %d times (parent Fires %q), want once each", starts, hellos, fired) } } + +// TestActorSystem_AbsorbRespawn_DoesNotMuteAnotherActorsDelivery pins that the quiet of +// an AbsorbRespawn covers only the actors it spawns: a delivery to another actor that +// was already running, made while AbsorbRespawn is under way (as another goroutine +// can), reaches the parent with the message it drives. +func TestActorSystem_AbsorbRespawn_DoesNotMuteAnotherActorsDelivery(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*trec]("mute"). + Actor("pinger"). + Actor("late"). + State("waiting").InvokeActor("pinger").InvokeActor("late"). + State("hellod"). + Initial("waiting"). + Transition("waiting").On("hello").GoTo("hellod"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("waiting")) + sys := state.NewActorSystem(inst) + sys.Register("pinger", func(map[string]any) (state.ActorInstance, error) { return &pinger{}, nil }) + pingerID := state.ActorID("mute", "waiting", 0) + sys.Register("late", func(map[string]any) (state.ActorInstance, error) { + // Another goroutine's delivery, landing while AbsorbRespawn runs. + sys.DeliverByID(ctx, pingerID, "ping") + return &startGreeter{sent: true}, nil + }) + effects := inst.StartEffects() + // The pinger was already running, started as usual. + sys.Absorb(ctx, effects[:1]) + sys.AbsorbRespawn(ctx, effects[1:]) + if got := inst.Current(); got != "hellod" { + t.Fatalf("the pinger's hello, delivered during AbsorbRespawn, left the parent in %q, want hellod", got) + } +} diff --git a/state/actor_system.go b/state/actor_system.go index a1d19629..11cf9be5 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -4,6 +4,7 @@ import ( "context" "sort" "sync" + "sync/atomic" ) // This file ships the reusable host-driver harness for the actor model. The @@ -178,14 +179,6 @@ type ActorSystem[S comparable, E comparable, C any] struct { // the per-instance Inspector wired with WithInspector: the ActorSystem owns // spawning, stopping, and message delivery, which the pure Fire step never sees. inspector Inspector - - // quiet is set while AbsorbRespawn spawns an actor: a message to the parent is - // dropped, and so is a nested actor's onDone or onError. A parent Fire it lets - // through clears it until that Fire's effects are absorbed. Guarded by mu. - quiet bool - // respawned holds the ids of the actors AbsorbRespawn is spawning, whose failed - // spawn or settle fires the parent even while it's quiet. Guarded by mu. - respawned map[string]bool } // WithActorInspector wires a live observer sink fed the ActorSystem's @@ -323,59 +316,67 @@ func (s *ActorSystem[S, E, C]) AbsorbRespawn(ctx context.Context, effects []Effe respawned[e.ID] = true } } - s.mu.Lock() - prev := s.respawned - s.respawned = respawned - s.mu.Unlock() - defer func() { - s.mu.Lock() - s.respawned = prev - s.mu.Unlock() - }() + q := &respawnQuiet{respawned: respawned} + // The quiet ends with AbsorbRespawn, even for a context an actor's behavior kept. + defer q.ended.Store(true) for _, eff := range effects { if e, ok := eff.(SpawnActor); ok { - s.respawnOne(ctx, e) + s.respawnOne(ctx, q, e) continue } s.absorb(ctx, []Effect{eff}, nil) } } -// respawnOne spawns e with the parent quiet, so its start doesn't reach the parent. -func (s *ActorSystem[S, E, C]) respawnOne(ctx context.Context, e SpawnActor) { - prev := s.setQuiet(true) - defer s.setQuiet(prev) - s.spawn(ctx, e) +// respawnQuiet is the quiet of one AbsorbRespawn: it rides the context of the call +// chain that spawns each actor, so only that chain's messages to the parent are dropped, +// and a delivery another goroutine makes meanwhile is heard. +type respawnQuiet struct { + // respawned holds the ids of the actors AbsorbRespawn was given, whose failed spawn + // or settle fires the parent even while it's quiet. + respawned map[string]bool + // ended is set when AbsorbRespawn returns, ending the quiet. + ended atomic.Bool } -// setQuiet sets whether the parent is quiet, as it is while AbsorbRespawn spawns an -// actor, and returns the previous setting. -func (s *ActorSystem[S, E, C]) setQuiet(quiet bool) bool { - s.mu.Lock() - defer s.mu.Unlock() - prev := s.quiet - s.quiet = quiet - return prev +// quietKey is the context key a respawnQuiet rides under. +type quietKey struct{} + +// quietOf returns the quiet ctx carries, or nil when ctx carries none or AbsorbRespawn +// has returned. +func quietOf(ctx context.Context) *respawnQuiet { + q, _ := ctx.Value(quietKey{}).(*respawnQuiet) + if q == nil || q.ended.Load() { + return nil + } + return q } -// isQuiet reports whether a message to the parent is dropped, as AbsorbRespawn drops -// one an actor's start sends. -func (s *ActorSystem[S, E, C]) isQuiet() bool { - s.mu.Lock() - defer s.mu.Unlock() - return s.quiet +// heard returns ctx with the quiet lifted, for a parent Fire that's new and so is all +// it drives. +func heard(ctx context.Context) context.Context { + if quietOf(ctx) == nil { + return ctx + } + return context.WithValue(ctx, quietKey{}, (*respawnQuiet)(nil)) } -// hearingLocked reports how a parent Fire for actor id's failed spawn or settle goes -// while the parent may be quiet: dropped, when it's part of the start AbsorbRespawn is -// repeating, or fired with the parent heard again, when id is an actor AbsorbRespawn was -// given, which was running, so the Fire is new and so is all it drives. s.mu must be -// held. -func (s *ActorSystem[S, E, C]) hearingLocked(id string) (drop, lift bool) { - if !s.quiet { +// respawnOne spawns e with the parent quiet on its call chain, so its start doesn't +// reach the parent. +func (s *ActorSystem[S, E, C]) respawnOne(ctx context.Context, q *respawnQuiet, e SpawnActor) { + s.spawn(context.WithValue(ctx, quietKey{}, q), e) +} + +// hearing reports how a parent Fire for actor id's failed spawn or settle goes on ctx's +// call chain: dropped, when it's part of the start AbsorbRespawn is repeating, or fired +// with the parent heard again, when id is an actor AbsorbRespawn was given, which was +// running, so the Fire is new and so is all it drives. +func hearing(ctx context.Context, id string) (drop, lift bool) { + q := quietOf(ctx) + if q == nil { return false, false } - if s.respawned[id] { + if q.respawned[id] { return false, true } return true, false @@ -474,9 +475,7 @@ func (s *ActorSystem[S, E, C]) spawn(ctx context.Context, e SpawnActor) { // failure escalates to the parent as a typed ActorEscalation rather than being // silently swallowed (the G3 default), so a spawn that cannot start is never lost. func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err error) { - s.mu.Lock() - drop, lift := s.hearingLocked(e.ID) - s.mu.Unlock() + drop, lift := hearing(ctx, e.ID) // A failure the start AbsorbRespawn is repeating was routed or escalated when it // first happened. if drop { @@ -490,8 +489,7 @@ func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err return } if lift { - prev := s.setQuiet(false) - defer s.setQuiet(prev) + ctx = heard(ctx) } res := s.parent.Fire(ctx, ev) s.noteParentFire(ParentFire[S]{Result: res, ActorID: e.ID, SpawnFailed: true}) @@ -750,7 +748,7 @@ func (s *ActorSystem[S, E, C]) resolveTarget(targetID, systemID string) (string, // drains it. This is the single path every routed message flows through, so parent // and child delivery share their sender bookkeeping. func (s *ActorSystem[S, E, C]) dispatch(ctx context.Context, targetID string, event any, senderID string) { - if targetID == parentActorID && s.isQuiet() { + if targetID == parentActorID && quietOf(ctx) != nil { return } s.inspectMessage(senderID, targetID, MessageSent, event) @@ -814,8 +812,8 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any ev, route = ra.onDone, ra.hasDone } s.lastOutcome = actorOutcome{output: output, err: err, set: true} - drop, lift := s.hearingLocked(id) s.mu.Unlock() + drop, lift := hearing(ctx, id) // A completed actor's children are torn down with it. for _, c := range children { @@ -836,8 +834,7 @@ func (s *ActorSystem[S, E, C]) settle(ctx context.Context, id string, output any return FireResult[S]{}, false } if lift { - prev := s.setQuiet(false) - defer s.setQuiet(prev) + ctx = heard(ctx) } // Deliver the child's output/error to the parent's onDone/onError transition's // Assign through the done-event payload (AssignCtx.Event), not a side channel: diff --git a/state/invoke.go b/state/invoke.go index 39aa4fad..3cd18390 100644 --- a/state/invoke.go +++ b/state/invoke.go @@ -79,15 +79,15 @@ type Invocation[S comparable, E comparable, C any] struct { // extra preserves unknown JSON keys a newer producer emitted so they survive a // load -> save cycle (forward-compat). Never inspected by the kernel. extra map[string]json.RawMessage - // hasOnError records that the builder was given WithInvokeOnError, since OnError - // holds the zero event either way. It doesn't serialize, so an invocation loaded - // from JSON falls back to OnError not being the zero event (declaresOnError). + // hasOnError records that an onError was declared, since OnError holds the zero + // event either way: the builder was given WithInvokeOnError, or the JSON it was + // loaded from has the onError key. hasOnError bool } -// declaresOnError reports whether the invocation declared an onError: the builder -// was given WithInvokeOnError, or, for one loaded from JSON, OnError isn't the zero -// event. +// declaresOnError reports whether the invocation declared an onError: the builder was +// given WithInvokeOnError, the JSON it was loaded from has the onError key, or, for one +// built some other way, OnError isn't the zero event. func (inv *Invocation[S, E, C]) declaresOnError() bool { var zero E return inv.hasOnError || inv.OnError != zero @@ -101,10 +101,28 @@ var invocationKnownKeys = map[string]struct{}{ } // MarshalJSON encodes an Invocation, merging its preserved unknown keys back in -// with stable key ordering. +// with stable key ordering. It writes the onError key only when an onError was +// declared, so a declared zero event survives the round trip and an undeclared one +// isn't read back as declared. func (inv Invocation[S, E, C]) MarshalJSON() ([]byte, error) { - type alias Invocation[S, E, C] - return marshalWithExtra(alias(inv), inv.extra) + if inv.declaresOnError() { + type alias Invocation[S, E, C] + return marshalWithExtra(alias(inv), inv.extra) + } + // The fields, in Invocation's order, less onError. + type undeclared struct { + ID string `json:"id,omitempty"` + Src Ref `json:"src"` + Input map[string]any `json:"input,omitempty"` + OnDone E `json:"onDone"` + Kind ActorKind `json:"kind,omitempty"` + SystemID string `json:"systemId,omitempty"` + Meta map[string]any `json:"meta,omitempty"` + } + return marshalWithExtra(undeclared{ + ID: inv.ID, Src: inv.Src, Input: inv.Input, OnDone: inv.OnDone, + Kind: inv.Kind, SystemID: inv.SystemID, Meta: inv.Meta, + }, inv.extra) } // UnmarshalJSON decodes an Invocation and captures any unknown keys into extra so @@ -118,6 +136,13 @@ func (inv *Invocation[S, E, C]) UnmarshalJSON(data []byte) error { } *inv = Invocation[S, E, C](a) inv.extra = extra + // A document that has the onError key declared one, even as the zero event; one + // from before this field always has it, and keeps routing the zero event. + var keys map[string]json.RawMessage + if err := json.Unmarshal(data, &keys); err != nil { + return err + } + _, inv.hasOnError = keys["onError"] return nil } From ee55ccb60bfc59b911d7dab19bb9c79ee2bf8c94 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Mon, 16 Nov 2026 00:43:58 -0700 Subject: [PATCH 31/38] fix(durable): don't rerun a compound state's settled invoke after Recover from an older checkpoint An older version started only the active leaves' services and actors at Start and Recover, so its checkpoints record no compound state's as settled or ended. Now that StartEffects includes a compound state's, Recover from such a checkpoint put a service that had settled into a child back in flight, and spawned an actor that had finished. For a checkpoint without a journal format, Recover counts a compound state's services as settled and its actors as ended, as that version left them, including on a later Recover after this version has recorded steps on top. The skipped host-clock test now points at #247. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 6 + durable/chained_deadline_internal_test.go | 2 +- durable/older_checkpoint_compound_test.go | 165 ++++++++++++++++++++++ durable/runner.go | 53 ++++++- 4 files changed, 223 insertions(+), 3 deletions(-) create mode 100644 durable/older_checkpoint_compound_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 58dfbec4..71a50dc2 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -142,6 +142,12 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Fixed +- **`Recover` from an older checkpoint doesn't rerun a compound state's settled service + or actor.** This version starts a compound state's services and actors at `Start` and + `Recover`, which an older one didn't, so it recorded none of them as settled or ended. + `Recover` from a checkpoint an older version wrote put such a service back in flight, + or spawned such an actor, even when it had settled into one of the state's children. + It now counts them as settled or ended, as that version left them. - **`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 diff --git a/durable/chained_deadline_internal_test.go b/durable/chained_deadline_internal_test.go index 8d311e66..39ee3313 100644 --- a/durable/chained_deadline_internal_test.go +++ b/durable/chained_deadline_internal_test.go @@ -257,7 +257,7 @@ func TestFire_ADeadlineHoldsWhenTheTransitionReadsTheClock(t *testing.T) { // the step's own, but Recover can't run that host read against the replay clock, so // replay's reads shift by one and the timer comes back at another deadline. func TestRecover_ReplaysAStepWhoseHostCodeReadTheInstanceClock(t *testing.T) { - t.Skip("a host read of Instance().Clock() during a step is journaled but can't be replayed; awaiting a ruling") + t.Skip("a host read of Instance().Clock() during a step is journaled but can't be replayed; #247") ctx := context.Background() type cx struct{} var h *Handle[string, string, cx] diff --git a/durable/older_checkpoint_compound_test.go b/durable/older_checkpoint_compound_test.go new file mode 100644 index 00000000..f9882098 --- /dev/null +++ b/durable/older_checkpoint_compound_test.go @@ -0,0 +1,165 @@ +package durable_test + +import ( + "context" + "encoding/json" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// olderCheckpoint returns the store's latest checkpoint rewritten in the shape an +// older version wrote, with no journal format and no actor or service sets, in a new +// store, at the same step. +func olderCheckpoint(t *testing.T, store *durable.MemStore, id durable.InstanceID) *durable.MemStore { + t.Helper() + ctx := context.Background() + snap, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(tail) != 0 { + t.Fatalf("tail holds %d Records, want the checkpoint to cover every step", len(tail)) + } + step, ok, err := store.LastStep(ctx, id) + if err != nil || !ok { + t.Fatalf("LastStep = %d, %v, %v", step, ok, err) + } + var env map[string]json.RawMessage + if err = json.Unmarshal(snap, &env); err != nil { + t.Fatalf("decoding the checkpoint: %v", err) + } + for _, k := range []string{"format", "endedServices", "endedActors", "unstartedActors"} { + delete(env, k) + } + if snap, err = json.Marshal(env); err != nil { + t.Fatalf("encoding the checkpoint: %v", err) + } + older := durable.NewMemStore() + if err = older.Checkpoint(ctx, id, snap, step); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + return older +} + +// TestRecover_FromAnOlderCheckpointDoesNotRerunACompoundStatesSettledService pins that +// Recover from a checkpoint an older version wrote starts what that version would have: +// the active leaves' services, not a compound state's, which the older version never +// started and which, here, already settled into a child. The service doesn't run again. +func TestRecover_FromAnOlderCheckpointDoesNotRerunACompoundStatesSettledService(t *testing.T) { + ctx := context.Background() + runs := 0 + load := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { runs++; return "ok", nil } + m := state.ForgeFor[stepCtx]("olderCompound"). + Service("load", load). + State("idle"). + SuperState("outer").Invoke("load", state.WithInvokeOnDone("loaded")). + SubState("loading"). + SubState("ready"). + Initial("loading"). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("outer"). + Transition("loading").On("loaded").GoTo("ready"). + Transition("ready").On("poke").GoTo("ready"). + Quench() + opts := []stepOption{ + durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("load", load)), + durable.WithCheckpointEvery[string, string, stepCtx](1), + } + store, id := durable.NewMemStore(), durable.InstanceID("older-compound") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + svcID := state.InvokeID("olderCompound", "outer", 0) + if _, ran, runErr := h.RunService(ctx, svcID); !ran || runErr != nil { + t.Fatalf("RunService = %v, %v", ran, runErr) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + older := olderCheckpoint(t, store, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, runErr := recovered.RunService(ctx, svcID); ran || runErr != nil { + t.Fatalf("RunService after Recover from an older checkpoint = ran %v, %v (runs %d), want the settled compound service left alone", ran, runErr, runs) + } + // A step this version records on top, and the checkpoint it lands, keep it settled. + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + again, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if _, ran, runErr := again.RunService(ctx, svcID); ran || runErr != nil { + t.Fatalf("RunService after a second Recover = ran %v, %v (runs %d), want the service still settled", ran, runErr, runs) + } +} + +// TestRecover_FromAnOlderCheckpointDoesNotRespawnACompoundStatesSettledActor pins the +// same for a compound state's actor that finished into a child: Recover from an older +// checkpoint, which records no ended actors, doesn't spawn it again. +func TestRecover_FromAnOlderCheckpointDoesNotRespawnACompoundStatesSettledActor(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[stepCtx]("olderCompoundActor"). + Actor("kid"). + State("idle"). + SuperState("outer").InvokeActor("kid", state.WithInvokeOnDone("kidDone"), state.WithInvokeID("kid")). + SubState("loading"). + SubState("ready"). + Initial("loading"). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("outer"). + Transition("loading").On("kidDone").GoTo("ready"). + Transition("ready").On("poke").GoTo("ready"). + Quench() + opts := []stepOption{ + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"kid": finishingChild()}), + durable.WithCheckpointEvery[string, string, stepCtx](1), + } + store, id := durable.NewMemStore(), durable.InstanceID("older-compound-actor") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + if ok, deliverErr := h.DeliverToActorByID(ctx, "kid", "finish"); !ok || deliverErr != nil { + t.Fatalf("DeliverToActorByID = %v, %v", ok, deliverErr) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("state = %q, want ready by the kid's onDone", got) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + older := olderCheckpoint(t, store, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, running := recovered.ActorRef("kid"); running { + t.Fatal("Recover from an older checkpoint spawned the compound state's kid again, which had finished") + } + // A step this version records on top, and the checkpoint it lands, keep it ended. + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + again, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if _, running := again.ActorRef("kid"); running { + t.Fatal("a second Recover spawned the finished kid again") + } +} diff --git a/durable/runner.go b/durable/runner.go index 56e1784a..5d91a957 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -1211,6 +1211,30 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { return &ActorSet{IDs: endedIDs}, &ActorSet{IDs: unstartedIDs} } +// compoundStarts returns the StartEffects of inst's active compound states, the ones +// that aren't active leaves: what StartEffects covers that an older version's, which +// covered the active leaves alone, didn't. +func compoundStarts[S comparable, E comparable, C any](inst *state.Instance[S, E, C]) []state.Effect { + leaves := map[string]bool{} + for _, s := range inst.Configuration() { + leaves[fmt.Sprint(s)] = true + } + var out []state.Effect + for _, eff := range inst.StartEffects() { + switch e := eff.(type) { + case state.StartService: + if !leaves[e.State] { + out = append(out, eff) + } + case state.SpawnActor: + if !leaves[e.State] { + out = append(out, eff) + } + } + } + return out +} + // actorSetsCache is the last result actorSets computed, with what it read: the // configuration and the running actors. type actorSetsCache struct { @@ -1343,10 +1367,27 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // step) can be re-settled from its recorded outcome without re-running it. A // service that had settled by the checkpoint while its state stayed active isn't // armed: it would run again. + // An older version started only the active leaves' services and actors at Start and + // Recover, never a compound state's, so it recorded none of theirs as settled or + // ended. For a checkpoint it wrote, count a compound state's as settled or ended, as + // that version left them, so Recover doesn't run one that already settled into a + // child. + endedServices := env.EndedServices + var olderEndedActors []string + if env.Format < actorArmsFormat { + for _, eff := range compoundStarts(inst) { + switch e := eff.(type) { + case state.StartService: + endedServices = append(endedServices, e.ID) + case state.SpawnActor: + olderEndedActors = append(olderEndedActors, e.ID) + } + } + } svcBuf := make([]state.JournalEntry, 0) svc := r.newServiceRunner(inst) if svc != nil { - svc.Absorb(ctx, startsExcept(inst.StartEffects(), env.EndedServices, func(sv state.StartService) string { return sv.ID })) + svc.Absorb(ctx, startsExcept(inst.StartEffects(), endedServices, func(sv state.StartService) string { return sv.ID })) } // Build the child-machine actor host driver, but DO NOT spawn the restored @@ -1367,7 +1408,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // services that settled in their state's current activation, starting from the ones // the checkpoint recorded. mirror := &armMirror{armed: armed, clock: repClock} - for _, sv := range env.EndedServices { + for _, sv := range endedServices { mirror.settle(sv) } @@ -1375,6 +1416,14 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // the checkpoint's, then each tail Record's that records one. Nil means none was // recorded, so Recover spawns every actor the configuration declares. ended := env.EndedActors + if len(olderEndedActors) > 0 { + ids := olderEndedActors + if ended != nil { + ids = append(ids, ended.IDs...) + } + slices.Sort(ids) + ended = &ActorSet{IDs: slices.Compact(ids)} + } // unstarted is the latest recorded set of the declared actors that weren't running // and hadn't ended, recorded alongside ended. Nil means none was recorded. unstarted := env.UnstartedActors From b97e07ddd0346a79e56cc5d844271d452e2f2d4a Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Mon, 16 Nov 2026 01:13:41 -0700 Subject: [PATCH 32/38] fix: a delivery whose context ended fails; Recover keeps a Handle once its spawns ran - durable: DeliverToActor records nothing and fails the Handle once its context ended by the end of the delivery, even when it drove no parent Fire. The ending may have made the kernel refuse the actor's own Fire, losing the event, while the call reported success. - durable: Recover no longer fails on a context that ends once it has spawned its actors with no Fire refused, as Start doesn't; their behaviors already ran, and a retry would run them again. - state: ResumeEffects covers the active leaves alone again, services and actors as well as timers. After a Restore, a compound state's service or actor may already have settled into a child, and starting it again ran it twice. - state: an Invocation's JSON is parsed once on load; AbsorbRespawn's doc no longer warns against concurrent deliveries, which the scoped quiet hears. Tests: a delivery refused inside the actor; Recover's context ending during a respawn; ResumeEffects after a compound service settled; every Invocation field kept when it declares no onError (by reflection, so a later field is covered). Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 8 +++- durable/actor.go | 19 ++++---- durable/deliver_ctx_test.go | 63 +++++++++++++++++++++++++ durable/recover_ctx_respawn_test.go | 44 ++++++++++++++++++ durable/runner.go | 11 +++-- durable/step_rule_test.go | 13 +++--- state/CHANGELOG.md | 9 ++-- state/actor_system.go | 5 +- state/envelope.go | 16 +++++-- state/invoke.go | 6 +-- state/invoke_declares_internal_test.go | 64 +++++++++++++++++++++++++- state/resume_compound_test.go | 46 ++++++++++++++++++ state/snapshot.go | 14 +++--- state/start_effects_superstate_test.go | 12 +++-- 14 files changed, 281 insertions(+), 49 deletions(-) create mode 100644 durable/deliver_ctx_test.go create mode 100644 durable/recover_ctx_respawn_test.go create mode 100644 state/resume_compound_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 71a50dc2..243d0825 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -185,8 +185,12 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. replay now meets the same refusal instead of failing Recover on it. After `Recover` the service stays in flight and must tolerate running again, the timer is re-armed, an `InvokeActor` actor restarts from its initial state, and a `Spawn` actor doesn't - return. `Recover` and `StateAt` now fail on a canceled context, rather than returning - state short of the journal. + return. `Recover` and `StateAt` now fail on a context that ends before the journal is + replayed, rather than returning state short of the journal. A context that ends once + `Recover` has spawned its actors, with no parent Fire refused, doesn't fail it, as for + `Start`, since their behaviors already ran. A `DeliverToActor` whose context ended by + the end of the delivery records nothing, even when it drove no parent Fire: the + ending may have made the kernel refuse the actor's own Fire, losing the event. - **`Fire` follows the same rule for the actors it spawns.** When an actor a Fire's state spawned failed to start and a context's ending refused its onError, the Fire was recorded, and `Recover` then applied the onError live never applied. Now `Fire` returns diff --git a/durable/actor.go b/durable/actor.go index 6ad7d1fe..46cfda53 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -111,9 +111,10 @@ type actorMessagePayload struct { // actor (already settled, stopped, or never spawned), or false and an error when no // palette is wired, the Handle has failed, or ctx ended before the delivery. Once the // actor ran it returns true with any error. A result that won't encode, a ctx that ended -// during a delivery that drove a parent Fire, or a parent Fire refused because a context -// ended (ctx, or one middleware derived from it) returns ErrHandleFailed and records -// nothing; a delivery that drove no parent Fire records as usual. On a +// by the end of the delivery, or a parent Fire refused because a context ended (ctx, or +// one middleware derived from it) returns ErrHandleFailed and records nothing: a ctx +// that ended before the actor handled the event made the kernel refuse the actor's own +// Fire, and the event was lost. On a // recovered Handle an InvokeActor actor restarts from its initial state, and a Spawn // actor doesn't return. A failed Append also returns ErrHandleFailed, but the write may // have landed anyway, and Recover finds out which. If another goroutine failed the Handle while this step was @@ -141,13 +142,11 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef if !delivered { return false, nil } - // A context that ended during the delivery can make the kernel refuse a parent - // Fire it drove. The refused Fire rolls back, so live never applied it, but - // journaling the delivery would replay it under a live context, where it applies. - // Record nothing. - // A delivery that drove no parent Fire changed nothing the journal holds, so an ended - // ctx can't have cost it anything. - if err := consumedCanceled(ctx, len(fires) > 0, parentFireErrs(fires)...); err != nil { + // A context that ended during the delivery can make the kernel refuse the actor's + // own Fire, losing the event, or a parent Fire it drove. A refused Fire rolls back, + // so live never applied it, but journaling the delivery would replay it under a live + // context, where it applies. Record nothing. + if err := stepCanceled(ctx, parentFireErrs(fires)...); err != nil { return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) } diff --git a/durable/deliver_ctx_test.go b/durable/deliver_ctx_test.go new file mode 100644 index 00000000..1dd8119d --- /dev/null +++ b/durable/deliver_ctx_test.go @@ -0,0 +1,63 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// cancelingActor wraps an actor and ends the step's context just before the actor +// handles a delivered event, as a deadline passing mid-delivery would. +type cancelingActor struct { + inner state.ActorInstance + cancel context.CancelFunc +} + +func (a *cancelingActor) DeliverFire(ctx context.Context, ev any) (bool, any) { + a.cancel() + return a.inner.DeliverFire(ctx, ev) +} +func (a *cancelingActor) ChildEffects() []state.Effect { return a.inner.ChildEffects() } +func (a *cancelingActor) Output() any { return a.inner.Output() } + +// TestDeliverToActor_AContextThatEndsBeforeTheActorHandlesItFails pins that a delivery +// whose context ends before the actor handles the event, so the actor's own Fire is +// refused and the event is lost, fails rather than reporting a delivery that never +// happened. +func TestDeliverToActor_AContextThatEndsBeforeTheActorHandlesItFails(t *testing.T) { + ctx := context.Background() + turn, cancel := context.WithCancel(ctx) + defer cancel() + child := state.ForgeFor[stepCtx]("kid"). + State("working"). + State("noted"). + Initial("working"). + Transition("working").On("note").GoTo("noted"). + Quench() + m := state.ForgeFor[stepCtx]("deliverCtx"). + Actor("kid"). + State("working").InvokeActor("kid", state.WithInvokeID("kid")). + Initial("working"). + Transition("working").On("poke").GoTo("working"). + Quench() + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "kid": func(map[string]any) (state.ActorInstance, error) { + inner := state.NewActor(child.Cast(stepCtx{}, state.WithInitialState("working")), nil) + return &cancelingActor{inner: inner, cancel: cancel}, nil + }, + })} + h, err := durable.NewRunner(m, durable.NewMemStore(), opts...).Start(ctx, "deliver-ctx", stepCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + found, err := h.DeliverToActorByID(turn, "kid", "note") + if !found { + t.Fatal("the kid isn't running") + } + if !errors.Is(err, context.Canceled) { + t.Fatalf("DeliverToActor = %v, want an error wrapping context.Canceled: the kid never handled the event", err) + } +} diff --git a/durable/recover_ctx_respawn_test.go b/durable/recover_ctx_respawn_test.go new file mode 100644 index 00000000..12ca73e7 --- /dev/null +++ b/durable/recover_ctx_respawn_test.go @@ -0,0 +1,44 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestRecover_AContextThatEndsWhileARespawnRunsWithNoFireRefused pins that Recover, like +// Start, doesn't fail when its context ends while it spawns an actor and no parent Fire +// was refused: the actor's behavior already ran, and failing would make the caller's +// retry run it again. +func TestRecover_AContextThatEndsWhileARespawnRunsWithNoFireRefused(t *testing.T) { + ctx := context.Background() + m := spawnRuleMachine(false, nil) + store, id := durable.NewMemStore(), durable.InstanceID("recover-ctx") + calls := 0 + var cancel context.CancelFunc + opts := []stepOption{durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "child": func(in map[string]any) (state.ActorInstance, error) { + calls++ + if calls == 1 { + return nil, errors.New("the child can't start yet") + } + cancel() // the deadline passes as the retried spawn runs + return finishingChild()(in) + }, + })} + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + turn, c := context.WithCancel(ctx) + cancel = c + if _, err = durable.Recover(turn, m, store, id, opts...); err != nil { + t.Fatalf("Recover = %v after the retried spawn ran (behavior ran %d times); want it to succeed, as Start does, so a retry doesn't run the behavior again", err, calls) + } +} diff --git a/durable/runner.go b/durable/runner.go index 5d91a957..d69cddbf 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -1317,8 +1317,10 @@ func respawn[S comparable, E comparable, C any](ctx context.Context, actors *sta // snapshot (firing nothing, no IO), and replays the tail's recorded driving // events through the kernel to reach the instance's live state. The returned // Handle continues recording subsequent Fires. Recover reports ErrInstanceNotFound -// for an instance that was never started, and the context's error if ctx ends or a -// context's ending refuses a parent Fire an actor it spawned drove. +// for an instance that was never started, and the context's error if ctx ends before +// the journal is replayed, or a context's ending refuses a parent Fire an actor it +// spawned drove. A ctx that ends once the actors are spawned, with no Fire refused, +// doesn't fail it, as for Start: their behaviors already ran. func Recover[S comparable, E comparable, C any](ctx context.Context, m *state.Machine[S, E, C], st Store, id InstanceID, opts ...Option[S, E, C]) (*Handle[S, E, C], error) { r := NewRunner(m, st, opts...) return r.recover(ctx, id) @@ -1587,10 +1589,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S } } + // A context that ended once the spawns ran fails nothing, as for Start: their + // behaviors already ran, and failing would make a retry run them again. h.pending = recoverFires - if err := ctx.Err(); err != nil { - return nil, fmt.Errorf("durable: recovering %q: %w", id, err) - } return h, nil } diff --git a/durable/step_rule_test.go b/durable/step_rule_test.go index 7f557289..59734651 100644 --- a/durable/step_rule_test.go +++ b/durable/step_rule_test.go @@ -855,10 +855,11 @@ func TestStart_FailsWhenItsContextEndsDuringASpawn(t *testing.T) { } } -// TestRecover_FailsWhenItsContextEndsAfterReplay proves Recover returns no Handle when -// its context ends after the journal is replayed, here while it spawns the resume -// point's actor, though no parent Fire was refused. -func TestRecover_FailsWhenItsContextEndsAfterReplay(t *testing.T) { +// TestRecover_SucceedsWhenItsContextEndsAfterReplay proves Recover, like Start, returns +// its Handle when its context ends after the journal is replayed, here while it spawns +// the resume point's actor, and no parent Fire was refused: the actor's behavior ran, +// and failing would make a retry run it again. +func TestRecover_SucceedsWhenItsContextEndsAfterReplay(t *testing.T) { ctx := context.Background() m := state.ForgeFor[stepCtx]("late"). Actor("quiet"). @@ -887,8 +888,8 @@ func TestRecover_FailsWhenItsContextEndsAfterReplay(t *testing.T) { turn, cancel := context.WithCancel(ctx) defer cancel() recovered, err := durable.Recover(turn, m, store, id, quiet(cancel)...) - if recovered != nil || !errors.Is(err, context.Canceled) { - t.Fatalf("Recover = Handle %v, %v, want no Handle and context.Canceled", recovered != nil, err) + if recovered == nil || err != nil { + t.Fatalf("Recover = Handle %v, %v, want the Handle and no error", recovered != nil, err) } } diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 00501423..9ef88fca 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -88,10 +88,11 @@ counts as an additive (minor) versus breaking (major) change. Use the - **`StartEffects` includes a compound state's invokes.** It looked only at the active leaves, so a service or actor declared on a compound state wasn't started while one of its children was active: not at a durable `Start` or `Recover`, and not for a child - actor's own nested actors. It now reports every active state's, ancestors first, and - so does `ResumeEffects` for services and actors. `ResumeEffects` still re-arms only the - active leaves' `after` timers: a compound state's timer may already have fired into - one of its children, and the snapshot can't say. + actor's own nested actors. It now reports every active state's, ancestors first. + `ResumeEffects` still covers the active leaves alone, timers, services and actors: + after a Restore, a compound state's timer may already have fired into one of its + children, or its service or actor may already have settled into one, and the snapshot + can't say. ## [1.0.0] — 2026-06-13 diff --git a/state/actor_system.go b/state/actor_system.go index 11cf9be5..20ef3520 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -307,8 +307,9 @@ func (s *ActorSystem[S, E, C]) AbsorbFor(ctx context.Context, event any, effects // start. A nested actor's failure with no onError doesn't escalate again either, while // one in effects that fails now does. The effects such a Fire drives absorb as under // Absorb: an actor its state spawns, or one it sends to, reaches the parent. Its other -// effects absorb as under Absorb. Don't drive the system from another goroutine while -// AbsorbRespawn runs: a parent Fire that one drives would be dropped too. +// effects absorb as under Absorb. The quiet rides the call chain that spawns each actor, +// so a delivery another goroutine makes while AbsorbRespawn runs reaches the parent as +// usual, and it ends when AbsorbRespawn returns. func (s *ActorSystem[S, E, C]) AbsorbRespawn(ctx context.Context, effects []Effect) { respawned := map[string]bool{} for _, eff := range effects { diff --git a/state/envelope.go b/state/envelope.go index 0d6bb3cb..bedb38fc 100644 --- a/state/envelope.go +++ b/state/envelope.go @@ -132,16 +132,22 @@ func marshalWithExtra(known any, extra map[string]json.RawMessage) ([]byte, erro // target struct owns; any key outside it is captured. A nil result means there // were no unknown keys. func captureExtra(data []byte, knownTarget any, knownKeys map[string]struct{}) (map[string]json.RawMessage, error) { + extra, _, err := captureExtraKeys(data, knownTarget, knownKeys) + return extra, err +} + +// captureExtraKeys is captureExtra that also returns every top-level key data has, +// known or not, so a caller can tell a key that is present from one that is absent +// without parsing data again. The keys are nil when data is not a JSON object. +func captureExtraKeys(data []byte, knownTarget any, knownKeys map[string]struct{}) (extra, all map[string]json.RawMessage, err error) { if err := json.Unmarshal(data, knownTarget); err != nil { - return nil, err + return nil, nil, err } - var all map[string]json.RawMessage if err := json.Unmarshal(data, &all); err != nil { // data was valid for the typed target but is not a JSON object (e.g. null): // there are no extra keys to capture. - return nil, nil //nolint:nilerr // a non-object body simply carries no extras. + return nil, nil, nil //nolint:nilerr // a non-object body simply carries no extras. } - var extra map[string]json.RawMessage for k, v := range all { if _, known := knownKeys[k]; known { continue @@ -151,7 +157,7 @@ func captureExtra(data []byte, knownTarget any, knownKeys map[string]struct{}) ( } extra[k] = v } - return extra, nil + return extra, all, nil } // cloneRawExtra deep-copies a preserved-unknown map so a deep-copied IR node never diff --git a/state/invoke.go b/state/invoke.go index 3cd18390..8a3090ac 100644 --- a/state/invoke.go +++ b/state/invoke.go @@ -130,7 +130,7 @@ func (inv Invocation[S, E, C]) MarshalJSON() ([]byte, error) { func (inv *Invocation[S, E, C]) UnmarshalJSON(data []byte) error { type alias Invocation[S, E, C] var a alias - extra, err := captureExtra(data, &a, invocationKnownKeys) + extra, keys, err := captureExtraKeys(data, &a, invocationKnownKeys) if err != nil { return err } @@ -138,10 +138,6 @@ func (inv *Invocation[S, E, C]) UnmarshalJSON(data []byte) error { inv.extra = extra // A document that has the onError key declared one, even as the zero event; one // from before this field always has it, and keeps routing the zero event. - var keys map[string]json.RawMessage - if err := json.Unmarshal(data, &keys); err != nil { - return err - } _, inv.hasOnError = keys["onError"] return nil } diff --git a/state/invoke_declares_internal_test.go b/state/invoke_declares_internal_test.go index 5772631f..241b61cb 100644 --- a/state/invoke_declares_internal_test.go +++ b/state/invoke_declares_internal_test.go @@ -1,6 +1,11 @@ package state -import "testing" +import ( + "encoding/json" + "reflect" + "strings" + "testing" +) // TestDeclaresOnError_NoPanicOnAnUncomparableEvent pins that declaresOnError, for an // invocation loaded from JSON (no builder flag), doesn't panic when its event type is an @@ -21,3 +26,60 @@ func TestDeclaresOnError_NoPanicOnAnUncomparableEvent(t *testing.T) { t.Fatal("a built onError of 0 reads as not declared") } } + +// TestInvocation_UndeclaredOnErrorKeepsEveryOtherField pins that an invocation with no +// onError declared, which MarshalJSON writes without the onError key, still writes every +// other field: each exported field of Invocation, found by reflection, so a field added +// later is covered too. +func TestInvocation_UndeclaredOnErrorKeepsEveryOtherField(t *testing.T) { + inv := Invocation[string, string, int]{} + v := reflect.ValueOf(&inv).Elem() + typ := v.Type() + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if !f.IsExported() || f.Name == "OnError" { + continue + } + fv := v.Field(i) + switch fv.Kind() { + case reflect.String: + fv.SetString("x") + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + fv.SetInt(1) + case reflect.Map: + fv.Set(reflect.MakeMapWithSize(fv.Type(), 1)) + fv.SetMapIndex(reflect.ValueOf("k"), reflect.ValueOf(any("v"))) + case reflect.Struct: + if f.Type == reflect.TypeOf(Ref{}) { + fv.Set(reflect.ValueOf(Ref{Name: "x"})) + } + default: + t.Fatalf("field %s has kind %s: teach this test to fill it", f.Name, fv.Kind()) + } + } + raw, err := json.Marshal(inv) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + var keys map[string]json.RawMessage + if err := json.Unmarshal(raw, &keys); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if !f.IsExported() { + continue + } + name := strings.Split(f.Tag.Get("json"), ",")[0] + _, present := keys[name] + if f.Name == "OnError" { + if present { + t.Fatal("an undeclared onError was written") + } + continue + } + if !present { + t.Fatalf("field %s (%q) is missing from the JSON of an invocation with no onError declared: %s", f.Name, name, raw) + } + } +} diff --git a/state/resume_compound_test.go b/state/resume_compound_test.go new file mode 100644 index 00000000..76e7ed59 --- /dev/null +++ b/state/resume_compound_test.go @@ -0,0 +1,46 @@ +package state_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestResumeEffects_DoesNotRestartACompoundServiceThatSettledIntoAChild pins that a host +// that restores a snapshot and absorbs ResumeEffects doesn't start a compound state's +// service again when, before the snapshot, it settled and moved the instance into one of +// the state's children. +func TestResumeEffects_DoesNotRestartACompoundServiceThatSettledIntoAChild(t *testing.T) { + m := state.ForgeFor[*trec]("resumeCompound"). + Service("authorize", func(context.Context, state.ServiceCtx[*trec]) (any, error) { return nil, nil }). + SuperState("ordering").Invoke("authorize", state.WithInvokeOnDone("authorized")). + SubState("pending"). + SubState("paid"). + Initial("pending"). + EndSuperState(). + Initial("ordering"). + Transition("pending").On("authorized").GoTo("paid"). + Quench() + inst := m.Cast(&trec{}, state.WithInitialState("pending")) + if res := inst.Fire(context.Background(), "authorized"); res.Err != nil { + t.Fatalf("Fire(authorized): %v", res.Err) + } + snap, err := state.MarshalSnapshot(inst.Snapshot()) + if err != nil { + t.Fatalf("MarshalSnapshot: %v", err) + } + restoredSnap, err := state.UnmarshalSnapshot[string, string, *trec](snap) + if err != nil { + t.Fatalf("UnmarshalSnapshot: %v", err) + } + restored, err := m.Restore(restoredSnap) + if err != nil { + t.Fatalf("Restore: %v", err) + } + for _, eff := range restored.ResumeEffects() { + if sv, ok := eff.(state.StartService); ok { + t.Fatalf("ResumeEffects after the service settled into paid starts %s again", sv.ID) + } + } +} diff --git a/state/snapshot.go b/state/snapshot.go index 444baaae..8906a780 100644 --- a/state/snapshot.go +++ b/state/snapshot.go @@ -417,12 +417,14 @@ func (i *Instance[S, E, C]) pendingRefs(cfg []S) PendingRefs { // post-1.0 ADDITIVE item, not a v1.0 contract. func (i *Instance[S, E, C]) ResumeEffects() []Effect { var tr Trace - // Timers come from the active leaves only: a compound state's `after` timer may - // already have fired into one of its children, and re-arming it would fire it again. - out := i.afterEffectsOnEntry(i.Configuration(), &tr) - active := i.activeStates() - out = append(out, i.invokeEffectsOnEntry(active, &tr)...) - out = append(out, i.actorEffectsOnEntry(active, &tr)...) + // Everything comes from the active leaves only: a compound state's `after` timer + // may already have fired into one of its children, and its service or actor may + // already have settled into one, and a snapshot can't say which, so re-arming or + // starting it again would fire or run it a second time. + leaves := i.Configuration() + out := i.afterEffectsOnEntry(leaves, &tr) + out = append(out, i.invokeEffectsOnEntry(leaves, &tr)...) + out = append(out, i.actorEffectsOnEntry(leaves, &tr)...) return out } diff --git a/state/start_effects_superstate_test.go b/state/start_effects_superstate_test.go index 9859e9bc..fd0830d3 100644 --- a/state/start_effects_superstate_test.go +++ b/state/start_effects_superstate_test.go @@ -39,14 +39,20 @@ func TestStartEffects_IncludesTheSuperstatesInvokes(t *testing.T) { if len(actors) != 1 || actors[0] != "outerActor" { t.Fatalf("actors = %v, want [outerActor]", actors) } + // ResumeEffects, after a Restore, covers the active leaves alone: a compound state's + // service or actor may already have settled into a child, which a snapshot can't + // tell (TestResumeEffects_DoesNotRestartACompoundServiceThatSettledIntoAChild). var resumed []string for _, eff := range inst.ResumeEffects() { - if e, ok := eff.(state.SpawnActor); ok { + switch e := eff.(type) { + case state.StartService: + resumed = append(resumed, e.Src.Name) + case state.SpawnActor: resumed = append(resumed, e.Src.Name) } } - if len(resumed) != 1 || resumed[0] != "outerActor" { - t.Fatalf("ResumeEffects actors = %v, want [outerActor]", resumed) + if len(resumed) != 1 || resumed[0] != "innerSvc" { + t.Fatalf("ResumeEffects starts %v, want the leaf's [innerSvc]", resumed) } } From 2ff9f8be33efe4c519868d83b4014d8540aab9b9 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Mon, 16 Nov 2026 01:34:33 -0700 Subject: [PATCH 33/38] fix: check Recover's context after the last Record; nil OnError for an undeclared invoke - durable: Recover checks its context once more after the replay walk, before any actor spawns. b97e07d dropped the only check after the last Record, so a context that ended while the last Tick or settle replayed could return a Handle short of the journal. - state: an invoked actor with no onError emits its SpawnActor with a nil OnError, as a Spawn with none does, so a host that reads the effect sees none declared; the actor system already escalates on a nil OnError. SpawnActor.NoOnError, which only stood in for that, is removed. - durable: DeliverToActor, Start and Recover restore the actor collector's step context in a defer, so a panic out of host code, such as a parent middleware's, doesn't leave it driving under the dead step's context. Start and Recover build StartEffects once. - state: the ResumeEffects and StartEffects docs say which to call after a Restore. Tests: the context ending during the last replayed Record; an undeclared invoke's nil OnError; a middleware panic during a delivery. Signed-off-by: Ray Karnes --- durable/actor.go | 9 ++-- durable/deliver_panic_internal_test.go | 65 ++++++++++++++++++++++++ durable/recover_tail_ctx_test.go | 69 ++++++++++++++++++++++++++ durable/runner.go | 40 +++++++++------ state/CHANGELOG.md | 11 ++-- state/actor.go | 20 +++----- state/actor_invoke_undeclared_test.go | 32 ++++++------ state/actor_system.go | 8 +-- state/invoke.go | 20 ++++++-- state/snapshot.go | 10 ++-- 10 files changed, 215 insertions(+), 69 deletions(-) create mode 100644 durable/deliver_panic_internal_test.go create mode 100644 durable/recover_tail_ctx_test.go diff --git a/durable/actor.go b/durable/actor.go index 46cfda53..03ffcc87 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -135,9 +135,12 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef } stepCtx := h.stepContext(ctx) - restore := h.actorFires.driving(stepCtx) - delivered := h.actors.Deliver(stepCtx, ref, event) - restore() + // Restore in a defer, so a panic out of host code doesn't leave the collector driving + // under this step's context. + delivered := func() bool { + defer h.actorFires.driving(stepCtx)() + return h.actors.Deliver(stepCtx, ref, event) + }() fires := h.actorFires.take() if !delivered { return false, nil diff --git a/durable/deliver_panic_internal_test.go b/durable/deliver_panic_internal_test.go new file mode 100644 index 00000000..0cf02995 --- /dev/null +++ b/durable/deliver_panic_internal_test.go @@ -0,0 +1,65 @@ +package durable + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// messenger is an actor that sends its parent "boom" when it's delivered an event. +type messenger struct{ out []state.Effect } + +func (a *messenger) DeliverFire(context.Context, any) (bool, any) { + a.out = []state.Effect{state.SendParent{Event: "boom"}} + return false, nil +} + +func (a *messenger) ChildEffects() []state.Effect { + out := a.out + a.out = nil + return out +} +func (a *messenger) Output() any { return nil } + +// TestDeliverToActor_APanicLeavesNoStepContextBehind pins that a panic during a +// delivery, here in the parent's middleware for a message the actor sent, doesn't leave the actor collector holding the dead step's context, which a +// later parent Fire on the system would arm its timers and services under. +func TestDeliverToActor_APanicLeavesNoStepContextBehind(t *testing.T) { + ctx := context.Background() + type cx struct{} + m := state.ForgeFor[cx]("panicky"). + Use(func(next state.FireFunc[string, string, cx]) state.FireFunc[string, string, cx] { + return func(ctx context.Context, ev string) state.FireResult[string] { + if ev == "boom" { + panic("the parent's middleware panicked") + } + return next(ctx, ev) + } + }). + Actor("kid"). + State("working").InvokeActor("kid", state.WithInvokeID("kid")). + Initial("working"). + Transition("working").On("boom").GoTo("working"). + Quench() + h, err := NewRunner(m, NewMemStore(), WithActorPalette[string, string, cx](map[string]state.ActorBehavior{ + "kid": func(map[string]any) (state.ActorInstance, error) { return &messenger{}, nil }, + })).Start(ctx, "panicky", cx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + panicked := false + func() { + defer func() { panicked = recover() != nil }() + _, _ = h.DeliverToActorByID(ctx, "kid", "go") + }() + if !panicked { + t.Skip("no host panic reaches DeliverToActor: the kernel and the actor system recover them") + } + h.actorFires.mu.Lock() + left := h.actorFires.ctx + h.actorFires.mu.Unlock() + if left != nil { + t.Fatal("the actor collector still holds the panicked step's context") + } +} diff --git a/durable/recover_tail_ctx_test.go b/durable/recover_tail_ctx_test.go new file mode 100644 index 00000000..6f92ef99 --- /dev/null +++ b/durable/recover_tail_ctx_test.go @@ -0,0 +1,69 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestRecover_FailsWhenItsContextEndsDuringTheLastRecord pins that Recover fails when its +// context ends while it replays the journal's last Record, here a Tick that fires two +// timers whose first transition ends the context, so the kernel refuses the second: the +// recovered instance would otherwise be short of the journal with no error. +func TestRecover_FailsWhenItsContextEndsDuringTheLastRecord(t *testing.T) { + ctx := context.Background() + var cancel context.CancelFunc + m := state.ForgeFor[stepCtx]("tailCtx"). + Action("end", func(state.ActionCtx[stepCtx]) (state.Effect, error) { + if cancel != nil { + cancel() + } + return nil, nil + }). + State("idle"). + SuperState("both"). + Region("left"). + Initial("l1"). + SubState("l1"). + SubState("l2"). + EndRegion(). + Region("right"). + Initial("r1"). + SubState("r1"). + SubState("r2"). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("both"). + Transition("l1").After(time.Second).On("toL2").GoTo("l2").Do("end"). + Transition("r1").After(time.Second).On("toR2").GoTo("r2"). + Quench() + clk := state.NewFakeClock(epoch) + opts := []stepOption{durable.WithRunnerClock[string, string, stepCtx](clk)} + store, id := durable.NewMemStore(), durable.InstanceID("tail-ctx") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire(go): %v", err) + } + clk.Advance(2 * time.Second) + if fired, tickErr := h.Tick(ctx); tickErr != nil || len(fired) != 2 { + t.Fatalf("Tick fired %d, %v; want both timers", len(fired), tickErr) + } + turn, c := context.WithCancel(ctx) + cancel = c + recovered, err := durable.Recover(turn, m, store, id, opts...) + if !errors.Is(err, context.Canceled) { + got := "no Handle" + if recovered != nil { + got = recovered.Instance().Snapshot().Current + } + t.Fatalf("Recover = %v (state %v), want context.Canceled: the last Record's second timer was refused", err, got) + } +} diff --git a/durable/runner.go b/durable/runner.go index d69cddbf..016a409a 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -538,10 +538,11 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // the first RunService. The service buffer journals each settled outcome for // replay. A machine with no service registry wired runs no services and records // no service entries. + starts := inst.StartEffects() svcBuf := make([]state.JournalEntry, 0) svc := r.newServiceRunner(inst) if svc != nil { - svc.Absorb(ctx, inst.StartEffects()) + svc.Absorb(ctx, starts) } // Install the child-machine actor host driver and spawn the initial @@ -568,10 +569,11 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt } if actors != nil { actorFires.arm = h.absorbParentFire - actorFires.attempt(inst.StartEffects()) - restore := actorFires.driving(ctx) - actors.Absorb(ctx, inst.StartEffects()) - restore() + actorFires.attempt(starts) + func() { + defer actorFires.driving(ctx)() + actors.Absorb(ctx, starts) + }() } // A parent Fire a starting actor drove (a message it sent as it started, or a failed // spawn's onError) applied to the instance after its baseline, so the first step @@ -1211,16 +1213,16 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { return &ActorSet{IDs: endedIDs}, &ActorSet{IDs: unstartedIDs} } -// compoundStarts returns the StartEffects of inst's active compound states, the ones -// that aren't active leaves: what StartEffects covers that an older version's, which -// covered the active leaves alone, didn't. -func compoundStarts[S comparable, E comparable, C any](inst *state.Instance[S, E, C]) []state.Effect { +// compoundStarts returns, of starts (inst's StartEffects), those of its active compound +// states, the ones that aren't active leaves: what StartEffects covers that an older +// version's, which covered the active leaves alone, didn't. +func compoundStarts[S comparable, E comparable, C any](inst *state.Instance[S, E, C], starts []state.Effect) []state.Effect { leaves := map[string]bool{} for _, s := range inst.Configuration() { leaves[fmt.Sprint(s)] = true } var out []state.Effect - for _, eff := range inst.StartEffects() { + for _, eff := range starts { switch e := eff.(type) { case state.StartService: if !leaves[e.State] { @@ -1374,10 +1376,11 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // ended. For a checkpoint it wrote, count a compound state's as settled or ended, as // that version left them, so Recover doesn't run one that already settled into a // child. + restoredStarts := inst.StartEffects() endedServices := env.EndedServices var olderEndedActors []string if env.Format < actorArmsFormat { - for _, eff := range compoundStarts(inst) { + for _, eff := range compoundStarts(inst, restoredStarts) { switch e := eff.(type) { case state.StartService: endedServices = append(endedServices, e.ID) @@ -1389,7 +1392,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S svcBuf := make([]state.JournalEntry, 0) svc := r.newServiceRunner(inst) if svc != nil { - svc.Absorb(ctx, startsExcept(inst.StartEffects(), endedServices, func(sv state.StartService) string { return sv.ID })) + svc.Absorb(ctx, startsExcept(restoredStarts, endedServices, func(sv state.StartService) string { return sv.ID })) } // Build the child-machine actor host driver, but DO NOT spawn the restored @@ -1464,6 +1467,12 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S } } + // A canceled context can stop the last replayed settle or tick with no error too, so + // check it once more, now that the walk is done, before any actor spawns. + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } + // Drain any clock readings the replay re-recorded after the cursor exhausted // (none in the common case where replay consumes exactly the recorded // readings): they belong to no new step and must not leak into the next Fire. @@ -1561,9 +1570,10 @@ 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) - restore := actorFires.driving(ctx) - respawn(ctx, actors, spawns, unstarted) - restore() + func() { + defer actorFires.driving(ctx)() + respawn(ctx, actors, 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 diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 9ef88fca..462b078b 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -23,11 +23,6 @@ counts as an additive (minor) versus breaking (major) change. Use the record of armed timers' deadlines, as `durable` does for a checkpoint, reads the one the scheduler holds rather than working it out from a clock read of its own. It's additive, within v1.1.0. -- **`SpawnActor.NoOnError`** reports that an invoked actor declared no onError, so its - `OnError` holds only the zero event. An onError that is itself the zero event, such as - the first constant of an `iota` enum, counts as declared when the machine was built - with `WithInvokeOnError`; an invocation loaded from JSON counts one as declared only - when it isn't the zero event. It's additive, within v1.1.0. - **`ActorSystem.AbsorbRespawn`** is `Absorb` for actors a host spawns again after rebuilding the parent from a record that already holds every parent Fire their earlier start drove: an actor it spawns starts as under `Absorb`, but its start @@ -82,8 +77,10 @@ counts as an additive (minor) versus breaking (major) change. Use the - **An invoked actor with no onError escalates its failure.** When an `InvokeActor` actor with no `WithInvokeOnError` couldn't start, or failed after it ran, the actor system fired the zero event at the parent, which a wildcard or a transition on that - event could take as if an onError had been declared. It now escalates, as a `Spawn` - with no onError always has (the G3 default), and fires nothing. A machine that relied + event could take as if an onError had been declared. Its `SpawnActor` now carries a + nil `OnError`, as a `Spawn` with none does, so it escalates (the G3 default) and fires + nothing. An onError that is itself the zero event, such as the first constant of an + `iota` enum, still counts as declared. A machine that relied on that zero-event Fire changes behavior. - **`StartEffects` includes a compound state's invokes.** It looked only at the active leaves, so a service or actor declared on a compound state wasn't started while one of diff --git a/state/actor.go b/state/actor.go index 268dc473..fbf51925 100644 --- a/state/actor.go +++ b/state/actor.go @@ -87,11 +87,6 @@ type SpawnActor struct { // under in the ActorSystem (its systemId), so a sibling can address it // by a well-known name rather than by ref. Empty when unset. SystemID string `json:"systemId,omitempty"` - // NoOnError reports that an invoked actor declared no onError, so OnError holds only - // the zero event. The actor system then escalates the actor's failure, to start or - // after it ran, as it does for a dynamic spawn with no onError, which leaves OnError - // nil, rather than firing the zero event at the parent. - NoOnError bool `json:"noOnError,omitempty"` } // StopActor is the effect the kernel emits when an instance exits a state that @@ -242,14 +237,13 @@ func (i *Instance[S, E, C]) actorEffectsOnEntry(entries []S, tr *Trace) []Effect } id := actorInvocationID(m.name, s, ix, inv) out = append(out, SpawnActor{ - ID: id, - Src: inv.Src, - Input: inv.Input, - OnDone: inv.OnDone, - OnError: inv.OnError, - State: fmtState(s), - SystemID: inv.SystemID, - NoOnError: !inv.declaresOnError(), + ID: id, + Src: inv.Src, + Input: inv.Input, + OnDone: inv.OnDone, + OnError: inv.declaredOnError(), + State: fmtState(s), + SystemID: inv.SystemID, }) tr.note("actor.spawn." + id) } diff --git a/state/actor_invoke_undeclared_test.go b/state/actor_invoke_undeclared_test.go index 1065448c..8ca5b307 100644 --- a/state/actor_invoke_undeclared_test.go +++ b/state/actor_invoke_undeclared_test.go @@ -31,17 +31,6 @@ func invokeParent(opts ...state.InvokeOption) *state.Machine[string, string, *tr Quench() } -// TestInvokeActor_NoOnError_Flags pins SpawnActor.NoOnError: set when the invoke -// declared no onError, clear when it declared one. -func TestInvokeActor_NoOnError_Flags(t *testing.T) { - if sp := spawnEffect(t, invokeParent(), "start"); !sp.NoOnError { - t.Fatal("NoOnError = false for an invoke with no onError") - } - if sp := spawnEffect(t, invokeParent(state.WithInvokeOnError("failed")), "start"); sp.NoOnError { - t.Fatal("NoOnError = true for an invoke with an onError") - } -} - // TestInvokeActor_ZeroValueOnError_IsDeclared pins that an onError that is the zero // event, as the first constant of an iota enum is, still counts as declared. func TestInvokeActor_ZeroValueOnError_IsDeclared(t *testing.T) { @@ -57,8 +46,8 @@ func TestInvokeActor_ZeroValueOnError_IsDeclared(t *testing.T) { CurrentStateFn(func(*trec) string { return "idle" }). Transition("idle").On(start).GoTo("supervising"). Quench() - if sp := spawnEffect(t, m, start); sp.NoOnError { - t.Fatal("NoOnError = true for an onError that is the zero event") + if sp := spawnEffect(t, m, start); sp.OnError != failed { + t.Fatalf("SpawnActor.OnError = %#v, want the declared zero-valued onError", sp.OnError) } } @@ -130,7 +119,20 @@ func TestInvokeActor_ZeroValueOnError_SurvivesJSON(t *testing.T) { t.Fatalf("LoadFromJSON: %v", err) } loaded := ir.Provide(state.NewRegistry[*trec]()).CurrentStateFn(func(*trec) string { return "idle" }).Quench() - if sp := spawnEffect(t, loaded, start); sp.NoOnError { - t.Fatal("NoOnError = true after the JSON round trip, for an onError that is the zero event") + if sp := spawnEffect(t, loaded, start); sp.OnError != failed { + t.Fatalf("SpawnActor.OnError = %#v after the JSON round trip, want the declared zero-valued onError", sp.OnError) + } +} + +// TestInvokeActor_NoOnError_CarriesNoOnErrorEvent pins that the SpawnActor an invoked +// actor with no onError emits carries no OnError, as a Spawn with none does, so a host +// that consumes SpawnActor effects and reads OnError, as its docs describe, escalates +// rather than firing the zero event. +func TestInvokeActor_NoOnError_CarriesNoOnErrorEvent(t *testing.T) { + if sp := spawnEffect(t, invokeParent(), "start"); sp.OnError != nil { + t.Fatalf("SpawnActor.OnError = %#v, want nil for an invoke with no onError", sp.OnError) + } + if sp := spawnEffect(t, invokeParent(state.WithInvokeOnError("failed")), "start"); sp.OnError != "failed" { + t.Fatalf("SpawnActor.OnError = %#v, want the declared failed", sp.OnError) } } diff --git a/state/actor_system.go b/state/actor_system.go index 20ef3520..ed44394b 100644 --- a/state/actor_system.go +++ b/state/actor_system.go @@ -448,9 +448,7 @@ func (s *ActorSystem[S, E, C]) spawn(ctx context.Context, e SpawnActor) { ra.onDone = d ra.hasDone = true } - // An invoked actor that declared no onError carries the zero event; its failure - // escalates, as a spawned actor's with none does (G3). - if er, ok := e.OnError.(E); ok && !e.NoOnError { + if er, ok := e.OnError.(E); ok { ra.onError = er ra.hasError = true } @@ -483,9 +481,7 @@ func (s *ActorSystem[S, E, C]) routeError(ctx context.Context, e SpawnActor, err return } ev, ok := e.OnError.(E) - // An invoked actor with no onError declared carries the zero event in OnError; it - // escalates, as a spawn with none does (G3), rather than firing that event. - if !ok || e.NoOnError { + if !ok { s.escalate(ctx, &runningActor[E]{ref: ActorRef{ID: e.ID, SystemID: e.SystemID, Src: e.Src.Name}}, "", err) return } diff --git a/state/invoke.go b/state/invoke.go index 8a3090ac..53096eb2 100644 --- a/state/invoke.go +++ b/state/invoke.go @@ -93,6 +93,16 @@ func (inv *Invocation[S, E, C]) declaresOnError() bool { return inv.hasOnError || inv.OnError != zero } +// declaredOnError is the onError a SpawnActor for inv carries: nil when inv declared +// none, as for a Spawn with none, so its failure escalates rather than firing the zero +// event. +func (inv *Invocation[S, E, C]) declaredOnError() any { + if !inv.declaresOnError() { + return nil + } + return inv.OnError +} + // invocationKnownKeys is the set of JSON keys Invocation models; anything else is // captured into extra and preserved verbatim on round-trip. var invocationKnownKeys = map[string]struct{}{ @@ -267,11 +277,11 @@ func (i *Instance[S, E, C]) invokeEffectsOnExit(exits []S, tr *Trace) []Effect { // first, so a compound state's invokes come before its children's; a parallel // configuration reports every active region's. // -// StartEffects recomputes over the live configuration on every call, so it is -// correct on both Cast (configuration is the initial leaves) and Restore -// (configuration is the restored leaves). The durable runner relies on this: -// after Recover sets up the restored configuration, StartEffects yields exactly -// the invoke/actor starts of the resumed state(s). +// StartEffects recomputes over the live configuration on every call. After a Restore, +// use ResumeEffects instead: StartEffects includes a compound state's services and +// actors, which may already have settled into one of its children, so starting them +// would run them again. The durable runner calls StartEffects after Recover, because it +// tracks which of them settled or ended, and leaves those out. func (i *Instance[S, E, C]) StartEffects() []Effect { var tr Trace active := i.activeStates() diff --git a/state/snapshot.go b/state/snapshot.go index 8906a780..057daeba 100644 --- a/state/snapshot.go +++ b/state/snapshot.go @@ -388,11 +388,11 @@ func (i *Instance[S, E, C]) pendingRefs(cfg []S) PendingRefs { // ResumeEffects returns the re-arm effects a host absorbs after Restore to // re-establish the instance's pending timers, invoked services, and spawned -// actors for its restored configuration: a ScheduleAfter per delayed transition of -// an active leaf state, and a StartService per invoked service and a SpawnActor per -// child-machine actor invocation of every active state, a compound state's included. -// A compound state's own `after` timers aren't re-armed, since the snapshot can't say -// whether one already fired. It is the restore +// actors for its restored configuration: a ScheduleAfter per delayed transition, a +// StartService per invoked service and a SpawnActor per child-machine actor invocation +// of each active leaf state. A compound state's own timers, services and actors aren't +// included, since the snapshot can't say whether a timer already fired into one of its +// children, or a service or actor already settled into one. It is the restore // twin of StartEffects (which arms an initial Cast configuration) extended with // the delayed-timer effects, so a restored instance // re-establishes its invoked/spawned children. Like StartEffects it is a pure From 71a52dac6530cbd7d8b4cfb5eb8d415d45c88ddc Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Mon, 16 Nov 2026 07:10:35 -0700 Subject: [PATCH 34/38] test(state): a restored actor doesn't respawn a nested actor that settled Pins that an actor restored from a snapshot resumes without spawning again a nested actor its earlier start spawned, once that nested actor settled and moved it on, for a nested actor declared on the actor's leaf state and on a compound state. Signed-off-by: Ray Karnes --- state/actor_restore_pending_test.go | 72 +++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 state/actor_restore_pending_test.go diff --git a/state/actor_restore_pending_test.go b/state/actor_restore_pending_test.go new file mode 100644 index 00000000..0352ea5c --- /dev/null +++ b/state/actor_restore_pending_test.go @@ -0,0 +1,72 @@ +package state_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestRestoreActors_DoesNotRespawnANestedActorThatSettled pins that an actor restored +// from a snapshot doesn't spawn a nested actor its earlier start spawned, once that +// nested actor settled and moved the actor on: the restored actor resumes, so the +// spawn its fresh Cast buffered is stale. It covers a nested actor declared on the +// actor's leaf state and on a compound state. +func TestRestoreActors_DoesNotRespawnANestedActorThatSettled(t *testing.T) { + for _, compound := range []bool{false, true} { + ctx := context.Background() + nestedRuns := 0 + cb := state.ForgeFor[*childEntity]("child").Actor("nested") + if compound { + cb = cb.SuperState("p").InvokeActor("nested", state.WithInvokeOnDone("nestedDone"), state.WithInvokeID("nested")). + SubState("a"). + SubState("b"). + Initial("a"). + EndSuperState(). + Initial("p") + } else { + cb = cb.State("a").InvokeActor("nested", state.WithInvokeOnDone("nestedDone"), state.WithInvokeID("nested")). + State("b"). + Initial("a") + } + child := cb.Transition("a").On("nestedDone").GoTo("b"). + Transition("b").On("poke").GoTo("b"). + Quench() + parent := state.ForgeFor[*trec]("parent"). + Actor("child"). + State("supervising").InvokeActor("child", state.WithInvokeID("child")). + Initial("supervising"). + Quench() + register := func(sys *state.ActorSystem[string, string, *trec]) { + sys.Register("child", func(map[string]any) (state.ActorInstance, error) { + return state.NewActor(child.Cast(&childEntity{}, state.WithInitialState("a")), nil), nil + }) + sys.Register("nested", func(in map[string]any) (state.ActorInstance, error) { + nestedRuns++ + return childBehavior()(in) + }) + } + inst := parent.Cast(&trec{}, state.WithInitialState("supervising")) + sys := state.NewActorSystem(inst) + register(sys) + sys.Absorb(ctx, inst.StartEffects()) + if nestedRuns != 1 { + t.Fatalf("compound=%v: nested ran %d times starting, want once", compound, nestedRuns) + } + sys.DeliverByID(ctx, "nested", "finish") + snaps, err := sys.SnapshotActors() + if err != nil { + t.Fatalf("SnapshotActors: %v", err) + } + inst2 := parent.Cast(&trec{}, state.WithInitialState("supervising")) + sys2 := state.NewActorSystem(inst2) + register(sys2) + if err = sys2.RestoreActors(ctx, snaps); err != nil { + t.Fatalf("RestoreActors: %v", err) + } + sys2.DeliverByID(ctx, "child", "poke") + if nestedRuns != 1 { + t.Fatalf("compound=%v: nested ran %d times, want once: the restored child spawned it again", compound, nestedRuns) + } + } +} From 60d2bdb9819f79478e4b606bdb1afe2cedff9eea Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Mon, 16 Nov 2026 08:03:27 -0700 Subject: [PATCH 35/38] revert: keep state's v1 behavior; track compound starts and undeclared onErrors as issues Reverts three changes to state's v1 behavior, so this PR adds to state without changing what it does: - StartEffects covers the active leaves again, as v1 does. A compound state's services and actors don't start at Start or Recover; tracked in #249. Recover's handling of an older checkpoint's compound invokes, which only that widening needed, goes too. - An InvokeActor with no onError fires the zero event again, as v1 documents, rather than escalating. durable tells "none declared" from "refused" by the kernel's refusal reason, a stopgap with known gaps; tracked in #250. - An Invocation's JSON writes onError as before; a declared zero-valued onError is lost through the IR, tracked in #251. The tests for what those changes fixed stay in the PR, skipped with a pointer to the issue. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 23 ++--- durable/actor_driven_drivers_test.go | 1 + durable/actor_lifecycle_test.go | 1 + durable/runner.go | 64 +++--------- durable/service_test.go | 1 + durable/spawn_message_test.go | 1 + durable/spawn_onerror_rule_test.go | 2 + durable/spawn_zero_event_test.go | 2 + state/CHANGELOG.md | 21 ---- state/actor.go | 2 +- state/actor_invoke_undeclared_test.go | 138 ------------------------- state/actor_respawn_lift_test.go | 42 -------- state/actor_restore_pending_test.go | 5 +- state/envelope.go | 16 +-- state/invoke.go | 99 ++++-------------- state/invoke_declares_internal_test.go | 85 --------------- state/kernel.go | 26 +++-- state/options.go | 4 +- state/snapshot.go | 20 ++-- state/start_effects_superstate_test.go | 48 --------- 20 files changed, 73 insertions(+), 528 deletions(-) delete mode 100644 state/actor_invoke_undeclared_test.go delete mode 100644 state/invoke_declares_internal_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 243d0825..2add5718 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -142,12 +142,6 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Fixed -- **`Recover` from an older checkpoint doesn't rerun a compound state's settled service - or actor.** This version starts a compound state's services and actors at `Start` and - `Recover`, which an older one didn't, so it recorded none of them as settled or ended. - `Recover` from a checkpoint an older version wrote put such a service back in flight, - or spawned such an actor, even when it had settled into one of the state's children. - It now counts them as settled or ended, as that version left them. - **`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 @@ -232,8 +226,11 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. already records it, and replay meets it again — so the actor counts as ended and `Recover` leaves it alone. A spawn whose onError a context's ending refused still retries, since the step that drove it records nothing, as does one with no onError - declared, as before. A declared onError the parent has no transition for counts as - refused, so the actor is done. + declared, as before. An invoked actor with no onError fires the zero event, which the + parent refuses as having no transition, and `durable` reads that refusal as "none + declared". So a declared onError the parent has no transition for retries too, and a + wildcard or a transition that takes the zero event counts as caught; #250 tracks a + better way to tell them apart. - **A message an actor sends its parent as it spawns applies once.** A `Fire`, `RunService`, `Start` or `Recover` didn't journal it, and `Recover` spawned the actor again to send it again: it landed after the steps that followed it live, or never, if @@ -263,16 +260,8 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **A delivery journals each parent Fire under the actor that drove it,** where it used to record every one under the actor delivered to. It no longer copies the instance's history twice per delivery to do it. -- **A compound state's services and actors start.** `Start` and `Recover` armed only - those declared on the active leaves, so a service or actor on a compound state didn't - run while one of its children was active. They come from `state.StartEffects`, which - now covers every active state. A journal from before this records no ended actors, - so `Recover` from it also spawns a compound state's actor that had settled, as it - already did for a leaf's. Restoring a checkpoint's timers before the replay walk is - left to a follow-up. - **`Recover` doesn't start a service that settled while its state stayed active.** A - checkpoint taken after such a settle, on a compound state whose onDone went to a child, - or on a leaf state that stayed put, left the service in flight again on recovery, so + checkpoint taken after such a settle, on a state that stayed put, left the service in flight again on recovery, so `RunService` ran it a second time. A checkpoint now records the declared services that settled while their state stayed active, and `Recover` doesn't start them. One that never settled, such as one whose state a `Tick` entered or re-entered (a `Tick` diff --git a/durable/actor_driven_drivers_test.go b/durable/actor_driven_drivers_test.go index 269d10f2..0942bf7e 100644 --- a/durable/actor_driven_drivers_test.go +++ b/durable/actor_driven_drivers_test.go @@ -284,6 +284,7 @@ func TestRecover_KeepsAReplayedActorFiresTimerDeadline(t *testing.T) { // flight, not settled, so Recover starts it: by a checkpoint the live run took, and by // one a recovered Handle took after replaying the run. func TestRecover_StartsAServiceAnActorsMessageReentered(t *testing.T) { + t.Skip("Start and Recover start only the active leaves' services and actors, not a compound state's; #249") ctx := context.Background() m := state.ForgeFor[actorCtx]("relay"). Service("fetch", fetchOK). diff --git a/durable/actor_lifecycle_test.go b/durable/actor_lifecycle_test.go index 25eeba0f..cc5d4008 100644 --- a/durable/actor_lifecycle_test.go +++ b/durable/actor_lifecycle_test.go @@ -398,6 +398,7 @@ func TestRecover_RetriesAnActorWhoseLatestSpawnInAStepFailed(t *testing.T) { // while one of its children is active: Start spawns it, and so does Recover after a // step moved between the children. func TestRecover_SpawnsASuperstatesActor(t *testing.T) { + t.Skip("Start and Recover start only the active leaves' services and actors, not a compound state's; #249") ctx := context.Background() m := state.ForgeFor[actorCtx]("nest"). Actor("spawnChild"). diff --git a/durable/runner.go b/durable/runner.go index 016a409a..36f01ca4 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -690,13 +690,14 @@ func (p *parentFires[S]) inspect(ev state.InspectionEvent) { func (p *parentFires[S]) note(pf state.ParentFire[S]) { p.mu.Lock() p.fires = append(p.fires, pf) - // A failed spawn routes an onError only when one was declared; with none, the system - // escalates and no Fire is noted, so the spawn stays unstarted and Recover retries it. // A spawn whose onError applied, or was refused for a reason other than a context // ending, such as a failing guard, is handled: the journal holds the onError or its // refusal, and a retry would run the behavior again. One a context's ending refused - // isn't: the step that drove it recorded nothing. - if pf.SpawnFailed && !isContextErr(pf.Result.Err) { + // isn't: the step that drove it recorded nothing. Nor is one the parent had no + // transition for: an invoked actor with no onError declared routes the zero event, + // which the parent refuses that way, and nothing caught the failure. Telling the two + // apart by the refusal's reason is a stopgap; see #250. + if pf.SpawnFailed && !isContextErr(pf.Result.Err) && !isNoTransition(pf.Result.Err) { if p.failed == nil { p.failed = map[string]bool{} } @@ -1213,30 +1214,6 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { return &ActorSet{IDs: endedIDs}, &ActorSet{IDs: unstartedIDs} } -// compoundStarts returns, of starts (inst's StartEffects), those of its active compound -// states, the ones that aren't active leaves: what StartEffects covers that an older -// version's, which covered the active leaves alone, didn't. -func compoundStarts[S comparable, E comparable, C any](inst *state.Instance[S, E, C], starts []state.Effect) []state.Effect { - leaves := map[string]bool{} - for _, s := range inst.Configuration() { - leaves[fmt.Sprint(s)] = true - } - var out []state.Effect - for _, eff := range starts { - switch e := eff.(type) { - case state.StartService: - if !leaves[e.State] { - out = append(out, eff) - } - case state.SpawnActor: - if !leaves[e.State] { - out = append(out, eff) - } - } - } - return out -} - // actorSetsCache is the last result actorSets computed, with what it read: the // configuration and the running actors. type actorSetsCache struct { @@ -1371,24 +1348,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // step) can be re-settled from its recorded outcome without re-running it. A // service that had settled by the checkpoint while its state stayed active isn't // armed: it would run again. - // An older version started only the active leaves' services and actors at Start and - // Recover, never a compound state's, so it recorded none of theirs as settled or - // ended. For a checkpoint it wrote, count a compound state's as settled or ended, as - // that version left them, so Recover doesn't run one that already settled into a - // child. restoredStarts := inst.StartEffects() endedServices := env.EndedServices - var olderEndedActors []string - if env.Format < actorArmsFormat { - for _, eff := range compoundStarts(inst, restoredStarts) { - switch e := eff.(type) { - case state.StartService: - endedServices = append(endedServices, e.ID) - case state.SpawnActor: - olderEndedActors = append(olderEndedActors, e.ID) - } - } - } svcBuf := make([]state.JournalEntry, 0) svc := r.newServiceRunner(inst) if svc != nil { @@ -1421,14 +1382,6 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // the checkpoint's, then each tail Record's that records one. Nil means none was // recorded, so Recover spawns every actor the configuration declares. ended := env.EndedActors - if len(olderEndedActors) > 0 { - ids := olderEndedActors - if ended != nil { - ids = append(ids, ended.IDs...) - } - slices.Sort(ids) - ended = &ActorSet{IDs: slices.Compact(ids)} - } // unstarted is the latest recorded set of the declared actors that weren't running // and hadn't ended, recorded alongside ended. Nil means none was recorded. unstarted := env.UnstartedActors @@ -1777,6 +1730,13 @@ func (jsonEventCodec[E]) Decode(payload []byte) (E, error) { return e, err } +// isNoTransition reports whether err is the kernel's refusal of an event the state has +// no transition for, as state's own unexported check reads it. +func isNoTransition(err error) bool { + var it *state.InvalidTransitionError + return errors.As(err, &it) && it.Reason == "no transition declared for this state and event" +} + // isContextErr reports whether err is a context's cancellation or deadline, which a // Store may report for either when the caller's context ends. func isContextErr(err error) bool { diff --git a/durable/service_test.go b/durable/service_test.go index 910ed858..4d29a5d8 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -838,6 +838,7 @@ func TestService_RefusedByADerivedContext_RecordsNothing(t *testing.T) { // Recover, so RunService doesn't run it again: not from the journal, and not from a // checkpoint taken after the settle, where the compound is still active. func TestRecover_DoesNotRearmASuperstatesSettledService(t *testing.T) { + t.Skip("Start and Recover start only the active leaves' services and actors, not a compound state's; #249") ctx := context.Background() // every=-1 runs live with no checkpoint, then checkpoints from each recovered Handle, // so the checkpoint comes from a replay of the settle. diff --git a/durable/spawn_message_test.go b/durable/spawn_message_test.go index 88570cfe..c54d2313 100644 --- a/durable/spawn_message_test.go +++ b/durable/spawn_message_test.go @@ -235,6 +235,7 @@ func (s *sender) Output() any { return nil } // region's state, which declares "v" too. The greeter must already be running there, // so that spawn is a no-op and its journaled hello applies once, across two Recovers. func TestRecover_ARetriedSpawnsMessageDoesNotRestartARunningActor(t *testing.T) { + t.Skip("Start and Recover start only the active leaves' services and actors, not a compound state's; #249") ctx := context.Background() note := func(s string) func(state.AssignCtx[actorCtx]) actorCtx { return func(in state.AssignCtx[actorCtx]) actorCtx { diff --git a/durable/spawn_onerror_rule_test.go b/durable/spawn_onerror_rule_test.go index 50992245..0b7e5644 100644 --- a/durable/spawn_onerror_rule_test.go +++ b/durable/spawn_onerror_rule_test.go @@ -102,12 +102,14 @@ func TestSpawnRule_GuardRefusedOnErrorIsDone(t *testing.T) { } func TestSpawnRule_DeclaredOnErrorWithNoTransitionIsDone(t *testing.T) { + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by the reason string; #250") if got := spawnRuleCalls(t, spawnRuleMachine(false, nil, state.WithInvokeOnError("spawnFailed"))); got != 1 { t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) } } func TestSpawnRule_DenialWordedLikeNoTransitionIsDone(t *testing.T) { + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by the reason string; #250") denial := &state.InvalidTransitionError{Event: "spawnFailed", Reason: "no transition declared for this state and event"} m := spawnRuleMachine(true, denyAs("spawnFailed", denial), state.WithInvokeOnError("spawnFailed")) if got := spawnRuleCalls(t, m); got != 1 { diff --git a/durable/spawn_zero_event_test.go b/durable/spawn_zero_event_test.go index 84302441..14a4050f 100644 --- a/durable/spawn_zero_event_test.go +++ b/durable/spawn_zero_event_test.go @@ -14,6 +14,7 @@ import ( // a transition the parent declares on that event never runs, live or after Recover, // and Recover retries the spawn: nothing declared for the failure caught it. func TestRecover_RetriesANoOnErrorSpawnEvenWhenTheZeroEventHasATransition(t *testing.T) { + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by the reason string; #250") ctx := context.Background() m := state.ForgeFor[stepCtx]("zeroOnError"). Reducer("note", func(in state.AssignCtx[stepCtx]) stepCtx { @@ -63,6 +64,7 @@ func TestRecover_RetriesANoOnErrorSpawnEvenWhenTheZeroEventHasATransition(t *tes // declared is retried at Recover when the parent's state swallows its zero event with a // catch-all or a forbid: nothing declared for the failure caught it. func TestRecover_RetriesANoOnErrorSpawnAWildcardSwallowed(t *testing.T) { + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by the reason string; #250") for _, how := range []string{"forbid any", "on any"} { t.Run(how, func(t *testing.T) { b := state.ForgeFor[stepCtx]("wildcard"). diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 462b078b..25e573e9 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -69,27 +69,6 @@ counts as an additive (minor) versus breaking (major) change. Use the whole system, so a message another goroutine's delivery sent the parent while it ran was dropped. The quiet now rides the call chain that spawns each actor, and ends when `AbsorbRespawn` returns. -- **An invocation's declared onError survives its JSON IR.** An onError that is the - zero event, such as an `iota` enum's first constant, read back as undeclared, and now - escalated. The IR writes the `onError` key only when one was declared and reads a - present key as declared, so IR written before this, which always has the key, keeps - routing the zero event as it did. -- **An invoked actor with no onError escalates its failure.** When an `InvokeActor` - actor with no `WithInvokeOnError` couldn't start, or failed after it ran, the actor - system fired the zero event at the parent, which a wildcard or a transition on that - event could take as if an onError had been declared. Its `SpawnActor` now carries a - nil `OnError`, as a `Spawn` with none does, so it escalates (the G3 default) and fires - nothing. An onError that is itself the zero event, such as the first constant of an - `iota` enum, still counts as declared. A machine that relied - on that zero-event Fire changes behavior. -- **`StartEffects` includes a compound state's invokes.** It looked only at the active - leaves, so a service or actor declared on a compound state wasn't started while one of - its children was active: not at a durable `Start` or `Recover`, and not for a child - actor's own nested actors. It now reports every active state's, ancestors first. - `ResumeEffects` still covers the active leaves alone, timers, services and actors: - after a Restore, a compound state's timer may already have fired into one of its - children, or its service or actor may already have settled into one, and the snapshot - can't say. ## [1.0.0] — 2026-06-13 diff --git a/state/actor.go b/state/actor.go index fbf51925..b7b4b6ee 100644 --- a/state/actor.go +++ b/state/actor.go @@ -241,7 +241,7 @@ func (i *Instance[S, E, C]) actorEffectsOnEntry(entries []S, tr *Trace) []Effect Src: inv.Src, Input: inv.Input, OnDone: inv.OnDone, - OnError: inv.declaredOnError(), + OnError: inv.OnError, State: fmtState(s), SystemID: inv.SystemID, }) diff --git a/state/actor_invoke_undeclared_test.go b/state/actor_invoke_undeclared_test.go deleted file mode 100644 index 8ca5b307..00000000 --- a/state/actor_invoke_undeclared_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package state_test - -import ( - "context" - "errors" - "testing" - - "github.com/stablekernel/crucible/state" -) - -// spawnEffect returns the SpawnActor entering supervising emits for m. -func spawnEffect[E comparable](t *testing.T, m *state.Machine[string, E, *trec], start E) state.SpawnActor { - t.Helper() - res := m.Cast(&trec{}, state.WithInitialState("idle")).Fire(context.Background(), start) - for _, eff := range res.Effects { - if sp, ok := eff.(state.SpawnActor); ok { - return sp - } - } - t.Fatal("entering supervising spawned no actor") - return state.SpawnActor{} -} - -func invokeParent(opts ...state.InvokeOption) *state.Machine[string, string, *trec] { - return state.ForgeFor[*trec]("parent"). - Actor("child"). - State("idle"). - State("supervising").InvokeActor("child", opts...). - Initial("idle"). - Transition("idle").On("start").GoTo("supervising"). - Quench() -} - -// TestInvokeActor_ZeroValueOnError_IsDeclared pins that an onError that is the zero -// event, as the first constant of an iota enum is, still counts as declared. -func TestInvokeActor_ZeroValueOnError_IsDeclared(t *testing.T) { - const ( - failed = iota - start - ) - m := state.Forge[string, int, *trec]("parent"). - Actor("child"). - State("idle"). - State("supervising").InvokeActor("child", state.WithInvokeOnError(failed)). - Initial("idle"). - CurrentStateFn(func(*trec) string { return "idle" }). - Transition("idle").On(start).GoTo("supervising"). - Quench() - if sp := spawnEffect(t, m, start); sp.OnError != failed { - t.Fatalf("SpawnActor.OnError = %#v, want the declared zero-valued onError", sp.OnError) - } -} - -// TestInvokeActor_NoOnError_FailuresEscalate pins that an invoked actor with no onError -// declared escalates its failure, to start or after it ran, as a spawned actor with none -// does (G3), and fires nothing at the parent; one with an onError routes it. -func TestInvokeActor_NoOnError_FailuresEscalate(t *testing.T) { - ctx := context.Background() - for _, declared := range []bool{false, true} { - for _, when := range []string{"at spawn", "after it ran"} { - var opts []state.InvokeOption - if declared { - opts = append(opts, state.WithInvokeOnError("failed")) - } - parent := invokeParent(opts...).Cast(&trec{}, state.WithInitialState("idle")) - var fires []state.ParentFire[string] - cause := errors.New("the child failed") - sys := state.NewActorSystem(parent). - WithParentFireObserver(func(pf state.ParentFire[string]) { fires = append(fires, pf) }) - if when == "at spawn" { - sys.Register("child", func(map[string]any) (state.ActorInstance, error) { return nil, cause }) - } else { - sys.Register("child", childBehavior()) - } - sys.Absorb(ctx, parent.Fire(ctx, "start").Effects) - if when == "after it ran" { - ids := sys.IDs() - if len(ids) != 1 { - t.Fatalf("declared=%v %s: running %v, want the child", declared, when, ids) - } - sys.SettleError(ctx, ids[0], cause) - } - esc := sys.LastEscalation() - if declared { - if len(fires) != 1 || esc != nil { - t.Fatalf("declared=%v %s: parent Fires %d, escalation %v; want the onError routed, no escalation", declared, when, len(fires), esc) - } - continue - } - if len(fires) != 0 || esc == nil || !errors.Is(esc, cause) { - t.Fatalf("declared=%v %s: parent Fires %d, escalation %v; want no Fire and the failure escalated", declared, when, len(fires), esc) - } - } - } -} - -// TestInvokeActor_ZeroValueOnError_SurvivesJSON pins that an InvokeActor whose onError is -// the zero event, such as an iota enum's first constant, still counts as declared after -// the machine goes through its JSON IR, as it does when built. -func TestInvokeActor_ZeroValueOnError_SurvivesJSON(t *testing.T) { - const ( - failed = iota - start - ) - built := state.Forge[string, int, *trec]("parent"). - Actor("child"). - State("idle"). - State("supervising").InvokeActor("child", state.WithInvokeOnError(failed)). - Initial("idle"). - CurrentStateFn(func(*trec) string { return "idle" }). - Transition("idle").On(start).GoTo("supervising"). - Quench() - raw, err := built.ToJSON() - if err != nil { - t.Fatalf("ToJSON: %v", err) - } - ir, err := state.LoadFromJSON[string, int, *trec](raw) - if err != nil { - t.Fatalf("LoadFromJSON: %v", err) - } - loaded := ir.Provide(state.NewRegistry[*trec]()).CurrentStateFn(func(*trec) string { return "idle" }).Quench() - if sp := spawnEffect(t, loaded, start); sp.OnError != failed { - t.Fatalf("SpawnActor.OnError = %#v after the JSON round trip, want the declared zero-valued onError", sp.OnError) - } -} - -// TestInvokeActor_NoOnError_CarriesNoOnErrorEvent pins that the SpawnActor an invoked -// actor with no onError emits carries no OnError, as a Spawn with none does, so a host -// that consumes SpawnActor effects and reads OnError, as its docs describe, escalates -// rather than firing the zero event. -func TestInvokeActor_NoOnError_CarriesNoOnErrorEvent(t *testing.T) { - if sp := spawnEffect(t, invokeParent(), "start"); sp.OnError != nil { - t.Fatalf("SpawnActor.OnError = %#v, want nil for an invoke with no onError", sp.OnError) - } - if sp := spawnEffect(t, invokeParent(state.WithInvokeOnError("failed")), "start"); sp.OnError != "failed" { - t.Fatalf("SpawnActor.OnError = %#v, want the declared failed", sp.OnError) - } -} diff --git a/state/actor_respawn_lift_test.go b/state/actor_respawn_lift_test.go index 62346e78..9880f043 100644 --- a/state/actor_respawn_lift_test.go +++ b/state/actor_respawn_lift_test.go @@ -2,53 +2,11 @@ package state_test import ( "context" - "errors" "testing" "github.com/stablekernel/crucible/state" ) -// TestActorSystem_AbsorbRespawn_ALiftedFireReenteringAStateStartsItsActorOnce pins -// what a lifted parent Fire does to an actor AbsorbRespawn hasn't respawned yet. outer's -// actor fails to start now, which it didn't before, so its onError is a new Fire and is -// heard; that Fire re-enters inner, whose greeter starts there as a new start, and its -// hello reaches the parent once. AbsorbRespawn's own spawn of the greeter then finds it -// running, and doesn't start it, or send its hello, a second time. -func TestActorSystem_AbsorbRespawn_ALiftedFireReenteringAStateStartsItsActorOnce(t *testing.T) { - ctx := context.Background() - m := state.ForgeFor[*trec]("lift"). - Actor("broken"). - Actor("greeter"). - SuperState("outer").InvokeActor("broken", state.WithInvokeOnError("brokenFailed")). - SubState("inner").InvokeActor("greeter"). - Initial("inner"). - EndSuperState(). - Initial("outer"). - Transition("inner").On("brokenFailed").GoTo("inner").Reenter(). - Transition("inner").On("hello").GoTo("inner"). - Quench() - inst := m.Cast(&trec{}, state.WithInitialState("inner")) - var fired []string - sys := state.NewActorSystem(inst). - WithParentFireObserver(func(pf state.ParentFire[string]) { fired = append(fired, pf.Result.Trace.Event) }) - sys.Register("broken", func(map[string]any) (state.ActorInstance, error) { return nil, errors.New("can't start now") }) - starts := 0 - sys.Register("greeter", func(map[string]any) (state.ActorInstance, error) { - starts++ - return &startGreeter{}, nil - }) - sys.AbsorbRespawn(ctx, inst.StartEffects()) - hellos := 0 - for _, ev := range fired { - if ev == "hello" { - hellos++ - } - } - if starts != 1 || hellos != 1 { - t.Fatalf("greeter started %d times and its hello reached the parent %d times (parent Fires %q), want once each", starts, hellos, fired) - } -} - // TestActorSystem_AbsorbRespawn_DoesNotMuteAnotherActorsDelivery pins that the quiet of // an AbsorbRespawn covers only the actors it spawns: a delivery to another actor that // was already running, made while AbsorbRespawn is under way (as another goroutine diff --git a/state/actor_restore_pending_test.go b/state/actor_restore_pending_test.go index 0352ea5c..31544c32 100644 --- a/state/actor_restore_pending_test.go +++ b/state/actor_restore_pending_test.go @@ -10,10 +10,9 @@ import ( // TestRestoreActors_DoesNotRespawnANestedActorThatSettled pins that an actor restored // from a snapshot doesn't spawn a nested actor its earlier start spawned, once that // nested actor settled and moved the actor on: the restored actor resumes, so the -// spawn its fresh Cast buffered is stale. It covers a nested actor declared on the -// actor's leaf state and on a compound state. +// spawn its fresh Cast buffered is stale. func TestRestoreActors_DoesNotRespawnANestedActorThatSettled(t *testing.T) { - for _, compound := range []bool{false, true} { + for _, compound := range []bool{false} { ctx := context.Background() nestedRuns := 0 cb := state.ForgeFor[*childEntity]("child").Actor("nested") diff --git a/state/envelope.go b/state/envelope.go index bedb38fc..0d6bb3cb 100644 --- a/state/envelope.go +++ b/state/envelope.go @@ -132,22 +132,16 @@ func marshalWithExtra(known any, extra map[string]json.RawMessage) ([]byte, erro // target struct owns; any key outside it is captured. A nil result means there // were no unknown keys. func captureExtra(data []byte, knownTarget any, knownKeys map[string]struct{}) (map[string]json.RawMessage, error) { - extra, _, err := captureExtraKeys(data, knownTarget, knownKeys) - return extra, err -} - -// captureExtraKeys is captureExtra that also returns every top-level key data has, -// known or not, so a caller can tell a key that is present from one that is absent -// without parsing data again. The keys are nil when data is not a JSON object. -func captureExtraKeys(data []byte, knownTarget any, knownKeys map[string]struct{}) (extra, all map[string]json.RawMessage, err error) { if err := json.Unmarshal(data, knownTarget); err != nil { - return nil, nil, err + return nil, err } + var all map[string]json.RawMessage if err := json.Unmarshal(data, &all); err != nil { // data was valid for the typed target but is not a JSON object (e.g. null): // there are no extra keys to capture. - return nil, nil, nil //nolint:nilerr // a non-object body simply carries no extras. + return nil, nil //nolint:nilerr // a non-object body simply carries no extras. } + var extra map[string]json.RawMessage for k, v := range all { if _, known := knownKeys[k]; known { continue @@ -157,7 +151,7 @@ func captureExtraKeys(data []byte, knownTarget any, knownKeys map[string]struct{ } extra[k] = v } - return extra, all, nil + return extra, nil } // cloneRawExtra deep-copies a preserved-unknown map so a deep-copied IR node never diff --git a/state/invoke.go b/state/invoke.go index 53096eb2..6dac951b 100644 --- a/state/invoke.go +++ b/state/invoke.go @@ -79,28 +79,6 @@ type Invocation[S comparable, E comparable, C any] struct { // extra preserves unknown JSON keys a newer producer emitted so they survive a // load -> save cycle (forward-compat). Never inspected by the kernel. extra map[string]json.RawMessage - // hasOnError records that an onError was declared, since OnError holds the zero - // event either way: the builder was given WithInvokeOnError, or the JSON it was - // loaded from has the onError key. - hasOnError bool -} - -// declaresOnError reports whether the invocation declared an onError: the builder was -// given WithInvokeOnError, the JSON it was loaded from has the onError key, or, for one -// built some other way, OnError isn't the zero event. -func (inv *Invocation[S, E, C]) declaresOnError() bool { - var zero E - return inv.hasOnError || inv.OnError != zero -} - -// declaredOnError is the onError a SpawnActor for inv carries: nil when inv declared -// none, as for a Spawn with none, so its failure escalates rather than firing the zero -// event. -func (inv *Invocation[S, E, C]) declaredOnError() any { - if !inv.declaresOnError() { - return nil - } - return inv.OnError } // invocationKnownKeys is the set of JSON keys Invocation models; anything else is @@ -111,28 +89,10 @@ var invocationKnownKeys = map[string]struct{}{ } // MarshalJSON encodes an Invocation, merging its preserved unknown keys back in -// with stable key ordering. It writes the onError key only when an onError was -// declared, so a declared zero event survives the round trip and an undeclared one -// isn't read back as declared. +// with stable key ordering. func (inv Invocation[S, E, C]) MarshalJSON() ([]byte, error) { - if inv.declaresOnError() { - type alias Invocation[S, E, C] - return marshalWithExtra(alias(inv), inv.extra) - } - // The fields, in Invocation's order, less onError. - type undeclared struct { - ID string `json:"id,omitempty"` - Src Ref `json:"src"` - Input map[string]any `json:"input,omitempty"` - OnDone E `json:"onDone"` - Kind ActorKind `json:"kind,omitempty"` - SystemID string `json:"systemId,omitempty"` - Meta map[string]any `json:"meta,omitempty"` - } - return marshalWithExtra(undeclared{ - ID: inv.ID, Src: inv.Src, Input: inv.Input, OnDone: inv.OnDone, - Kind: inv.Kind, SystemID: inv.SystemID, Meta: inv.Meta, - }, inv.extra) + type alias Invocation[S, E, C] + return marshalWithExtra(alias(inv), inv.extra) } // UnmarshalJSON decodes an Invocation and captures any unknown keys into extra so @@ -140,15 +100,12 @@ func (inv Invocation[S, E, C]) MarshalJSON() ([]byte, error) { func (inv *Invocation[S, E, C]) UnmarshalJSON(data []byte) error { type alias Invocation[S, E, C] var a alias - extra, keys, err := captureExtraKeys(data, &a, invocationKnownKeys) + extra, err := captureExtra(data, &a, invocationKnownKeys) if err != nil { return err } *inv = Invocation[S, E, C](a) inv.extra = extra - // A document that has the onError key declared one, even as the zero event; one - // from before this field always has it, and keeps routing the zero event. - _, inv.hasOnError = keys["onError"] return nil } @@ -267,43 +224,25 @@ func (i *Instance[S, E, C]) invokeEffectsOnExit(exits []S, tr *Trace) []Effect { return out } -// StartEffects returns the StartService and SpawnActor effects for the invoked -// services and actors declared on every active state, so a host can arm the services -// and actors of the state(s) entered at Cast, the entry that Fire never observes -// because no event drove it. Call it once, right after Cast, and route the effects -// through the same drivers used for Fire's effects. It is a pure read of the +// StartEffects returns the StartService effects for the invoked services declared +// on the instance's initial active configuration, so a host can arm the services +// of the state(s) entered at Cast — the entry that Fire never observes because no +// event drove it. Call it once, right after Cast, and route the effects through +// the same ServiceRunner used for Fire's effects. It is a pure read of the // configuration and emits no IO, consistent with the kernel's effects-as-data -// contract. The active states are each active leaf and its ancestors, outermost -// first, so a compound state's invokes come before its children's; a parallel -// configuration reports every active region's. +// contract. A flat or single-spine instance reports its single starting state's +// services; a parallel initial configuration reports every active region's. // -// StartEffects recomputes over the live configuration on every call. After a Restore, -// use ResumeEffects instead: StartEffects includes a compound state's services and -// actors, which may already have settled into one of its children, so starting them -// would run them again. The durable runner calls StartEffects after Recover, because it -// tracks which of them settled or ended, and leaves those out. +// StartEffects recomputes over the live configuration on every call, so it is +// correct on both Cast (configuration is the initial leaves) and Restore +// (configuration is the restored leaves). The durable runner relies on this: +// after Recover sets up the restored configuration, StartEffects yields exactly +// the invoke/actor starts of the resumed state(s). func (i *Instance[S, E, C]) StartEffects() []Effect { var tr Trace - active := i.activeStates() - out := i.invokeEffectsOnEntry(active, &tr) - out = append(out, i.actorEffectsOnEntry(active, &tr)...) - return out -} - -// activeStates returns every active state: each active leaf's ancestors, outermost -// first, then the leaf, each state once, in the configuration's order. -func (i *Instance[S, E, C]) activeStates() []S { - var out []S - seen := map[S]bool{} - for _, leaf := range i.Configuration() { - chain := i.machine.ancestors(leaf) - for k := len(chain) - 1; k >= 0; k-- { - if s := chain[k]; !seen[s] { - seen[s] = true - out = append(out, s) - } - } - } + cfg := i.Configuration() + out := i.invokeEffectsOnEntry(cfg, &tr) + out = append(out, i.actorEffectsOnEntry(cfg, &tr)...) return out } diff --git a/state/invoke_declares_internal_test.go b/state/invoke_declares_internal_test.go deleted file mode 100644 index 241b61cb..00000000 --- a/state/invoke_declares_internal_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package state - -import ( - "encoding/json" - "reflect" - "strings" - "testing" -) - -// TestDeclaresOnError_NoPanicOnAnUncomparableEvent pins that declaresOnError, for an -// invocation loaded from JSON (no builder flag), doesn't panic when its event type is an -// interface holding an uncomparable value, as a JSON array decodes to, and reads such -// an onError as declared and the zero event as not. -func TestDeclaresOnError_NoPanicOnAnUncomparableEvent(t *testing.T) { - loaded := Invocation[string, any, int]{OnError: []any{1.0}} - if !loaded.declaresOnError() { - t.Fatal("an onError holding a JSON array reads as not declared") - } - if zero := (Invocation[string, any, int]{}); zero.declaresOnError() { - t.Fatal("a nil onError reads as declared") - } - if typed := (Invocation[string, int, int]{OnError: 0}); typed.declaresOnError() { - t.Fatal("a loaded int onError of 0 reads as declared") - } - if built := (Invocation[string, int, int]{OnError: 0, hasOnError: true}); !built.declaresOnError() { - t.Fatal("a built onError of 0 reads as not declared") - } -} - -// TestInvocation_UndeclaredOnErrorKeepsEveryOtherField pins that an invocation with no -// onError declared, which MarshalJSON writes without the onError key, still writes every -// other field: each exported field of Invocation, found by reflection, so a field added -// later is covered too. -func TestInvocation_UndeclaredOnErrorKeepsEveryOtherField(t *testing.T) { - inv := Invocation[string, string, int]{} - v := reflect.ValueOf(&inv).Elem() - typ := v.Type() - for i := 0; i < typ.NumField(); i++ { - f := typ.Field(i) - if !f.IsExported() || f.Name == "OnError" { - continue - } - fv := v.Field(i) - switch fv.Kind() { - case reflect.String: - fv.SetString("x") - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - fv.SetInt(1) - case reflect.Map: - fv.Set(reflect.MakeMapWithSize(fv.Type(), 1)) - fv.SetMapIndex(reflect.ValueOf("k"), reflect.ValueOf(any("v"))) - case reflect.Struct: - if f.Type == reflect.TypeOf(Ref{}) { - fv.Set(reflect.ValueOf(Ref{Name: "x"})) - } - default: - t.Fatalf("field %s has kind %s: teach this test to fill it", f.Name, fv.Kind()) - } - } - raw, err := json.Marshal(inv) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - var keys map[string]json.RawMessage - if err := json.Unmarshal(raw, &keys); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for i := 0; i < typ.NumField(); i++ { - f := typ.Field(i) - if !f.IsExported() { - continue - } - name := strings.Split(f.Tag.Get("json"), ",")[0] - _, present := keys[name] - if f.Name == "OnError" { - if present { - t.Fatal("an undeclared onError was written") - } - continue - } - if !present { - t.Fatalf("field %s (%q) is missing from the JSON of an invocation with no onError declared: %s", f.Name, name, raw) - } - } -} diff --git a/state/kernel.go b/state/kernel.go index d6cf127e..bb4e43e1 100644 --- a/state/kernel.go +++ b/state/kernel.go @@ -995,12 +995,11 @@ func (b *Builder[S, E, C]) Invoke(src string, opts ...InvokeOption) *Builder[S, o(&cfg) } b.curState.state.Invoke = append(b.curState.state.Invoke, Invocation[S, E, C]{ - ID: cfg.id, - Src: Ref{Name: src, Params: cfg.params}, - Input: cfg.input, - OnDone: invokeOutcome[E](cfg.onDone, cfg.hasOnDone), - OnError: invokeOutcome[E](cfg.onError, cfg.hasOnError), - hasOnError: cfg.hasOnError, + ID: cfg.id, + Src: Ref{Name: src, Params: cfg.params}, + Input: cfg.input, + OnDone: invokeOutcome[E](cfg.onDone, cfg.hasOnDone), + OnError: invokeOutcome[E](cfg.onError, cfg.hasOnError), }) return b } @@ -1040,14 +1039,13 @@ func (b *Builder[S, E, C]) InvokeActor(src string, opts ...InvokeOption) *Builde o(&cfg) } b.curState.state.Invoke = append(b.curState.state.Invoke, Invocation[S, E, C]{ - ID: cfg.id, - Src: Ref{Name: src, Params: cfg.params}, - Input: cfg.input, - OnDone: invokeOutcome[E](cfg.onDone, cfg.hasOnDone), - OnError: invokeOutcome[E](cfg.onError, cfg.hasOnError), - Kind: ActorKindMachine, - SystemID: cfg.systemID, - hasOnError: cfg.hasOnError, + ID: cfg.id, + Src: Ref{Name: src, Params: cfg.params}, + Input: cfg.input, + OnDone: invokeOutcome[E](cfg.onDone, cfg.hasOnDone), + OnError: invokeOutcome[E](cfg.onError, cfg.hasOnError), + Kind: ActorKindMachine, + SystemID: cfg.systemID, }) return b } diff --git a/state/options.go b/state/options.go index e4d22288..74d01403 100644 --- a/state/options.go +++ b/state/options.go @@ -105,9 +105,7 @@ func WithInvokeOnDone[E comparable](onDone E) InvokeOption { // WithInvokeOnError sets the event the host re-fires through Fire when an invoked // service fails (or, for InvokeActor, when the child machine fails), routing the // error through an ordinary transition from the owning state. Omitting it leaves -// the invocation's OnError at the zero event; for InvokeActor, the child's failure then -// escalates, as a Spawn with no onError does, and no event is fired. It mirrors -// WithSpawnOnError. +// the invocation's OnError at the zero event. It mirrors WithSpawnOnError. func WithInvokeOnError[E comparable](onError E) InvokeOption { return func(c *invokeConfig) { c.onError = onError diff --git a/state/snapshot.go b/state/snapshot.go index 057daeba..4bcbf732 100644 --- a/state/snapshot.go +++ b/state/snapshot.go @@ -388,11 +388,9 @@ func (i *Instance[S, E, C]) pendingRefs(cfg []S) PendingRefs { // ResumeEffects returns the re-arm effects a host absorbs after Restore to // re-establish the instance's pending timers, invoked services, and spawned -// actors for its restored configuration: a ScheduleAfter per delayed transition, a -// StartService per invoked service and a SpawnActor per child-machine actor invocation -// of each active leaf state. A compound state's own timers, services and actors aren't -// included, since the snapshot can't say whether a timer already fired into one of its -// children, or a service or actor already settled into one. It is the restore +// actors for its restored configuration: a ScheduleAfter per pending delayed +// transition, a StartService per invoked service, and a SpawnActor per +// child-machine actor invocation active in the configuration. It is the restore // twin of StartEffects (which arms an initial Cast configuration) extended with // the delayed-timer effects, so a restored instance // re-establishes its invoked/spawned children. Like StartEffects it is a pure @@ -417,14 +415,10 @@ func (i *Instance[S, E, C]) pendingRefs(cfg []S) PendingRefs { // post-1.0 ADDITIVE item, not a v1.0 contract. func (i *Instance[S, E, C]) ResumeEffects() []Effect { var tr Trace - // Everything comes from the active leaves only: a compound state's `after` timer - // may already have fired into one of its children, and its service or actor may - // already have settled into one, and a snapshot can't say which, so re-arming or - // starting it again would fire or run it a second time. - leaves := i.Configuration() - out := i.afterEffectsOnEntry(leaves, &tr) - out = append(out, i.invokeEffectsOnEntry(leaves, &tr)...) - out = append(out, i.actorEffectsOnEntry(leaves, &tr)...) + cfg := i.Configuration() + out := i.afterEffectsOnEntry(cfg, &tr) + out = append(out, i.invokeEffectsOnEntry(cfg, &tr)...) + out = append(out, i.actorEffectsOnEntry(cfg, &tr)...) return out } diff --git a/state/start_effects_superstate_test.go b/state/start_effects_superstate_test.go index fd0830d3..a449e887 100644 --- a/state/start_effects_superstate_test.go +++ b/state/start_effects_superstate_test.go @@ -8,54 +8,6 @@ import ( "github.com/stablekernel/crucible/state" ) -// TestStartEffects_IncludesTheSuperstatesInvokes proves StartEffects and ResumeEffects -// report the services and actors a compound state declares while one of its children -// is active, the compound state's before its child's. -func TestStartEffects_IncludesTheSuperstatesInvokes(t *testing.T) { - svc := func(context.Context, state.ServiceCtx[*trec]) (any, error) { return nil, nil } - m := state.ForgeFor[*trec]("nest"). - Service("outerSvc", svc). - Service("innerSvc", svc). - Actor("outerActor"). - SuperState("outer").Invoke("outerSvc").InvokeActor("outerActor"). - SubState("inner").Invoke("innerSvc"). - Initial("inner"). - EndSuperState(). - Initial("outer"). - Quench() - inst := m.Cast(&trec{}, state.WithInitialState("inner")) - var services, actors []string - for _, eff := range inst.StartEffects() { - switch e := eff.(type) { - case state.StartService: - services = append(services, e.Src.Name) - case state.SpawnActor: - actors = append(actors, e.Src.Name) - } - } - if len(services) != 2 || services[0] != "outerSvc" || services[1] != "innerSvc" { - t.Fatalf("services = %v, want [outerSvc innerSvc]", services) - } - if len(actors) != 1 || actors[0] != "outerActor" { - t.Fatalf("actors = %v, want [outerActor]", actors) - } - // ResumeEffects, after a Restore, covers the active leaves alone: a compound state's - // service or actor may already have settled into a child, which a snapshot can't - // tell (TestResumeEffects_DoesNotRestartACompoundServiceThatSettledIntoAChild). - var resumed []string - for _, eff := range inst.ResumeEffects() { - switch e := eff.(type) { - case state.StartService: - resumed = append(resumed, e.Src.Name) - case state.SpawnActor: - resumed = append(resumed, e.Src.Name) - } - } - if len(resumed) != 1 || resumed[0] != "innerSvc" { - t.Fatalf("ResumeEffects starts %v, want the leaf's [innerSvc]", resumed) - } -} - // TestResumeEffects_DoesNotRearmASuperstatesTimer proves ResumeEffects re-arms an // active leaf's `after` timer but not a compound state's: here the compound's timer // already fired into one of its children, so re-arming it after Restore would fire it From c9d083fa5ea00f49ca6bade31a14429ad5835d31 Mon Sep 17 00:00:00 2001 From: Joshua Temple Date: Mon, 16 Nov 2026 11:49:51 -0500 Subject: [PATCH 36/38] fix(state): export ErrNoTransition for durable's no-transition check - InvalidTransitionError.Is matches ErrNoTransition only for the kernel's own refusal - durable drops its copy of the reason-string check - a host refusal worded like the kernel's now counts as handled; unskip its test --- durable/CHANGELOG.md | 9 ++-- durable/runner.go | 11 +---- durable/spawn_onerror_rule_test.go | 3 +- durable/spawn_zero_event_test.go | 4 +- state/CHANGELOG.md | 3 ++ state/errors.go | 25 ++++++++++ state/fire.go | 14 +----- state/no_transition_test.go | 73 ++++++++++++++++++++++++++++++ state/parallel.go | 6 +-- 9 files changed, 114 insertions(+), 34 deletions(-) create mode 100644 state/no_transition_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 2add5718..a038a776 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -227,10 +227,11 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. `Recover` leaves it alone. A spawn whose onError a context's ending refused still retries, since the step that drove it records nothing, as does one with no onError declared, as before. An invoked actor with no onError fires the zero event, which the - parent refuses as having no transition, and `durable` reads that refusal as "none - declared". So a declared onError the parent has no transition for retries too, and a - wildcard or a transition that takes the zero event counts as caught; #250 tracks a - better way to tell them apart. + parent refuses as having no transition, and `durable` reads that refusal + (`state.ErrNoTransition`) as "none declared". So a declared onError the parent has no + transition for retries too, and a wildcard or a transition that takes the zero event + counts as caught; #250 tracks a better way to tell them apart. A host refusal worded + like the kernel's counts as handled. - **A message an actor sends its parent as it spawns applies once.** A `Fire`, `RunService`, `Start` or `Recover` didn't journal it, and `Recover` spawned the actor again to send it again: it landed after the steps that followed it live, or never, if diff --git a/durable/runner.go b/durable/runner.go index 36f01ca4..c42b9e19 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -696,8 +696,8 @@ func (p *parentFires[S]) note(pf state.ParentFire[S]) { // isn't: the step that drove it recorded nothing. Nor is one the parent had no // transition for: an invoked actor with no onError declared routes the zero event, // which the parent refuses that way, and nothing caught the failure. Telling the two - // apart by the refusal's reason is a stopgap; see #250. - if pf.SpawnFailed && !isContextErr(pf.Result.Err) && !isNoTransition(pf.Result.Err) { + // apart by a no-transition refusal is a stopgap; see #250. + if pf.SpawnFailed && !isContextErr(pf.Result.Err) && !errors.Is(pf.Result.Err, state.ErrNoTransition) { if p.failed == nil { p.failed = map[string]bool{} } @@ -1730,13 +1730,6 @@ func (jsonEventCodec[E]) Decode(payload []byte) (E, error) { return e, err } -// isNoTransition reports whether err is the kernel's refusal of an event the state has -// no transition for, as state's own unexported check reads it. -func isNoTransition(err error) bool { - var it *state.InvalidTransitionError - return errors.As(err, &it) && it.Reason == "no transition declared for this state and event" -} - // isContextErr reports whether err is a context's cancellation or deadline, which a // Store may report for either when the caller's context ends. func isContextErr(err error) bool { diff --git a/durable/spawn_onerror_rule_test.go b/durable/spawn_onerror_rule_test.go index 0b7e5644..8e73d765 100644 --- a/durable/spawn_onerror_rule_test.go +++ b/durable/spawn_onerror_rule_test.go @@ -102,14 +102,13 @@ func TestSpawnRule_GuardRefusedOnErrorIsDone(t *testing.T) { } func TestSpawnRule_DeclaredOnErrorWithNoTransitionIsDone(t *testing.T) { - t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by the reason string; #250") + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by a no-transition refusal; #250") if got := spawnRuleCalls(t, spawnRuleMachine(false, nil, state.WithInvokeOnError("spawnFailed"))); got != 1 { t.Fatalf("behavior ran %d times, want Recover to leave it alone", got) } } func TestSpawnRule_DenialWordedLikeNoTransitionIsDone(t *testing.T) { - t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by the reason string; #250") denial := &state.InvalidTransitionError{Event: "spawnFailed", Reason: "no transition declared for this state and event"} m := spawnRuleMachine(true, denyAs("spawnFailed", denial), state.WithInvokeOnError("spawnFailed")) if got := spawnRuleCalls(t, m); got != 1 { diff --git a/durable/spawn_zero_event_test.go b/durable/spawn_zero_event_test.go index 14a4050f..1bb89513 100644 --- a/durable/spawn_zero_event_test.go +++ b/durable/spawn_zero_event_test.go @@ -14,7 +14,7 @@ import ( // a transition the parent declares on that event never runs, live or after Recover, // and Recover retries the spawn: nothing declared for the failure caught it. func TestRecover_RetriesANoOnErrorSpawnEvenWhenTheZeroEventHasATransition(t *testing.T) { - t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by the reason string; #250") + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by a no-transition refusal; #250") ctx := context.Background() m := state.ForgeFor[stepCtx]("zeroOnError"). Reducer("note", func(in state.AssignCtx[stepCtx]) stepCtx { @@ -64,7 +64,7 @@ func TestRecover_RetriesANoOnErrorSpawnEvenWhenTheZeroEventHasATransition(t *tes // declared is retried at Recover when the parent's state swallows its zero event with a // catch-all or a forbid: nothing declared for the failure caught it. func TestRecover_RetriesANoOnErrorSpawnAWildcardSwallowed(t *testing.T) { - t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by the reason string; #250") + t.Skip("an InvokeActor with no onError fires the zero event, so durable tells none declared from refused by a no-transition refusal; #250") for _, how := range []string{"forbid any", "on any"} { t.Run(how, func(t *testing.T) { b := state.ForgeFor[stepCtx]("wildcard"). diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 25e573e9..6617e6a6 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -13,6 +13,9 @@ counts as an additive (minor) versus breaking (major) change. Use the ### Added +- **`ErrNoTransition`** matches, with `errors.Is`, the `*InvalidTransitionError` a `Fire` + returns when the active configuration declares no transition for the event, and no + host-built error with the same `Reason`. It's additive, within v1.1.0. - **`ActorSystem.WithParentFireObserver`** calls a function with each parent Fire the system drives (a `ParentFire`: its result, refused ones included, the actor it came from, whether it settled that actor, with its output or error, and whether it routed diff --git a/state/errors.go b/state/errors.go index 1ac786c6..0e8c9f2d 100644 --- a/state/errors.go +++ b/state/errors.go @@ -1,6 +1,7 @@ package state import ( + "errors" "fmt" "strings" "time" @@ -18,6 +19,30 @@ type InvalidTransitionError struct { To string Event string Reason string + + // noTransition marks the kernel's own refusal of an event the active + // configuration declares no transition for, which ErrNoTransition matches. + noTransition bool +} + +// ErrNoTransition matches, with errors.Is, the *InvalidTransitionError a Fire +// returns when the active configuration declares no transition for the event. It +// matches only the kernel's own refusal, not one a host builds with the same Reason. +var ErrNoTransition = errors.New("crucible/state: no transition declared for this state and event") + +// noTransitionReason is the Reason of the kernel's no-transition refusal. +const noTransitionReason = "no transition declared for this state and event" + +// newNoTransitionError returns the kernel's refusal of event in from, which has no +// transition declared for it. +func newNoTransitionError(from, event string) *InvalidTransitionError { + return &InvalidTransitionError{From: from, Event: event, Reason: noTransitionReason, noTransition: true} +} + +// Is reports whether target is ErrNoTransition and e is the kernel's no-transition +// refusal. +func (e *InvalidTransitionError) Is(target error) bool { + return target == ErrNoTransition && e.noTransition } func (e *InvalidTransitionError) Error() string { diff --git a/state/fire.go b/state/fire.go index ae3706bf..3168cc4f 100644 --- a/state/fire.go +++ b/state/fire.go @@ -604,13 +604,7 @@ func microstepOverflow[S comparable](res FireResult[S], state S) FireResult[S] { // isNoTransition reports whether err is the "no transition declared" outcome — // the benign result of a raised event the current configuration does not handle. -func isNoTransition(err error) bool { - var it *InvalidTransitionError - if as(err, &it) { - return it.Reason == "no transition declared for this state and event" - } - return false -} +func isNoTransition(err error) bool { return errors.Is(err, ErrNoTransition) } // fireOnce is the pure single-event transition step. It resolves the event // against the active configuration child-first, bubbling up through ancestors, @@ -750,11 +744,7 @@ func (i *Instance[S, E, C]) fireSpine(ctx context.Context, event E, tr Trace) Fi return FireResult[S]{NewState: from, Trace: tr, Err: lastGuardErr} } - err := &InvalidTransitionError{ - From: fmtState(from), - Event: fmt.Sprint(event), - Reason: "no transition declared for this state and event", - } + err := newNoTransitionError(fmtState(from), fmt.Sprint(event)) return FireResult[S]{NewState: from, Trace: tr, Err: err} } diff --git a/state/no_transition_test.go b/state/no_transition_test.go new file mode 100644 index 00000000..b108e74e --- /dev/null +++ b/state/no_transition_test.go @@ -0,0 +1,73 @@ +package state_test + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// TestErrNoTransition_MatchesOnlyTheKernelsOwnRefusal pins that errors.Is(err, +// ErrNoTransition) is true for the refusal a Fire returns when the active +// configuration declares no transition for the event, flat or parallel, wrapped or +// not, and false for any other error, including a host-built InvalidTransitionError +// worded the same way. +func TestErrNoTransition_MatchesOnlyTheKernelsOwnRefusal(t *testing.T) { + ctx := context.Background() + flat := state.ForgeFor[acct]("flat"). + State("a"). + State("b").Final(). + Initial("a"). + Transition("a").On("go").GoTo("b"). + Quench() + parallel := state.ForgeFor[acct]("par"). + SuperState("live"). + Region("r1"). + Initial("r1a"). + SubState("r1a").On("tick").GoTo("r1b"). + SubState("r1b"). + EndRegion(). + Region("r2"). + Initial("r2a"). + SubState("r2a"). + EndRegion(). + EndSuperState(). + Initial("live"). + Quench() + flatErr := flat.Cast(acct{}, state.WithInitialState[string]("a")).Fire(ctx, "nope").Err + parErr := parallel.Cast(acct{}, state.WithInitialState[string]("live")).Fire(ctx, "nope").Err + final := flat.Cast(acct{}, state.WithInitialState[string]("a")) + if res := final.Fire(ctx, "go"); res.Err != nil { + t.Fatalf("Fire(go): %v", res.Err) + } + finalErr := final.Fire(ctx, "go").Err + + cases := []struct { + name string + err error + want bool + }{ + {"flat no transition", flatErr, true}, + {"parallel no transition", parErr, true}, + {"wrapped", fmt.Errorf("host: %w", flatErr), true}, + {"other refusal", finalErr, false}, + {"lookalike", &state.InvalidTransitionError{Event: "nope", Reason: "no transition declared for this state and event"}, false}, + {"nil", nil, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if tc.want && tc.err == nil { + t.Fatal("the Fire returned no error") + } + if got := errors.Is(tc.err, state.ErrNoTransition); got != tc.want { + t.Fatalf("errors.Is(%v, ErrNoTransition) = %v, want %v", tc.err, got, tc.want) + } + }) + } + var it *state.InvalidTransitionError + if !errors.As(flatErr, &it) || it.Reason == "" { + t.Fatalf("the refusal %v is no longer an *InvalidTransitionError with a Reason", flatErr) + } +} diff --git a/state/parallel.go b/state/parallel.go index 99e10928..a8f17b15 100644 --- a/state/parallel.go +++ b/state/parallel.go @@ -644,10 +644,6 @@ func (i *Instance[S, E, C]) fireFromState(ctx context.Context, start S, event E, } } - err := &InvalidTransitionError{ - From: fmtState(from), - Event: fmt.Sprint(event), - Reason: "no transition declared for this state and event", - } + err := newNoTransitionError(fmtState(from), fmt.Sprint(event)) return FireResult[S]{NewState: from, Trace: tr, Err: err} } From 00c905898a0df99d2659e85bb4128ba6fdfb8864 Mon Sep 17 00:00:00 2001 From: Joshua Temple Date: Mon, 16 Nov 2026 11:56:18 -0500 Subject: [PATCH 37/38] perf(durable): key the actor-set cache on the configuration slice - compare []S with slices.Equal instead of fmt.Sprint per step - idle step with three actors: 35 to 32 allocs, 4088 to 4032 B/op - add BenchmarkHandle_Fire_ActorIdleStep --- durable/bench_test.go | 39 +++++++++++++++++++++++++++++++++++++++ durable/runner.go | 12 ++++++------ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/durable/bench_test.go b/durable/bench_test.go index 4b474f9a..0562721d 100644 --- a/durable/bench_test.go +++ b/durable/bench_test.go @@ -80,3 +80,42 @@ func BenchmarkMemStore_Append(b *testing.B) { } } } + +// BenchmarkHandle_Fire_ActorIdleStep measures what a machine that declares actors pays +// on a step that touches none: the actor sets the step records come from a cache, so +// the difference from the no-actor case is the cache check. +func BenchmarkHandle_Fire_ActorIdleStep(b *testing.B) { + ctx := context.Background() + for _, tc := range []struct { + name string + actors bool + }{{"noActors", false}, {"threeActors", true}} { + b.Run(tc.name, func(b *testing.B) { + bl := state.ForgeFor[stepCtx]("cost") + if tc.actors { + bl = bl.Actor("a").Actor("b").Actor("c") + } + bl = bl.State("working") + if tc.actors { + bl = bl.InvokeActor("a").InvokeActor("b").InvokeActor("c") + } + m := bl.Initial("working").Transition("working").On("poke").GoTo("working").Quench() + var opts []stepOption + if tc.actors { + beh := func(map[string]any) (state.ActorInstance, error) { return &reentryGreeter{sent: true}, nil } + opts = append(opts, durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{"a": beh, "b": beh, "c": beh})) + } + h, err := durable.NewRunner(m, durable.NewMemStore(), opts...).Start(ctx, "cost", stepCtx{}, state.WithInitialState("working")) + if err != nil { + b.Fatalf("Start: %v", err) + } + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if _, err := h.Fire(ctx, "poke"); err != nil { + b.Fatalf("Fire: %v", err) + } + } + }) + } +} diff --git a/durable/runner.go b/durable/runner.go index c42b9e19..aa6573f8 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -144,7 +144,7 @@ type Handle[S comparable, E comparable, C any] struct { ended recordedSet // the ended actors the journal last recorded unstarted recordedSet // the unstarted actors the journal last recorded seen map[string]bool // declared actors seen running, so a stopped one counts as ended - sets actorSetsCache // the last actorSets result, reused while nothing it reads changed + sets actorSetsCache[S] // the last actorSets result, reused while nothing it reads changed pending []state.ParentFire[S] // parent Fires Start's or Recover's spawns drove, journaled with the next step actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step @@ -1176,13 +1176,13 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { // The sets depend on the declared actors, so on the configuration, on which are // running, and on this step's spawns. A step that changed none of them, as most // steps that touch no actor don't, gets the last result back. - config := fmt.Sprint(h.inst.Configuration()) + config := h.inst.Configuration() if h.sets.valid && len(attempted) == 0 && len(spawned) == 0 && len(failed) == 0 && - config == h.sets.config && slices.Equal(running, h.sets.running) { + slices.Equal(config, h.sets.config) && slices.Equal(running, h.sets.running) { return h.sets.ended, h.sets.unstarted } defer func() { - h.sets = actorSetsCache{valid: true, config: config, running: running, ended: ended, unstarted: unstarted} + h.sets = actorSetsCache[S]{valid: true, config: config, running: running, ended: ended, unstarted: unstarted} }() endedIDs, unstartedIDs := []string{}, []string{} for _, id := range declaredActors(h.inst.StartEffects()) { @@ -1216,9 +1216,9 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { // actorSetsCache is the last result actorSets computed, with what it read: the // configuration and the running actors. -type actorSetsCache struct { +type actorSetsCache[S comparable] struct { valid bool - config string + config []S running []string ended, unstarted *ActorSet } From 72975970e4e5744913f34db94f471d732252eb54 Mon Sep 17 00:00:00 2001 From: Joshua Temple Date: Mon, 16 Nov 2026 12:32:42 -0500 Subject: [PATCH 38/38] fix(durable): keep a running actor whose respawn fails out of the unstarted set - Mark Recover's quiet respawns so a failed one stays in neither actor set - Next Recover respawns it quietly, so its start message applies once - Cover zero-event, no-onError and context-ended respawn failures --- durable/CHANGELOG.md | 3 + durable/recover_respawn_failure_test.go | 188 ++++++++++++++++++++++++ durable/runner.go | 100 +++++++++---- durable/store.go | 6 +- 4 files changed, 269 insertions(+), 28 deletions(-) create mode 100644 durable/recover_respawn_failure_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index a038a776..60405754 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -149,6 +149,9 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **A step that touches no actor doesn't recompute the actor sets.** Each append rebuilt the declared actors from every active state; it now reuses the last sets while the configuration, the running actors and the step's spawns are unchanged. +- **A running actor whose respawn fails isn't recorded as unstarted.** A failed `Recover` + respawn with no onError to catch it made the next `Recover` spawn the actor as new, so + its start message applied twice. It now stays out of both sets and respawns quietly. - **A chained timer's deadline is the one the scheduler armed it at.** A `Tick` recorded the deadline of a timer its fired transition chained from the tick's last clock read, which is later than the read the scheduler armed it at. With a real clock, a checkpoint diff --git a/durable/recover_respawn_failure_test.go b/durable/recover_respawn_failure_test.go new file mode 100644 index 00000000..aedc2ae8 --- /dev/null +++ b/durable/recover_respawn_failure_test.go @@ -0,0 +1,188 @@ +package durable_test + +// The Recover tests for a running actor whose respawn fails: the journal already holds +// every parent Fire its start drove, so it stays running in the journal, and a later +// Recover spawns it again quietly rather than as new. + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// flakyGreeterPalette binds a greeter that fails to start while *fail is set, and the +// finisher. +func flakyGreeterPalette(fail *bool, opts ...greetOption) []greetOption { + palette := durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { + if *fail { + return nil, errors.New("the greeter can't start yet") + } + return &greeter{}, nil + }, + "spawnChild": finishingChild(), + }) + return append([]greetOption{palette}, opts...) +} + +// TestRecover_ARunningActorWhoseRespawnFailsStaysRunning proves a greeter that was +// running, whose respawn fails at one or more Recovers with no onError to catch it, +// stays running in the journal, with and without checkpoints: the next Recover spawns +// it again without sending its hello, so the hello applies once. +func TestRecover_ARunningActorWhoseRespawnFailsStaysRunning(t *testing.T) { + ctx := context.Background() + for _, every := range []int{0, 1} { + for _, failures := range []int{1, 2} { + t.Run(fmt.Sprintf("every=%d/failures=%d", every, failures), func(t *testing.T) { + fail := false + var extra []greetOption + if every > 0 { + extra = append(extra, durable.WithCheckpointEvery[string, string, actorCtx](every)) + } + opts := flakyGreeterPalette(&fail, extra...) + m := greetMachine(false) + store, id := durable.NewMemStore(), durable.InstanceID("respawn-fails") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("greeting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + wantHellos(t, "live", h) + + fail = true + for round := 1; round <= failures; round++ { + failed, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d with the greeter failing: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d with the greeter failing", round), failed) + if _, err = failed.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover %d: %v", round, err) + } + } + + fail = false + for round := 1; round <= 2; round++ { + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover %d with the greeter starting: %v", round, err) + } + wantHellos(t, fmt.Sprintf("Recover %d with the greeter starting", round), recovered) + if _, err = recovered.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after the greeter started again: %v", err) + } + } + }) + } + } +} + +// anyGreetMachine is greetMachine(false)'s greeting state for a machine whose events +// are interfaces, so its invoke's onError is nil rather than the zero event, and a +// failed spawn escalates with no parent Fire. +func anyGreetMachine() *state.Machine[string, any, actorCtx] { + return state.Forge[string, any, actorCtx]("anyGreet"). + Reducer("noteHello", func(in state.AssignCtx[actorCtx]) actorCtx { + c := in.Entity + c.Notes = append(c.Notes, "hello") + return c + }). + Actor("greeter"). + State("greeting").InvokeActor("greeter"). + Initial("greeting"). + Transition("greeting").On("hello").GoTo("greeting").Assign("noteHello"). + Transition("greeting").On("poke").GoTo("greeting"). + Quench() +} + +// hellosAfterAFailedRespawn runs a greeter live in m's greeting, then Recovers on +// failCtx with the greeter's behavior returning fail's error, steps that Handle with +// poke when the Recover succeeds, and returns the hellos a last Recover, with the +// greeter starting, holds. +func hellosAfterAFailedRespawn[E comparable](t *testing.T, m *state.Machine[string, E, actorCtx], poke E, failCtx context.Context, fail func() error) int { + t.Helper() + ctx := context.Background() + failing := false + opts := []durable.Option[string, E, actorCtx]{durable.WithActorPalette[string, E, actorCtx](map[string]state.ActorBehavior{ + "greeter": func(map[string]any) (state.ActorInstance, error) { + if failing { + return nil, fail() + } + return &greeter{}, nil + }, + })} + store, id := durable.NewMemStore(), durable.InstanceID("respawn-failure") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState("greeting")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, poke); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + + failing = true + if failed, recoverErr := durable.Recover(failCtx, m, store, id, opts...); recoverErr == nil { + // The Handle outlives the Recover's context: its next step journals what it holds. + if _, err = failed.Fire(ctx, poke); err != nil { + t.Fatalf("Fire(poke) after the failed respawn: %v", err) + } + } else if !errors.Is(recoverErr, failCtx.Err()) || failCtx.Err() == nil { + t.Fatalf("Recover with the greeter failing = %v, want success, or the error of its ended context", recoverErr) + } + + failing = false + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover with the greeter starting: %v", err) + } + hellos := 0 + for _, n := range recovered.Instance().Entity().Notes { + if n == "hello" { + hellos++ + } + } + return hellos +} + +// TestRecover_ARunningActorWhoseRespawnEscalatesStaysRunning proves a running greeter +// with no onError at all, whose failed respawn escalates and fires the parent nothing, +// stays running in the journal: the next Recover spawns it again without its hello. +func TestRecover_ARunningActorWhoseRespawnEscalatesStaysRunning(t *testing.T) { + transient := func() error { return errors.New("the greeter can't start yet") } + if got := hellosAfterAFailedRespawn(t, anyGreetMachine(), any("poke"), context.Background(), transient); got != 1 { + t.Fatalf("hellos = %d, want the live spawn's one", got) + } +} + +// TestRecover_ARunningActorWhoseRespawnAContextEndsStaysRunning proves a running greeter +// whose respawn fails because Recover's context ended, as a behavior that heeds its +// context reports, stays running in the journal: with the zero-event onError the +// Recover fails, and with none it succeeds, and either way the next Recover spawns the +// greeter again without its hello. +func TestRecover_ARunningActorWhoseRespawnAContextEndsStaysRunning(t *testing.T) { + ended := func() (context.Context, func() error) { + turn, cancel := context.WithCancel(context.Background()) + return turn, func() error { + cancel() // the deadline passes as the respawn runs + return turn.Err() + } + } + t.Run("zero-event onError", func(t *testing.T) { + turn, fail := ended() + if got := hellosAfterAFailedRespawn(t, greetMachine(false), "poke", turn, fail); got != 1 { + t.Fatalf("hellos = %d, want the live spawn's one", got) + } + }) + t.Run("no onError", func(t *testing.T) { + turn, fail := ended() + if got := hellosAfterAFailedRespawn(t, anyGreetMachine(), any("poke"), turn, fail); got != 1 { + t.Fatalf("hellos = %d, want the live spawn's one", got) + } + }) +} diff --git a/durable/runner.go b/durable/runner.go index aa6573f8..7af0b366 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -140,13 +140,16 @@ type Handle[S comparable, E comparable, C any] struct { // that declares them, so a checkpoint records them and Recover doesn't start them. settled map[string]bool - actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired - ended recordedSet // the ended actors the journal last recorded - unstarted recordedSet // the unstarted actors the journal last recorded - seen map[string]bool // declared actors seen running, so a stopped one counts as ended - sets actorSetsCache[S] // the last actorSets result, reused while nothing it reads changed - pending []state.ParentFire[S] // parent Fires Start's or Recover's spawns drove, journaled with the next step - actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step + actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired + ended recordedSet // the ended actors the journal last recorded + unstarted recordedSet // the unstarted actors the journal last recorded + seen map[string]bool // declared actors seen running, so a stopped one counts as ended + // respawnFailed holds the declared actors that aren't running because a respawn of + // them failed: the journal holds their start, so they stay out of the unstarted set. + respawnFailed map[string]bool + sets actorSetsCache[S] // the last actorSets result, reused while nothing it reads changed + pending []state.ParentFire[S] // parent Fires Start's or Recover's spawns drove, journaled with the next step + actorFires *parentFires[S] // the parent Fires the actor system drove, taken per step out outbox // what a step leaves behind once it releases the step lock } @@ -638,6 +641,19 @@ type parentFires[S comparable] struct { spawned map[string]bool // actors whose latest spawn this step started attempted map[string]bool // actors the system was asked to spawn this step failed map[string]bool // actors whose latest spawn failed and whose declared onError applied, or was refused for a reason other than a context ending + respawned map[string]bool // actors whose latest spawn was a respawn of one running at the journal's end, whose start the journal holds +} + +// actorLifecycle is what a step did to the actors: the ones it asked the system to +// spawn, and of those, the ones that started, failed with an onError the journal holds, +// or were respawned, so the journal already holds their start. +type actorLifecycle struct { + spawned, attempted, failed, respawned map[string]bool +} + +// empty reports whether the step did nothing to the actors. +func (l actorLifecycle) empty() bool { + return len(l.attempted) == 0 && len(l.spawned) == 0 && len(l.failed) == 0 && len(l.respawned) == 0 } // attempt notes the actors effects ask the system to spawn. @@ -656,21 +672,41 @@ func (p *parentFires[S]) attempt(effects []state.Effect) { // The latest attempt decides: until it starts, the actor hasn't run again. delete(p.spawned, sp.ID) delete(p.failed, sp.ID) + delete(p.respawned, sp.ID) + } + } +} + +// respawning notes the actors effects respawn: each was running at the journal's end, +// so the journal holds every parent Fire its start drove, even if this spawn fails. +// Call it after attempt, which forgets the mark. It's safe on a nil collector. +func (p *parentFires[S]) respawning(effects []state.Effect) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok { + if p.respawned == nil { + p.respawned = map[string]bool{} + } + p.respawned[sp.ID] = true } } } -// takeLifecycle returns the actors spawned and the actors asked to spawn since the -// last call, and forgets them. It's safe on a nil collector, which has none. -func (p *parentFires[S]) takeLifecycle() (spawned, attempted, failed map[string]bool) { +// takeLifecycle returns what the steps since the last call did to the actors, and +// forgets it. It's safe on a nil collector, which has none. +func (p *parentFires[S]) takeLifecycle() actorLifecycle { if p == nil { - return nil, nil, nil + return actorLifecycle{} } p.mu.Lock() defer p.mu.Unlock() - spawned, attempted, failed = p.spawned, p.attempted, p.failed - p.spawned, p.attempted, p.failed = nil, nil, nil - return spawned, attempted, failed + lc := actorLifecycle{spawned: p.spawned, attempted: p.attempted, failed: p.failed, respawned: p.respawned} + p.spawned, p.attempted, p.failed, p.respawned = nil, nil, nil, nil + return lc } // inspect notes each actor the system spawned. The system reports a spawn only once @@ -1165,19 +1201,21 @@ func (r *recordedSet) note(now *ActorSet) { // also counts as ended, since the journal holds that onError, or the refusal replay // meets again. So an actor whose spawn failed with no onError declared, or whose // onError a context's ending refused, which left the step that drove it recording -// nothing, hasn't ended: it's unstarted, and Recover tries it again. Both are -// nil with no actor palette. +// nothing, hasn't ended: it's unstarted, and Recover tries it again. One whose +// respawn of a running actor failed is in neither set, as it was while running, until +// a later spawn of it: the journal holds its start, so Recover respawns it again. Both +// are nil with no actor palette. func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { if h.actors == nil { return nil, nil } - spawned, attempted, failed := h.actorFires.takeLifecycle() + lc := h.actorFires.takeLifecycle() running := h.actors.IDs() // The sets depend on the declared actors, so on the configuration, on which are // running, and on this step's spawns. A step that changed none of them, as most // steps that touch no actor don't, gets the last result back. config := h.inst.Configuration() - if h.sets.valid && len(attempted) == 0 && len(spawned) == 0 && len(failed) == 0 && + if h.sets.valid && lc.empty() && slices.Equal(config, h.sets.config) && slices.Equal(running, h.sets.running) { return h.sets.ended, h.sets.unstarted } @@ -1185,24 +1223,34 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { h.sets = actorSetsCache[S]{valid: true, config: config, running: running, ended: ended, unstarted: unstarted} }() endedIDs, unstartedIDs := []string{}, []string{} + respawnFailed := map[string]bool{} for _, id := range declaredActors(h.inst.StartEffects()) { if slices.Contains(running, id) { continue } _, ran := h.actors.Ref(id) + journaled := false // whether the journal holds its start though it isn't running switch { case ran: - case attempted[id]: - ran = spawned[id] || failed[id] + case lc.attempted[id]: + ran = lc.spawned[id] || lc.failed[id] + journaled = lc.respawned[id] default: ran = h.seen[id] + journaled = h.respawnFailed[id] } - if ran { + switch { + case ran: endedIDs = append(endedIDs, id) - } else { + case journaled: + // Its respawn failed, but the journal holds its start: it's in neither set, + // as when it was running, so Recover respawns it again rather than as new. + respawnFailed[id] = true + default: unstartedIDs = append(unstartedIDs, id) } } + h.respawnFailed = respawnFailed slices.Sort(endedIDs) endedIDs = slices.Compact(endedIDs) slices.Sort(unstartedIDs) @@ -1277,8 +1325,9 @@ 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. -func respawn[S comparable, E comparable, C any](ctx context.Context, actors *state.ActorSystem[S, E, C], effects []state.Effect, unstarted *ActorSet) { +// parent a second time. It notes the running ones on fires, so one whose spawn fails +// still counts as having started. +func respawn[S comparable, E comparable, C any](ctx context.Context, actors *state.ActorSystem[S, E, C], fires *parentFires[S], effects []state.Effect, unstarted *ActorSet) { var running, fresh []state.Effect for _, eff := range effects { if sp, ok := eff.(state.SpawnActor); ok && unstarted != nil && !slices.Contains(unstarted.IDs, sp.ID) { @@ -1287,6 +1336,7 @@ 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) } @@ -1525,7 +1575,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S actorFires.attempt(spawns) func() { defer actorFires.driving(ctx)() - respawn(ctx, actors, spawns, unstarted) + respawn(ctx, actors, actorFires, spawns, unstarted) }() } // A parent Fire a newly started actor drove (a message it sent as it started, or a diff --git a/durable/store.go b/durable/store.go index fcbd6c0e..0ba8ca0d 100644 --- a/durable/store.go +++ b/durable/store.go @@ -103,9 +103,9 @@ type Record struct { // context ended, which // left the step that drove it recording nothing. Recover // spawns them as new, so the messages they send the parent as they start apply and - // are journaled. A declared actor in neither set was running, and the journal holds - // every parent Fire its start drove, so Recover spawns it again without letting - // those reach the parent. It's + // are journaled. A declared actor in neither set was running, or a Recover's respawn + // of it failed, and the journal holds every parent Fire its start drove, so Recover + // spawns it again without letting those reach the parent. It's // recorded as EndedActors is: with the first step after Start, then when a step // changes it, and an empty set is not nil. When the journal holds none, as on a // Record from before this field, Recover lets every spawn reach the parent.