From 663de98f3a0ea40e34b3e0bf5ebed91bf69d4a93 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 18 Nov 2026 15:09:37 -0700 Subject: [PATCH 1/2] fix(durable): record an actor stopped in the step that spawns it, or before it respawns, as ended An explicit stopActor while the actor's declaring state stays active - one a step's own effects hold later than the spawn, as the OnDone of a compound the step completes, or one a parent Fire an earlier spawn drove - skipped the spawn but noted nothing, not even an attempt, so the journal recorded the actor unstarted and a Recover spawned it fresh, running its behavior a second time. The same held for a stop a parent Fire noted while Recover respawned a batch of running actors, before its target respawned: the stop found nothing running and did nothing, though the journal held it, so both the recovering Handle and a later Recover ran the actor the live run had ended. And an explicit StopActor counted as the actor's state being left, so a stop followed by a re-entry of the same state later in the same step skipped the new activation's spawn too, and the actor never ran though its state was active. - durable: absorbActors notes every spawn it skips as attempted and stopped, so actorSets counts the actor ended and the journal records it ended rather than unstarted, and a Recover spawns none of them. An actor that is explicitly stopped in the step that spawns it, while its state stays active, never runs its behavior. - durable: a parent Fire's stops are noted by actor on the collector, and left now reports the states a Fire's trace says it exited, so an explicit StopActor no longer lefts the state. A StopActor the step absorbs supersedes the Fire's mark, so a stop followed by a re-entry of the same state later in the same step doesn't skip the new activation's spawn. - durable: respawn applies the stops a batch's Fires noted, before their target's respawn, to the actors the batch respawned, so the recovering Handle ends them and the journal records them ended, and a later Recover ends them too. Closes #261. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 13 + durable/actor_stop_sets_test.go | 462 ++++++++++++++++++++++++++++++++ durable/runner.go | 151 +++++++++-- 3 files changed, 598 insertions(+), 28 deletions(-) create mode 100644 durable/actor_stop_sets_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 5168e28..dab7e7a 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -296,6 +296,19 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Fixed +- **An actor stopped in the step that spawns it, or before it respawns, is recorded + as ended.** An explicit `StopActor` that a step's own effects hold, or a parent + `Fire` an earlier spawn drove, while the actor's state stays active, skipped the + actor's spawn but noted nothing — not even an attempt — so the journal recorded the + actor unstarted, and a `Recover` spawned it fresh and ran its behavior a second time. + Now every skipped spawn is noted as stopped, so the journal records the actor ended + and a `Recover` runs none of them. An explicit stop no longer counts as the actor's + state being left: a stop followed by a re-entry of the same state later in the same + step doesn't skip the new activation's spawn, whose actor runs, live and on + `Recover`, as a stop the step absorbs between the two supersedes. And a stop a + parent `Fire` notes while `Recover` respawns a batch of running actors, before its + target respawns, now applies to the actors the batch respawned, so both the + recovering `Handle` and a later `Recover` end the actor. - **A parent transition an actor drives dispatches its domain effects.** A domain effect a parent `Fire` emitted, where an actor drove that Fire — a failed spawn's onError during a `Fire`, a `Tick`, or a service settle's transition, or a settle or diff --git a/durable/actor_stop_sets_test.go b/durable/actor_stop_sets_test.go new file mode 100644 index 0000000..ccbbbba --- /dev/null +++ b/durable/actor_stop_sets_test.go @@ -0,0 +1,462 @@ +package durable_test + +// The tests for the two gaps of issue #261, an explicit stopActor while the declaring +// state stays active. First: a step that skips a state's spawn because the same step +// stops the actor notes nothing — not even an attempt — so the journal records the +// actor unstarted, and Recover runs it fresh where the live Handle has none. The skip +// comes two ways: a stop later in the step's own effects (the OnDone of a compound the +// step completes, or a stop a later timer of the same Tick declares), or a stop a +// parent Fire an earlier spawn drove, which marks the actor's activation exited. Second: +// a stop that arrives while Recover respawns a batch of running actors, before its +// target respawns, does nothing to it, though the journal holds the stop. +// +// Every row compares the live Handle's actors with the recovered Handle's: neither may +// run an actor the journal ended, and both must hold the same ones. + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// stepFetch is a service that succeeds, for the stepCtx fixtures. +func stepFetch(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + +// stopSkipMachine enters Y, which declares kitchen, by one of three drivings: a Fire of +// "go", the "go" a Tick fires for w's timer, or the "fetched" a RunService settles for +// loading's fetch. Entering Y completes Yc, whose OnDone runs stopActor on kitchen +// while Y stays active — a stop later in the same effects than kitchen's spawn. +func stopSkipMachine() stepMachine { + return state.ForgeFor[stepCtx]("stopSkip"). + Service("fetch", stepFetch). + Actor("kitchen"). + State("idle"). + State("w"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("fetched")). + SuperState("Yc"). + Initial("Y"). + OnDone("crucible.stopActor", map[string]any{"id": "kitchen"}). + SubState("Y").InvokeActor("kitchen", state.WithInvokeID("kitchen")).Final(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("Y"). + Transition("idle").On("wait").GoTo("w"). + Transition("w").After(4 * time.Second).On("go").GoTo("Y"). + Transition("idle").On("load").GoTo("loading"). + Transition("loading").On("fetched").GoTo("Y"). + Quench() +} + +// TestRecover_ASpawnTheSameStepStops_IsEndedNotUnstarted pins that a spawn a step +// skips because a later effect of the same step stops the actor, while its state stays +// active, counts as ended: the live Handle runs nothing, and Recover mustn't either — +// the journal must record the skipped spawn as attempted and ended, not unstarted, or +// a Recover runs the actor fresh and its behavior a second time. +func TestRecover_ASpawnTheSameStepStops_IsEndedNotUnstarted(t *testing.T) { + ctx := context.Background() + for _, by := range []string{"Fire", "Tick", "RunService"} { + for _, every := range []int{0, 1} { + t.Run(fmt.Sprintf("%s checkpoint every %d", by, every), func(t *testing.T) { + m := stopSkipMachine() + var kitchenSpawns int + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "kitchen": func(map[string]any) (state.ActorInstance, error) { + kitchenSpawns++ + return ¬eTarget{}, nil + }, + }), + } + if by == "Tick" { + opts = append(opts, durable.WithRunnerClock[string, string, stepCtx](clk)) + } + if by == "RunService" { + opts = append(opts, durable.WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", stepFetch))) + } + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("stop-same-step") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("idle")) + 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 "Tick": + if _, err = h.Fire(ctx, "wait"); err != nil { + t.Fatalf("Fire(wait): %v", err) + } + clk.Advance(6 * time.Second) + if fired, terr := h.Tick(ctx); terr != nil || len(fired) != 1 { + t.Fatalf("Tick fired %d timer(s), err %v; want w's one", len(fired), terr) + } + case "RunService": + if _, err = h.Fire(ctx, "load"); err != nil { + t.Fatalf("Fire(load): %v", err) + } + if _, ran, rerr := h.RunService(ctx, state.InvokeID("stopSkip", "loading", 0)); !ran || rerr != nil { + t.Fatalf("RunService = ran %v, err %v; want the fetch settled", ran, rerr) + } + } + if _, ok := h.ActorRef("kitchen"); ok { + t.Fatal("live: kitchen is running, want none: the step skipped its spawn for the stop the same effects hold") + } + if kitchenSpawns != 0 { + t.Fatalf("live: kitchen spawned %d time(s), want none", kitchenSpawns) + } + for round := 1; round <= 2; round++ { + recovered, rerr := durable.Recover(ctx, m, store, id, opts...) + if rerr != nil { + t.Fatalf("Recover %d: %v", round, rerr) + } + if _, ok := recovered.ActorRef("kitchen"); ok { + t.Fatalf("Recover %d runs kitchen, want none: the live Handle has no such actor, so the journal must record the skipped spawn as ended, not unstarted", round) + } + if kitchenSpawns != 0 { + t.Fatalf("Recover %d ran kitchen's behavior %d time(s), want none: a fresh spawn re-runs what the live step skipped", round, kitchenSpawns) + } + } + }) + } + } +} + +// stopByParentMachine enters both — by a Fire of "enter", or by starting in it — whose +// left region runs a1 and whose right region declares kitchen. a1 sends stopK as it +// starts, whose Fire enters X2 and explicitly stops kitchen while Y stays active, +// before the step absorbs kitchen's own spawn. +func stopByParentMachine() stepMachine { + return state.ForgeFor[stepCtx]("stopByParent"). + Actor("a1"). + Actor("kitchen"). + State("idle"). + SuperState("both"). + Region("left"). + Initial("X"). + SubState("X").InvokeActor("a1", state.WithInvokeID("a1")). + SubState("X2"). + EndRegion(). + Region("right"). + Initial("Y"). + SubState("Y").InvokeActor("kitchen", state.WithInvokeID("kitchen")). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("enter").GoTo("both"). + Transition("X").On("stopK").GoTo("X2").StopActor("kitchen"). + Transition("Y").On("poke").GoTo("Y"). + Quench() +} + +// TestRecover_ASpawnAParentFireStops_IsEndedNotUnstarted pins the same for a stop a +// parent Fire an earlier spawn drove: the Fire's stop, arriving before the step absorbs +// kitchen's spawn, notes kitchen's activation as exited, so the step skips the spawn as +// one whose state was left — but Y stays active. The Handle that drove the step runs no +// kitchen; the journal must record the skipped spawn as ended, so a Recover runs none. +// A Start that begins in both leaves the same journal once a step records its sets. +func TestRecover_ASpawnAParentFireStops_IsEndedNotUnstarted(t *testing.T) { + ctx := context.Background() + for _, by := range []string{"Fire", "Start"} { + for _, every := range []int{0, 1} { + t.Run(fmt.Sprintf("%s checkpoint every %d", by, every), func(t *testing.T) { + m := stopByParentMachine() + var kitchenSpawns int + opts := []stepOption{ + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "a1": func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "stopK"}, nil }, + "kitchen": func(map[string]any) (state.ActorInstance, error) { + kitchenSpawns++ + return ¬eTarget{}, nil + }, + }), + } + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("stop-by-parent") + initial := "idle" + if by == "Start" { + initial = "both" + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState(initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + if by == "Fire" { + if _, err = h.Fire(ctx, "enter"); err != nil { + t.Fatalf("Fire(enter): %v", err) + } + } + // A step journals the driven Fire and the actor sets: for a Start, the + // driven Fire is pending until one runs. + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if _, ok := h.ActorRef("kitchen"); ok { + t.Fatal("live: kitchen is running, want none: a1's Fire stopped it before its spawn was absorbed") + } + if kitchenSpawns != 0 { + t.Fatalf("live: kitchen spawned %d time(s), want none", kitchenSpawns) + } + for round := 1; round <= 2; round++ { + recovered, rerr := durable.Recover(ctx, m, store, id, opts...) + if rerr != nil { + t.Fatalf("Recover %d: %v", round, rerr) + } + if _, ok := recovered.ActorRef("kitchen"); ok { + t.Fatalf("Recover %d runs kitchen, want none: the live Handle has no such actor, so the journal must record the skipped spawn as ended, not unstarted", round) + } + if kitchenSpawns != 0 { + t.Fatalf("Recover %d ran kitchen's behavior %d time(s), want none", round, kitchenSpawns) + } + } + }) + } + } +} + +// reentryMachine starts in both, whose left region runs nothing in X and whose right +// region runs kitchen in Y. X's 4-second timer enters X3, which runs stopper; Y's +// 6-second timer re-enters right, exiting and re-entering Y. A Tick past both deadlines +// fires them in that order: the go timer's absorb spawns stopper, whose stopK Fire +// enters X2 and explicitly stops kitchen while Y stays active, and the re timer's absorb +// then takes kitchen's spawn for Y's new activation, after the stop its exit emitted. +func reentryMachine() stepMachine { + return state.ForgeFor[stepCtx]("stopReentry"). + Actor("stopper"). + Actor("kitchen"). + SuperState("both"). + Region("left"). + Initial("X"). + SubState("X"). + SubState("X3").InvokeActor("stopper", state.WithInvokeID("stopper")). + SubState("X2"). + EndRegion(). + Region("right"). + Initial("R"). + SuperState("R"). + Initial("Y"). + SubState("Y").InvokeActor("kitchen", state.WithInvokeID("kitchen")). + EndSuperState(). + EndRegion(). + EndSuperState(). + Initial("both"). + Transition("X").After(4 * time.Second).On("go").GoTo("X3"). + Transition("Y").After(6 * time.Second).On("re").GoTo("R"). + Transition("X3").On("stopK").GoTo("X2").StopActor("kitchen"). + Transition("Y").On("poke").GoTo("Y"). + Quench() +} + +// TestTick_AnExplicitStopThenAReentry_SpawnsTheNewActivation pins that an explicit stop +// a parent Fire notes during a tick ends only the activation that was current when the +// Fire noted it: a later timer of the same tick that re-enters the state spawns the new +// activation's actor, rather than skipping it as one the stop ended. The live Handle +// runs kitchen again, and a Recover, which replays the tick's timers and then its driven +// Fire, ends in the same configuration and runs kitchen too. +func TestTick_AnExplicitStopThenAReentry_SpawnsTheNewActivation(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 := reentryMachine() + var kitchenSpawns int + clk := state.NewFakeClock(epoch) + opts := []stepOption{ + durable.WithRunnerClock[string, string, stepCtx](clk), + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "stopper": func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "stopK"}, nil }, + "kitchen": func(map[string]any) (state.ActorInstance, error) { + kitchenSpawns++ + return ¬eTarget{}, nil + }, + }), + } + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("stop-reentry") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("both")) + if err != nil { + t.Fatalf("Start: %v", err) + } + // A step journals kitchen as running, so a Recover respawns it. + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + if kitchenSpawns != 1 { + t.Fatalf("setup: kitchen spawned %d times, want its start", kitchenSpawns) + } + clk.Advance(7 * time.Second) + fired, err := h.Tick(ctx) + if err != nil || len(fired) != 2 { + t.Fatalf("Tick fired %d timer(s), err %v; want go then re", len(fired), err) + } + if _, ok := h.ActorRef("kitchen"); !ok { + t.Fatal("live: kitchen isn't running, want it running for Y's new activation: the re timer's spawn isn't one the stopK Fire ended") + } + if kitchenSpawns != 2 { + t.Fatalf("live: kitchen spawned %d times, want its start and the new activation's", kitchenSpawns) + } + wantSpawns := kitchenSpawns + for round := 1; round <= 2; round++ { + recovered, rerr := durable.Recover(ctx, m, store, id, opts...) + if rerr != nil { + t.Fatalf("Recover %d: %v", round, rerr) + } + if cfg := fmt.Sprint(recovered.Instance().Configuration()); cfg != "[X2 Y]" { + t.Fatalf("Recover %d configuration %s, want [X2 Y]", round, cfg) + } + if _, ok := recovered.ActorRef("kitchen"); !ok { + t.Fatalf("Recover %d doesn't run kitchen, want it running, as the live Handle does: the replayed stopK Fire precedes the respawn, so it ends nothing the new activation holds", round) + } + wantSpawns++ + if kitchenSpawns != wantSpawns { + t.Fatalf("Recover %d: kitchen spawned %d times, want %d", round, kitchenSpawns, wantSpawns) + } + } + if cfg := fmt.Sprint(h.Instance().Configuration()); cfg != "[X2 Y]" { + t.Fatalf("live configuration %s, want [X2 Y]", cfg) + } + }) + } +} + +// earlyStopMachine runs a1 in A1 and c1 in C1, two regions of both. a1's spawn fails +// from its second run on, routing errA, whose Fire leaves A1 for A2 and explicitly +// stops c1 while C1 stays active. +func earlyStopMachine() stepMachine { + return state.ForgeFor[stepCtx]("earlyStop"). + Actor("a1"). + Actor("c1"). + SuperState("both"). + Region("left"). + Initial("A1"). + SubState("A1").InvokeActor("a1", state.WithInvokeID("a1"), state.WithInvokeOnError("errA")). + SubState("A2"). + EndRegion(). + Region("right"). + Initial("C1"). + SubState("C1").InvokeActor("c1", state.WithInvokeID("c1")). + EndRegion(). + EndSuperState(). + Initial("both"). + Transition("A1").On("errA").GoTo("A2").StopActor("c1"). + Transition("C1").On("poke").GoTo("C1"). + Quench() +} + +// earlyStopPalette counts each actor's spawns; a1 fails from its second spawn on, as +// when a Recover's respawn finds a dependency gone, routing errA. +func earlyStopPalette(a1Spawns, c1Spawns *int) stepOption { + return durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "a1": func(map[string]any) (state.ActorInstance, error) { + *a1Spawns++ + if *a1Spawns > 1 { + return nil, errors.New("gone") + } + return ¬eTarget{}, nil + }, + "c1": func(map[string]any) (state.ActorInstance, error) { + *c1Spawns++ + return ¬eTarget{}, nil + }, + }) +} + +// TestRecover_AStopBeforeItsTargetRespawns_EndsIt pins that an explicit stop of c1 +// ends it wherever the stop arrives. A live Fire of errA, stopping c1 while it runs, +// ends it, and Recover agrees — the journal records it ended. A stop that arrives +// while Recover respawns a batch of running actors must end the actors that batch +// respawned too: a1's respawn fails first, routing errA before c1 respawns, so the +// stop finds nothing running and does nothing — yet the journal holds it. The Handle +// that drove the respawn, and one recovered from its journal, must both hold c1 ended. +func TestRecover_AStopBeforeItsTargetRespawns_EndsIt(t *testing.T) { + ctx := context.Background() + t.Run("a live Fire, while its target runs", func(t *testing.T) { + m := earlyStopMachine() + var a1Spawns, c1Spawns int + opts := []stepOption{earlyStopPalette(&a1Spawns, &c1Spawns)} + store, id := durable.NewMemStore(), durable.InstanceID("early-stop-live") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("both")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "errA"); err != nil { + t.Fatalf("Fire(errA): %v", err) + } + for _, hh := range []struct { + name string + h *durable.Handle[string, string, stepCtx] + }{{"live", h}} { + if _, ok := hh.h.ActorRef("c1"); ok { + t.Fatalf("%s: c1 is running, want it stopped by the errA Fire while C1 stays active", hh.name) + } + } + recovered, rerr := durable.Recover(ctx, m, store, id, opts...) + if rerr != nil { + t.Fatalf("Recover: %v", rerr) + } + if _, ok := recovered.ActorRef("c1"); ok { + t.Fatal("recovered: c1 is running, want it ended, as the live Fire stopped it") + } + if c1Spawns != 1 { + t.Fatalf("c1 spawned %d time(s), want only its live start", c1Spawns) + } + }) + for _, every := range []int{0, 1} { + t.Run(fmt.Sprintf("a respawn, checkpoint every %d", every), func(t *testing.T) { + m := earlyStopMachine() + var a1Spawns, c1Spawns int + opts := []stepOption{earlyStopPalette(&a1Spawns, &c1Spawns)} + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("early-stop-respawn") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, stepCtx{}, state.WithInitialState("both")) + if err != nil { + t.Fatalf("Start: %v", err) + } + // A step records both actors running, so the Recover respawns them as a + // batch, a1 first. + if _, err = h.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + h1, rerr := durable.Recover(ctx, m, store, id, opts...) + if rerr != nil { + t.Fatalf("Recover: %v", rerr) + } + if a1Spawns != 2 { + t.Fatalf("setup: a1 spawned %d times, want its respawn tried and failed", a1Spawns) + } + // The stop a1's failed respawn routed must apply to the batch: c1 ended. + if _, err = h1.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) after Recover: %v", err) + } + h2, rerr := durable.Recover(ctx, m, store, id, opts...) + if rerr != nil { + t.Fatalf("Recover again: %v", rerr) + } + for _, hh := range []struct { + name string + h *durable.Handle[string, string, stepCtx] + }{{"the Handle that drove the respawn", h1}, {"a Handle recovered from its journal", h2}} { + if _, ok := hh.h.ActorRef("c1"); ok { + t.Fatalf("%s runs c1, want it ended: a1's failed respawn routed errA, whose stop of c1 the journal holds", hh.name) + } + if _, ok := hh.h.ActorRef("a1"); ok { + t.Fatalf("%s runs a1, want none: its respawn failed and errA left A1", hh.name) + } + } + }) + } +} diff --git a/durable/runner.go b/durable/runner.go index 52f88b1..ca72e5c 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -421,8 +421,15 @@ func (h *Handle[S, E, C]) absorbServices(ctx context.Context, effects []state.Ef // absorbActors feeds the system one effect at a time. It's so too when a later effect // of the step stops the actor (see stoppedLater): one in effects, or in later, the // effects a later call of the same step absorbs, as when a later timer of a Tick -// leaves the state. A spawn the step's effects then make for a new activation of the -// state isn't skipped, unless a parent Fire left that one too. +// leaves the state. And it's so when a parent Fire stopped the actor explicitly, while +// its state stayed active (see parentFires.fireStopped): a Recover replays the Fire +// before it respawns, so it ends the actor, and the live Handle must not run it. Every +// skipped spawn is noted as stopped (see actorLifecycle.stopped), so the journal +// records the actor ended rather than unstarted, and a Recover doesn't run its +// behavior fresh. A spawn the step's effects then make for a new activation of the +// state isn't skipped, unless a parent Fire left that one too: a StopActor for the +// actor that precedes it in the effects the step absorbs supersedes an explicit stop a +// Fire noted (see parentFires.spent). func (h *Handle[S, E, C]) absorbActors(ctx context.Context, event any, effects, later []state.Effect) { if h.actors == nil { return @@ -431,7 +438,10 @@ func (h *Handle[S, E, C]) absorbActors(ctx context.Context, event any, effects, for i := range effects { switch eff := effects[i].(type) { case state.SpawnActor: - if h.actorFires.left(eff) || stoppedLater(eff, effects[i+1:], later) { + if h.actorFires.left(eff) || stoppedLater(eff, effects[i+1:], later) || h.actorFires.fireStopped(eff) { + one := effects[i : i+1 : i+1] + h.actorFires.attempt(one) + h.actorFires.stoppedSpawn(one) continue } case state.ForwardEvent: @@ -439,6 +449,11 @@ func (h *Handle[S, E, C]) absorbActors(ctx context.Context, event any, effects, if event == nil { continue } + case state.StopActor: + // A stop the step absorbs for an actor supersedes one a parent Fire noted + // for it: the activation that stop ended is over, and a spawn of the actor + // that follows is for a new activation of its state. + h.actorFires.spent(eff.ID) } one := effects[i : i+1 : i+1] h.actorFires.attempt(one) @@ -828,19 +843,28 @@ type parentFires[S comparable] struct { attempted map[string]bool // actors the system was asked to spawn this step failed map[string]bool // actors whose latest spawn failed and whose declared onError applied, or was refused for a reason other than a context ending respawned map[string]bool // actors whose latest spawn was a respawn of one running at the journal's end, whose start the journal holds - exited map[string]bool // actors a parent Fire noted since the last take stopped: the activation of their state that spawned them ended + stopped map[string]bool // actors whose spawn this step skipped for a stop, so the journal records them ended rather than unstarted (see absorbActors) + exited map[string]bool // the states, by label, a parent Fire noted since the last take exited: a spawn one declares is for an activation that ended (see left) + // stoppedByFire holds the actors a parent Fire's effects stopped since the last + // take. A spawn of one the step hasn't absorbed yet is for an activation the stop + // ended, so absorbActors skips it and notes it stopped, as a Recover, which replays + // the Fire before it respawns, ends the actor. A StopActor the step absorbs for the + // actor later supersedes the mark (see spent): the spawn after it is for a new + // activation of its state, which the stop didn't end. + stoppedByFire map[string]bool } // 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. +// were respawned, so the journal already holds their start, or were stopped instead of +// started, so the journal records them ended. type actorLifecycle struct { - spawned, attempted, failed, respawned map[string]bool + spawned, attempted, failed, respawned, stopped 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 + return len(l.attempted) == 0 && len(l.spawned) == 0 && len(l.failed) == 0 && len(l.respawned) == 0 && len(l.stopped) == 0 } // attempt notes the actors effects ask the system to spawn. @@ -860,6 +884,7 @@ func (p *parentFires[S]) attempt(effects []state.Effect) { delete(p.spawned, sp.ID) delete(p.failed, sp.ID) delete(p.respawned, sp.ID) + delete(p.stopped, sp.ID) } } } @@ -891,8 +916,8 @@ func (p *parentFires[S]) takeLifecycle() actorLifecycle { } p.mu.Lock() defer p.mu.Unlock() - lc := actorLifecycle{spawned: p.spawned, attempted: p.attempted, failed: p.failed, respawned: p.respawned} - p.spawned, p.attempted, p.failed, p.respawned = nil, nil, nil, nil + lc := actorLifecycle{spawned: p.spawned, attempted: p.attempted, failed: p.failed, respawned: p.respawned, stopped: p.stopped} + p.spawned, p.attempted, p.failed, p.respawned, p.stopped = nil, nil, nil, nil, nil return lc } @@ -935,13 +960,23 @@ func (p *parentFires[S]) note(pf state.ParentFire[S]) { } p.failed[pf.ActorID] = true } - // A parent Fire that leaves a state stops its actors (see left). + // A parent Fire that leaves a state stops its actors (see left): the states its + // trace reports it exited, which a durable instance always records (see Start and + // Recover), mark every spawn one declares as for an activation that ended. Its + // effects can also stop an actor explicitly, while the actor's state stays active + // (see stoppedByFire). + for _, s := range nf.pf.Result.Trace.ExitedStates { + if p.exited == nil { + p.exited = map[string]bool{} + } + p.exited[s] = true + } for _, eff := range nf.pf.Result.Effects { if e, ok := eff.(state.StopActor); ok { - if p.exited == nil { - p.exited = map[string]bool{} + if p.stoppedByFire == nil { + p.stoppedByFire = map[string]bool{} } - p.exited[e.ID] = true + p.stoppedByFire[e.ID] = true } } ctx := p.ctx @@ -1023,23 +1058,75 @@ func (p *parentFires[S]) take() []notedFire[S] { p.mu.Lock() defer p.mu.Unlock() fires := p.fires - p.fires, p.exited = nil, nil + p.fires, p.exited, p.stoppedByFire = nil, nil, nil return fires } // left reports whether a parent Fire noted since the last take left the state that // declares sp, so sp, a spawn a step's own transitions produced before that Fire, is -// for an activation of the state that has ended: the Fire stopped sp's actor. Spawning -// it would run an actor for a state that isn't active, or, if a later Fire entered the -// state again, a second time for one activation, when that Fire spawned its own. A -// dynamic spawn, which declares no state, is never left. It's safe on a nil collector. +// for an activation of the state that has ended: the Fire exited the state, stopping +// its actors. Spawning it would run an actor for a state that isn't active, or, if a +// later Fire entered the state again, a second time for one activation, when that Fire +// spawned its own. An explicit StopActor a Fire's effects holds doesn't mark the state +// left: the state stays active, and a spawn of it the step absorbs later, for a new +// activation the stop didn't end, runs — the stop ends only the spawns that were +// pending when the Fire noted it (see stoppedByFire). A dynamic spawn, which declares +// no state, is never left. It's safe on a nil collector. func (p *parentFires[S]) left(sp state.SpawnActor) bool { if p == nil || sp.State == "" { return false } p.mu.Lock() defer p.mu.Unlock() - return p.exited[sp.ID] + return p.exited[sp.State] +} + +// fireStopped reports whether a parent Fire noted since the last take stopped sp's +// actor while its state stayed active, so sp, a spawn the step hasn't absorbed yet, is +// for an activation the stop ended: skipping it keeps the live Handle in step with a +// Recover, which replays the Fire before it respawns, and so ends the actor. A dynamic +// spawn, which declares no state, is never stopped this way, as for stoppedLater. It's +// safe on a nil collector. +func (p *parentFires[S]) fireStopped(sp state.SpawnActor) bool { + if p == nil || sp.State == "" { + return false + } + p.mu.Lock() + defer p.mu.Unlock() + return p.stoppedByFire[sp.ID] +} + +// spent forgets the mark a parent Fire's stop left on an actor: the step has absorbed +// a StopActor for it since, so the activation the stop ended is over, and a spawn of it +// that follows is for a new activation of its state, which the mark must not skip. It's +// safe on a nil collector. +func (p *parentFires[S]) spent(id string) { + if p == nil { + return + } + p.mu.Lock() + delete(p.stoppedByFire, id) + p.mu.Unlock() +} + +// stoppedSpawn notes the actors effects ask the system to spawn as stopped instead of +// started: the step was asked for them, and stopped them, so the journal records them +// ended rather than unstarted, and a Recover doesn't run their behavior fresh. Call it +// after attempt, which forgets the mark. It's safe on a nil collector. +func (p *parentFires[S]) stoppedSpawn(effects []state.Effect) { + if p == nil { + return + } + p.mu.Lock() + for _, eff := range effects { + if sp, ok := eff.(state.SpawnActor); ok { + if p.stopped == nil { + p.stopped = map[string]bool{} + } + p.stopped[sp.ID] = true + } + } + p.mu.Unlock() } // stoppedLater reports whether a StopActor for sp's actor follows sp in the effects a @@ -1576,9 +1663,11 @@ func (r *recordedSet) note(now *ActorSet) { // and those that aren't running and haven't ended, and remembers them for the next // step. A declared actor that isn't running has ended when it settled (the actor system // keeps a settled actor), or when this step asked the system to spawn it and the latest -// of those spawns started it (then something stopped it), or, when this step didn't try -// to spawn it, when it was running or ended at the previous step. A spawn whose onError -// applied, or whose onError was refused for a reason other than a context ending, +// of those spawns started it (then something stopped it) or was stopped instead of +// started, as when the same step that spawns it stops it while its state stays active, +// or, when this step didn't try to spawn it, when it was running or ended at the +// previous step. A spawn whose onError applied, or whose onError was refused for a +// reason other than a context ending, // also counts as ended, since the journal holds that onError, or the refusal replay // meets again. So an actor whose spawn failed with no onError declared, or whose // onError a context's ending refused, which left the step that drove it recording @@ -1614,7 +1703,7 @@ func (h *Handle[S, E, C]) actorSets() (ended, unstarted *ActorSet) { switch { case ran: case lc.attempted[id]: - ran = lc.spawned[id] || lc.failed[id] + ran = lc.spawned[id] || lc.failed[id] || lc.stopped[id] journaled = lc.respawned[id] default: ran = h.seen[id] @@ -1743,7 +1832,11 @@ func startsExcept[T state.Effect](effects []state.Effect, ids []string, id func( // running actor whose respawn fails. The new actors go through absorbActors, which // skips such a spawn. The running ones respawn together, so one whose state such a Fire // left respawns all the same; respawn then stops each whose state isn't active, as a -// Recover from the journal, replaying that Fire, never runs it. +// Recover from the journal, replaying that Fire, never runs it. A Fire the batch drove +// can also stop one of them explicitly, before its respawn: the stop found nothing +// running and did nothing, though the journal holds it, so respawn applies it to the +// actors the batch respawned (see fireStopped), and both the recovering Handle and a +// Recover from its journal end the actor. func (h *Handle[S, E, C]) respawn(ctx context.Context, effects []state.Effect, unstarted *ActorSet) { var running, fresh []state.Effect for _, eff := range effects { @@ -1764,13 +1857,15 @@ func (h *Handle[S, E, C]) respawn(ctx context.Context, effects []state.Effect, u return } // Every one of them was declared by an active leaf before the spawns, so one whose - // state isn't active now is one such a Fire left. Stopping one that isn't running, as - // one whose state that Fire left after it respawned, so the Fire stopped it, is a - // no-op. + // state isn't active now is one such a Fire left. One a Fire the batch drove stopped + // explicitly, before its respawn and while its state stayed active, is one the stop + // must end here. Stopping one that isn't running, as one whose state that Fire left + // after it respawned, so the Fire stopped it, is a no-op. var stops []state.Effect active := declaredActors(h.inst.StartEffects()) for _, eff := range running { - if sp := eff.(state.SpawnActor); !slices.Contains(active, sp.ID) { + sp := eff.(state.SpawnActor) + if !slices.Contains(active, sp.ID) || (h.actorFires.fireStopped(sp) && !h.actorFires.left(sp)) { stops = append(stops, state.StopActor{ID: sp.ID}) } } From 7cd223ca3e9832a7b8a0801f5dd865da8f8258c0 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 18 Nov 2026 16:41:36 -0700 Subject: [PATCH 2/2] fix(durable): don't count a failed parent Fire's exits as states left Signed-off-by: Ray Karnes --- durable/actor_stop_sets_test.go | 97 +++++++++++++++++++++++++++++++++ durable/runner.go | 22 +++++--- 2 files changed, 111 insertions(+), 8 deletions(-) diff --git a/durable/actor_stop_sets_test.go b/durable/actor_stop_sets_test.go index ccbbbba..bbf6d01 100644 --- a/durable/actor_stop_sets_test.go +++ b/durable/actor_stop_sets_test.go @@ -331,6 +331,103 @@ func TestTick_AnExplicitStopThenAReentry_SpawnsTheNewActivation(t *testing.T) { } } +var errYExit = errors.New("state Y's exit failed") + +// failedExitMachine enters both — by a Fire of "enter" — whose left region runs a1 and +// whose right region declares kitchen. a1 sends bye as it starts, whose Fire would +// leave Y for Y2 — but Y's OnExit fails, so the Fire fails, the configuration is +// unchanged, and Y stays active with kitchen's spawn, which the step absorbs after +// a1's, still to run. +func failedExitMachine() stepMachine { + return state.ForgeFor[stepCtx]("stopByFailedExit"). + Action("explode", func(state.ActionCtx[stepCtx]) (state.Effect, error) { + return nil, errYExit + }). + Actor("a1"). + Actor("kitchen"). + State("idle"). + SuperState("both"). + Region("left"). + Initial("X"). + SubState("X").InvokeActor("a1", state.WithInvokeID("a1")). + EndRegion(). + Region("right"). + Initial("Y"). + SubState("Y").InvokeActor("kitchen", state.WithInvokeID("kitchen")).OnExit("explode"). + SubState("Y2"). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("enter").GoTo("both"). + Transition("Y").On("bye").GoTo("Y2"). + Quench() +} + +// TestRecover_ASpawnAStateAFailedFireTriedToExit_Runs pins that a parent Fire whose +// exit cascade fails — Y's OnExit returns an error — leaves nothing: the Fire failed, +// so the configuration is unchanged and Y stays active, and kitchen, the actor Y +// declares and the step absorbs after the Fire, must spawn and run. The Fire's trace +// still names Y among its ExitedStates (recorded before the exit actions ran) and +// holds no effects (a failed Fire emits none), so nothing may take the trace's word +// for the state having been left: the live Handle runs kitchen, and a Recover, whose +// journal records it running, respawns it. +func TestRecover_ASpawnAStateAFailedFireTriedToExit_Runs(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 := failedExitMachine() + var kitchenSpawns int + opts := []stepOption{ + durable.WithActorPalette[string, string, stepCtx](map[string]state.ActorBehavior{ + "a1": func(map[string]any) (state.ActorInstance, error) { return &sender{ev: "bye"}, nil }, + "kitchen": func(map[string]any) (state.ActorInstance, error) { + kitchenSpawns++ + return ¬eTarget{}, nil + }, + }), + } + if every > 0 { + opts = append(opts, durable.WithCheckpointEvery[string, string, stepCtx](every)) + } + store, id := durable.NewMemStore(), durable.InstanceID("stop-by-failed-exit") + 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, "enter"); err != nil { + t.Fatalf("Fire(enter): %v", err) + } + // The bye Fire failed on Y's exit, so Y stayed active and kitchen runs. + if _, ok := h.ActorRef("kitchen"); !ok { + t.Fatal("live: kitchen isn't running, want it running: the bye Fire's failed exit left Y active") + } + if kitchenSpawns != 1 { + t.Fatalf("live: kitchen spawned %d time(s), want its start", kitchenSpawns) + } + if cfg := fmt.Sprint(h.Instance().Configuration()); cfg != "[X Y]" { + t.Fatalf("live configuration %s, want [X Y]: the bye Fire failed and changed nothing", cfg) + } + wantSpawns := kitchenSpawns + for round := 1; round <= 2; round++ { + recovered, rerr := durable.Recover(ctx, m, store, id, opts...) + if rerr != nil { + t.Fatalf("Recover %d: %v", round, rerr) + } + if _, ok := recovered.ActorRef("kitchen"); !ok { + t.Fatalf("Recover %d doesn't run kitchen, want it running, as the live Handle does: the bye Fire's failed exit left Y active", round) + } + if cfg := fmt.Sprint(recovered.Instance().Configuration()); cfg != "[X Y]" { + t.Fatalf("Recover %d configuration %s, want [X Y]", round, cfg) + } + wantSpawns++ + if kitchenSpawns != wantSpawns { + t.Fatalf("Recover %d: kitchen spawned %d times, want %d", round, kitchenSpawns, wantSpawns) + } + } + }) + } +} + // earlyStopMachine runs a1 in A1 and c1 in C1, two regions of both. a1's spawn fails // from its second run on, routing errA, whose Fire leaves A1 for A2 and explicitly // stops c1 while C1 stays active. diff --git a/durable/runner.go b/durable/runner.go index ca72e5c..cf6ac60 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -962,14 +962,20 @@ func (p *parentFires[S]) note(pf state.ParentFire[S]) { } // A parent Fire that leaves a state stops its actors (see left): the states its // trace reports it exited, which a durable instance always records (see Start and - // Recover), mark every spawn one declares as for an activation that ended. Its - // effects can also stop an actor explicitly, while the actor's state stays active - // (see stoppedByFire). - for _, s := range nf.pf.Result.Trace.ExitedStates { - if p.exited == nil { - p.exited = map[string]bool{} - } - p.exited[s] = true + // Recover), mark every spawn one declares as for an activation that ended. A failed + // Fire marks none: its trace names the states its exit cascade began — recorded + // before the exit actions ran — but the failure left the configuration unchanged, so + // every state it names stayed active, and a spawn one declares isn't for an + // activation that ended. Its effects can also stop an actor explicitly, while the + // actor's state stays active (see stoppedByFire); a failed Fire emits no effects (the + // kernel returns none on every failure path), so that scan needs no such guard. + if nf.pf.Result.Err == nil { + for _, s := range nf.pf.Result.Trace.ExitedStates { + if p.exited == nil { + p.exited = map[string]bool{} + } + p.exited[s] = true + } } for _, eff := range nf.pf.Result.Effects { if e, ok := eff.(state.StopActor); ok {