diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index 59c0c5d..2b055fd 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -30,8 +30,11 @@ implement the `Store` interface out of tree. - **Deterministic replay.** A recovered instance is byte-identical to one that never crashed, because recovery replays the recorded driving events and nondeterministic results rather than re-executing their sources. -- **Exactly-once effects.** A domain effect from a step (not an initial entry, which is at-least-once, or a parent transition an actor drives, which is not dispatched) is applied exactly once over the - instance's lifetime (the live run plus any number of recoveries), even though +- **Exactly-once effects.** A domain effect from a step, including a parent + transition an actor drives (not an initial entry, which is at-least-once, or a + parent transition driven by an actor that `Start` or `Recover` spawned, which is + not dispatched yet: #269), is applied exactly once over the instance's lifetime + (the live run plus any number of recoveries), even though the replay loop is at-least-once. The exception is a crash or failed mark after the handler returned, or a handoff between owners, where it can apply twice, so keep handlers idempotent on `EffectInstance` plus the `EffectID`. Each effect carries a diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 5dfce2f..5168e28 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 +- **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 + message a `DeliverToActor` delivery drove — never reached the `EffectHandler`: the + step that drove the Fire journaled it but named only its own effects, so the effect + was never dispatched, live or on `Recover`, and an effect id re-derived by replay + deduplicated nothing. Now every such step — `Fire`, `Tick`, `DeliverToActor` and + `RunService` — names the driven Fires' effects after its own, in fire order, under + the same deterministic ids live and on replay, so `Recover` re-dispatches one a + crash kept from landing, exactly once. An actor delivery now dispatches after + releasing the step lock, as `Fire` does, so an effect handler can call back into the + same `Handle`. The parent Fires an actor spawned by `Start` or `Recover` drives run + before any step and still dispatch none of their effects. - **A settle a respawn drops runs no transform.** The drop a host's respawn replay makes (`AbsorbRespawn`) was decided after the settle transform ran, so a respawned nested child whose output differed from its first spawn's — a time, a random id, diff --git a/durable/README.md b/durable/README.md index ad32154..688bc30 100644 --- a/durable/README.md +++ b/durable/README.md @@ -31,8 +31,11 @@ backends implement the `Store` interface out of tree. - **Deterministic replay**: a recovered instance is byte-identical to one that never crashed, because recovery replays the recorded driving events and nondeterministic results rather than re-executing their sources. -- **Exactly-once effects**: a domain effect from a step (not an initial entry, which is at-least-once, or a parent transition an actor drives, which is not dispatched) is applied exactly once over the - instance's lifetime (the live run plus any number of recoveries), even though +- **Exactly-once effects**: a domain effect from a step, including a parent + transition an actor drives (not an initial entry, which is at-least-once, or a + parent transition driven by an actor that `Start` or `Recover` spawned, which is + not dispatched yet: #269), is applied exactly once over the instance's lifetime + (the live run plus any number of recoveries), even though the replay loop is at-least-once. The exception is a crash or failed mark after the handler returned, or a handoff between owners, where it can apply twice, so keep handlers idempotent on `EffectInstance` plus the `EffectID`. Each effect carries a diff --git a/durable/actor.go b/durable/actor.go index 72ca4be..8a49fc0 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -116,7 +116,10 @@ type actorMessagePayload struct { // 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 +// transition the delivery drove, persists the produced step, and dispatches the +// domain effects those transitions emitted once it is recorded, as Fire dispatches +// its own. A failed dispatch fails the Handle with ErrHandleFailed; the step stays +// recorded, and Recover sends its effects. 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 @@ -155,13 +158,35 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef if err := h.acquire(ctx); err != nil { return false, err } + delivered, rec, des, err := h.lockedDeliverStep(ctx, ref, event) + if rec == nil { + return delivered, err + } + // Dispatch after releasing the step lock, as Fire does, so an effect handler can + // call back into this Handle. The Record already names every effect (write-ahead), + // so a crash here leaves it for recovery to redispatch, deduped by id. + return delivered, errors.Join(err, h.finishStep(ctx, rec, des)) +} + +// lockedDeliverStep runs deliverStep and releases the step lock however it returns. +// A panic in host code fails the Handle first, since the kernel may have applied a +// parent Fire the delivery drove. +func (h *Handle[S, E, C]) lockedDeliverStep(ctx context.Context, ref state.ActorRef, event any) (bool, *Record, []dispatchableEffect, error) { defer h.release() defer h.failOnPanic() + return h.deliverStep(ctx, ref, event) +} + +// deliverStep is the part of DeliverToActor that holds the step lock: it runs the +// delivery and records the step, naming the domain effects of the parent Fires it +// drove, before any is dispatched. It returns a nil Record when nothing was +// recorded. ctx is the step's marked context. +func (h *Handle[S, E, C]) deliverStep(ctx context.Context, ref state.ActorRef, event any) (bool, *Record, []dispatchableEffect, error) { if err := h.refuse(ctx); err != nil { - return false, err + return false, nil, nil, err } if h.actors == nil { - return false, fmt.Errorf("durable: no actor palette wired for %q (supply WithActorPalette)", h.id) + return false, nil, nil, fmt.Errorf("durable: no actor palette wired for %q (supply WithActorPalette)", h.id) } stepCtx := h.stepContext(ctx) @@ -173,14 +198,14 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef }() fires := h.actorFires.take() if !delivered { - return false, nil + return false, nil, nil, 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)) + return true, nil, nil, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, err)) } // The actor's done-data wouldn't decode for its onDone event, or decodes as another // type than the actor produced: the settle aborted, firing nothing, so no Assign ran @@ -189,22 +214,45 @@ func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef // but the actor can run again. Fail the Handle and record nothing, so a recovered // Handle runs the actor from its initial state and the delivery again. if abort := h.actorFires.takeAborts(); abort != nil { - return true, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, abort)) + return true, nil, nil, h.fail(fmt.Errorf("durable: delivering to actor %q for %q: %w", ref.ID, h.id, abort)) } 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)) + return true, nil, nil, h.fail(fmt.Errorf("durable: recording actor %q result for %q: %w", ref.ID, h.id, err)) } - // A parent Fire the delivery drove can arm a timer, which reads the clock. Its effects - // aren't dispatched, so the step names none, and finishStep only offers its - // checkpoint. + // A parent Fire the delivery drove can arm a timer, which reads the clock, and can + // emit a domain effect, which the step dispatches as its own: the delivery itself + // produces no parent transition, so the driven Fires' effects are all it names. rec := &Record{Step: h.nextStep, Entries: append(h.drainClock(), entries...)} - if _, err := h.recordStep(ctx, rec, nil); err != nil { - return true, err + des, err := h.recordStep(ctx, rec, drivenFireEffects(nil, fires)) + if err != nil { + return true, nil, nil, err + } + return true, rec, des, nil +} + +// drivenFireEffects appends the effects of the parent Fires an actor system drove, in +// fire order, after a step's own effects, so the driving step names a parent +// transition an actor drove among the effects it dispatches: the step's own first, +// then each driven Fire's, in fire order. The stamped ids follow that order +// (dispatchableEffects numbers every dispatchable effect of one step), and replay +// reproduces it, re-firing the recorded Fires after the step's own work (see +// replayActors), so live and Recover stamp and dispatch the same ids. A refused Fire +// applied nothing and carries no effects; Fires that drove none leave the step's own +// effects unchanged. +func drivenFireEffects[S comparable](own []state.Effect, fires []notedFire[S]) []state.Effect { + var driven []state.Effect + for _, nf := range fires { + driven = append(driven, nf.pf.Result.Effects...) + } + if len(driven) == 0 { + return own } - return true, h.finishStep(ctx, rec, nil) + out := make([]state.Effect, 0, len(own)+len(driven)) + out = append(out, own...) + return append(out, driven...) } // DeliverToActorByID is DeliverToActor keyed by raw actor id, for a host that diff --git a/durable/actor_fire_effects_test.go b/durable/actor_fire_effects_test.go index db20cfd..cb92cda 100644 --- a/durable/actor_fire_effects_test.go +++ b/durable/actor_fire_effects_test.go @@ -2,7 +2,11 @@ package durable_test import ( "context" + "errors" + "slices" + "sync/atomic" "testing" + "time" "github.com/stablekernel/crucible/durable" "github.com/stablekernel/crucible/state" @@ -12,7 +16,6 @@ import ( // parent Fire emits, where an actor drove that Fire, is dispatched like the event // Fire's own: here a failed spawn's onError transition emits a notify. func TestFire_DispatchesTheEffectsOfAParentFireAnActorDrove(t *testing.T) { - t.Skip("a parent Fire an actor drove has its timers and services armed, but its domain effects aren't dispatched; see #257") ctx := context.Background() type cx struct{} m := state.ForgeFor[cx]("actorEffects"). @@ -45,3 +48,419 @@ func TestFire_DispatchesTheEffectsOfAParentFireAnActorDrove(t *testing.T) { t.Fatalf("dispatched %d effects, want the onError transition's notify", got) } } + +// actorEffectsEnd is one seam that drives a parent Fire an actor brought about — a +// Fire, a Tick, a RunService settle, or a DeliverToActor settle — with the machine +// that makes it, the state it starts in, how to drive it, and the state it ends in. +// Each machine routes one transition that emits a notify, so the seam's step owes +// exactly one domain effect, whatever driver effects also pass through it. +type actorEffectsEnd struct { + name string + machine func() *state.Machine[string, string, actorCtx] + initial string + drive func(t *testing.T, h *durable.Handle[string, string, actorCtx], clk *state.FakeClock) + final string +} + +// notifyAction builds the action every end's parent transition runs, emitting the +// notify the step must dispatch. +func notifyAction() func(state.ActionCtx[actorCtx]) (state.Effect, error) { + return func(state.ActionCtx[actorCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + } +} + +// TestActorDrivenFire_DispatchesItsDomainEffects pins that a domain effect a parent +// Fire an actor drove emits is dispatched however the actor was driven — a delivery's +// settle, a timer that spawned the actor, a service settle that spawned it — live by +// the step that drove it, and by Recover's replay of the journal that step wrote, so +// an effect that never landed applies exactly once across a crash (#257). +func TestActorDrivenFire_DispatchesItsDomainEffects(t *testing.T) { + ctx := context.Background() + ends := []actorEffectsEnd{ + { + // Fire: idle -start-> spawning, whose child can't start, so the onError + // spawnFailed drives the notify transition. + name: "Fire", + machine: func() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("fireEffects"). + Action("notify", notifyAction()). + 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() + }, + initial: "idle", + drive: func(t *testing.T, h *durable.Handle[string, string, actorCtx], _ *state.FakeClock) { + if _, err := h.Fire(ctx, "start"); err != nil { + t.Fatalf("Fire(start): %v", err) + } + }, + final: "failed", + }, + { + // DeliverToActor: working's finisher completes on "finish", so the settle's + // childDone drives the notify transition. + name: "DeliverToActor", + machine: func() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("deliverEffects"). + Action("notify", notifyAction()). + Actor("finisher"). + State("working").InvokeActor("finisher", state.WithInvokeOnDone("childDone")). + State("done"). + Initial("working"). + Transition("working").On("childDone").GoTo("done").Do("notify"). + Quench() + }, + initial: "working", + drive: func(t *testing.T, h *durable.Handle[string, string, actorCtx], _ *state.FakeClock) { + found, err := h.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("deliverEffects", "working", 0)}, "finish") + if !found || err != nil { + t.Fatalf("DeliverToActor = %v, %v", found, err) + } + }, + final: "done", + }, + { + // Tick: waiting's 10s timer enters spawning, whose child can't start, so the + // onError spawnFailed drives the notify transition within the tick's step. + name: "Tick", + machine: func() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("tickEffects"). + Action("notify", notifyAction()). + Actor("child"). + State("waiting"). + State("spawning").InvokeActor("child", state.WithInvokeOnError("spawnFailed")). + State("failed"). + Initial("waiting"). + Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed").Do("notify"). + Quench() + }, + initial: "waiting", + drive: func(t *testing.T, h *durable.Handle[string, string, actorCtx], clk *state.FakeClock) { + clk.Advance(10 * time.Second) + if _, err := h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + }, + final: "failed", + }, + { + // RunService: loading's fetch settles, and the loaded transition it drives + // enters spawning, whose child can't start, so the onError spawnFailed drives + // the notify transition within the settle's step. + name: "RunService", + machine: func() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("serviceEffects"). + Action("notify", notifyAction()). + Service("fetch", fetchOK). + Actor("child"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("loaded")). + State("spawning").InvokeActor("child", state.WithInvokeOnError("spawnFailed")). + State("failed"). + Initial("loading"). + Transition("loading").On("loaded").GoTo("spawning"). + Transition("spawning").On("spawnFailed").GoTo("failed").Do("notify"). + Quench() + }, + initial: "loading", + drive: func(t *testing.T, h *durable.Handle[string, string, actorCtx], _ *state.FakeClock) { + if _, ran, err := h.RunService(ctx, state.InvokeID("serviceEffects", "loading", 0)); !ran || err != nil { + t.Fatalf("RunService = %v, %v, want it to settle the fetch service", ran, err) + } + }, + final: "failed", + }, + } + for _, end := range ends { + for _, where := range []string{"live", "Recover"} { + t.Run(end.name+"/"+where, func(t *testing.T) { + clk := state.NewFakeClock(epoch) + opts := []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{ + "child": failingSpawn(nil), + "finisher": finishingChild(), + }), + } + // The live leg wires the handler up front, so the step that drives the + // parent Fire dispatches the notify itself. The Recover leg leaves it out, + // modeling a crash between the step's append and its dispatch: nothing is + // marked, so Recover's replay must send the effect the journal names. + rec := newEffectRecorder() + if where == "live" { + opts = append(opts, durable.WithEffectHandler[string, string, actorCtx](rec.handler())) + } + store, id := durable.NewMemStore(), durable.InstanceID("actorEffects-"+end.name) + h, err := durable.NewRunner(end.machine(), store, opts...).Start(ctx, id, actorCtx{}, state.WithInitialState(end.initial)) + if err != nil { + t.Fatalf("Start: %v", err) + } + end.drive(t, h, clk) + if got := h.Instance().Current(); got != end.final { + t.Fatalf("state = %q, want %q", got, end.final) + } + if where == "Recover" { + h, err = durable.Recover(ctx, end.machine(), store, id, + append(opts, durable.WithEffectHandler[string, string, actorCtx](rec.handler()))...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := h.Instance().Current(); got != end.final { + t.Fatalf("recovered state = %q, want %q", got, end.final) + } + } + if got := len(rec.values); got != 1 { + t.Fatalf("%s dispatched %d effects (%v), want the parent transition's notify once", where, got, rec.values) + } + }) + } + } +} + +// TestActorDrivenFire_EffectIDsPutTheStepsOwnFirst pins the id scheme's order rule: a +// step whose own transition emits an effect, and a parent Fire an actor drove that +// emits another, dispatches them under ids that name the step's own effect first, then +// the driven Fire's — and Recover, replaying the same step, stamps and dispatches the +// same ids in the same order, so an effect that never landed applies exactly once +// across the crash. +func TestActorDrivenFire_EffectIDsPutTheStepsOwnFirst(t *testing.T) { + ctx := context.Background() + // idle -start-> spawning runs "charge" (the step's own effect); the spawn fails, so + // its onError drives spawning -spawnFailed-> failed, which runs "notify" (the driven + // Fire's). + machine := func() *state.Machine[string, string, actorCtx] { + return state.ForgeFor[actorCtx]("ordered"). + Action("charge", func(state.ActionCtx[actorCtx]) (state.Effect, error) { + return chargeEffect{Cents: 500}, nil + }). + Action("notify", notifyAction()). + Actor("child"). + State("idle"). + State("spawning").InvokeActor("child", state.WithInvokeOnError("spawnFailed")). + State("failed").Final(). + Initial("idle"). + Transition("idle").On("start").GoTo("spawning").Do("charge"). + Transition("spawning").On("spawnFailed").GoTo("failed").Do("notify"). + Quench() + } + want := []string{"0#0#demo.charge", "0#1#demo.notify"} + for _, where := range []string{"live", "Recover"} { + t.Run(where, func(t *testing.T) { + // The live leg wires the handler up front; the Recover leg leaves it out, + // modeling a crash between the step's append and its dispatch, so replay + // must stamp the ids itself. + rec := newEffectRecorder() + opts := []greetOption{ + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{"child": failingSpawn(nil)}), + } + if where == "live" { + opts = append(opts, durable.WithEffectHandler[string, string, actorCtx](rec.handler())) + } + store, id := durable.NewMemStore(), durable.InstanceID("ordered-effects-"+where) + h, err := durable.NewRunner(machine(), store, opts...).Start(ctx, id, actorCtx{}, 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 where == "Recover" { + // The ids the recovered Handle stamps come from the journal, so the + // Handle itself is nothing the test needs past its error. + if _, rerr := durable.Recover(ctx, machine(), store, id, + append(opts, durable.WithEffectHandler[string, string, actorCtx](rec.handler()))...); rerr != nil { + t.Fatalf("Recover: %v", rerr) + } + } + if got := rec.order; !slices.Equal(got, want) { + t.Fatalf("%s dispatched %v, want %v: the step's own effect first, then the driven Fire's", where, got, want) + } + for _, id := range want { + if n := rec.count(id); n != 1 { + t.Fatalf("%s: effect %q applied %d times, want once", where, id, n) + } + } + }) + } +} + +// serviceAbortEffectsMachine invokes fetch in first; its onDone enters second, +// which invokes kid (routing childDone) and poker. The poker sends the parent +// "poke" as it starts, and the poke transition emits a notify and finishes kid, +// so kid settles — and its done-data hits the refusing decoder — inside the +// RunService step that settled fetch: the journal-service-first abort path, where +// the service's settle is recorded before the Handle fails on the actor's settle. +func serviceAbortEffectsMachine(fn state.ServiceFn[outcomeCtx]) *state.Machine[string, string, outcomeCtx] { + return state.ForgeFor[outcomeCtx]("svcabortfx"). + Action("notify", func(state.ActionCtx[outcomeCtx]) (state.Effect, error) { + return notifyEffect{To: "ops@example.com"}, nil + }). + Service("fetch", fn). + State("first").Invoke("fetch", state.WithInvokeOnDone("served")). + State("second"). + InvokeActor("kid", state.WithInvokeOnDone("childDone")). + InvokeActor("poker"). + Initial("first"). + Transition("first").On("served").GoTo("second"). + Transition("second").On("poke").GoTo("second").Do("notify"). + SendTo(state.ActorID("svcabortfx", "second", 0), "finish"). + Quench() +} + +// TestActorDrivenFire_DispatchesOnAServiceSettleAnActorAbortedIn pins #257's +// dispatch on the journal-service-first abort path: the service settle a step +// records before an actor settle the same step drove aborts still names the domain +// effect of the parent Fire it drove (the poke's notify), so the failed RunService +// dispatches it live through finishStep, and Recover's replay of the recorded +// settle re-fires the poke and re-dispatches its notify under the same id — exactly +// once across the crash, whatever driver effects (the poke's SendTo) the step also +// carried. +func TestActorDrivenFire_DispatchesOnAServiceSettleAnActorAbortedIn(t *testing.T) { + ctx := context.Background() + for _, where := range []string{"live", "Recover"} { + t.Run(where, func(t *testing.T) { + fn := state.ServiceFn[outcomeCtx](func(context.Context, state.ServiceCtx[outcomeCtx]) (any, error) { + return "ok", nil + }) + m := serviceAbortEffectsMachine(fn) + // The live leg wires the handler up front, so the failed step dispatches + // the notify itself before RunService returns. The Recover leg leaves it + // out, modeling a crash between the settle's append and its dispatch. + rec := newEffectRecorder() + opts := []durable.Option[string, string, outcomeCtx]{ + durable.WithServiceRegistry[string, string, outcomeCtx](state.NewRegistry[outcomeCtx]().Service("fetch", fn)), + durable.WithActorPalette[string, string, outcomeCtx](map[string]state.ActorBehavior{ + "kid": outputChild(new(int64), order{ID: 7}), + "poker": func(map[string]any) (state.ActorInstance, error) { return &poking{}, nil }, + }), + durable.WithEventDataDecoder[string, string, outcomeCtx](func(e string, data []byte) (any, error) { + if e == "childDone" { + return nil, errors.New("decoder refused") + } + return durable.DecodeAs[any](data) + }), + } + if where == "live" { + opts = append(opts, durable.WithEffectHandler[string, string, outcomeCtx](rec.handler())) + } + store, id := durable.NewMemStore(), durable.InstanceID("svcabort-fx-"+where) + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, outcomeCtx{}, state.WithInitialState("first")) + if err != nil { + t.Fatalf("Start: %v", err) + } + // The settle drives fetch's onDone into second, whose poker pokes the + // parent: the poke transition emits the notify and finishes kid, whose + // settle the decoder refuses. The step fails the Handle with the actor's + // abort, but the service settle it recorded — journal-service-first — + // already names the poke's notify. + _, ran, err := h.RunService(ctx, state.InvokeID("svcabortfx", "first", 0)) + if !ran { + t.Fatal("RunService reported the service not in flight; want it ran and settled") + } + if !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("RunService = %v; want ErrHandleFailed wrapping the actor settle's ErrEventDataEncoding", err) + } + if got := h.Instance().Current(); got != "second" { + t.Fatalf("state = %q, want second by the recorded settle", got) + } + if where == "Recover" { + h, err = durable.Recover(ctx, m, store, id, + append(opts, durable.WithEffectHandler[string, string, outcomeCtx](rec.handler()))...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := h.Instance().Current(); got != "second" { + t.Fatalf("recovered state = %q, want second: the recorded settle replayed", got) + } + } + if got := len(rec.values); got != 1 { + t.Fatalf("%s dispatched %d effects (%v), want the poke transition's notify once", where, got, rec.values) + } + for effectID, n := range rec.counts { + if n != 1 { + t.Fatalf("%s: effect %q applied %d times, want once", where, effectID, n) + } + } + }) + } +} + +// TestDeliverToActor_AnEffectHandlerCallsBackIntoTheHandle pins that an effect +// handler dispatched from a delivery can call back into the same Handle: a +// delivery's step names the effects of the parent Fires it drove, and +// DeliverToActor dispatches them after releasing the step lock, as Fire does, so +// the handler's View and Fire both succeed — neither deadlocking on the step +// lock its dispatch would hold, nor meeting ErrReentrantStep. waitFor bounds it, +// so a regression that dispatches under the lock fails instead of hanging. +func TestDeliverToActor_AnEffectHandlerCallsBackIntoTheHandle(t *testing.T) { + ctx := context.Background() + // working holds a finisher; delivering "finish" settles it, and the settle's + // childDone drives working -childDone-> done, whose notify the delivery's step + // dispatches. The handler then Views the settled parent and Fires "bill" on it. + m := state.ForgeFor[actorCtx]("deliverCallback"). + Action("notify", notifyAction()). + Actor("finisher"). + State("working").InvokeActor("finisher", state.WithInvokeOnDone("childDone")). + State("done"). + State("billed"). + Initial("working"). + Transition("working").On("childDone").GoTo("done").Do("notify"). + Transition("done").On("bill").GoTo("billed"). + Quench() + var h *durable.Handle[string, string, actorCtx] + var calledBack atomic.Bool + var viewErr, fireErr error + var saw string + handler := func(ctx context.Context, _ string, _ state.Effect) error { + if calledBack.CompareAndSwap(false, true) { + viewErr = h.View(ctx, func(inst *state.Instance[string, string, actorCtx]) { + saw = inst.Current() + }) + _, fireErr = h.Fire(ctx, "bill") + } + return nil + } + h, err := durable.NewRunner(m, durable.NewMemStore(), + durable.WithEffectHandler[string, string, actorCtx](handler), + durable.WithActorPalette[string, string, actorCtx](map[string]state.ActorBehavior{ + "finisher": finishingChild(), + }), + ).Start(ctx, "deliver-callback", actorCtx{}, state.WithInitialState("working")) + if err != nil { + t.Fatalf("Start: %v", err) + } + delivered := make(chan struct{}) + go func() { + defer close(delivered) + _, err = h.DeliverToActor(ctx, state.ActorRef{ID: state.ActorID("deliverCallback", "working", 0)}, "finish") + }() + waitFor(t, delivered, "DeliverToActor(finish)") + if err != nil { + t.Fatalf("DeliverToActor(finish) = %v, want nil", err) + } + if !calledBack.Load() { + t.Fatal("the effect handler never ran: the delivery's step named no effect") + } + if viewErr != nil { + t.Fatalf("the handler's View = %v, want nil", viewErr) + } + if saw != "done" { + t.Fatalf("the handler's View saw state %q, want done: the childDone already applied", saw) + } + if fireErr != nil { + t.Fatalf("the handler's Fire(bill) = %v, want nil", fireErr) + } + if got := h.Instance().Current(); got != "billed" { + t.Fatalf("state = %q, want billed by the handler's Fire", got) + } +} diff --git a/durable/doc.go b/durable/doc.go index f8f1ef0..7522a06 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -17,10 +17,12 @@ // recovery replays the exact recorded driving events and nondeterministic results // through the same pure transition function. // -// Exactly-once effects: a domain effect emitted by a step (Runner.Start's initial entry -// is at-least-once, and a parent transition an actor drives isn't dispatched) is applied -// exactly once over the instance's lifetime — the live run plus any number of -// recoveries — even though the runtime's replay loop is at-least-once. The exception is +// Exactly-once effects: a domain effect emitted by a step, including a parent +// transition an actor drives (Runner.Start's initial entry is at-least-once, and a +// parent transition driven by an actor that Start or Recover spawned isn't dispatched +// yet; see #269), is applied exactly once over the instance's lifetime — the live run +// plus any number of recoveries — even though the runtime's replay loop is +// at-least-once. The exception is // a crash or failed mark after the handler returned, or a handoff between owners, where // an effect can apply twice, so keep handlers idempotent on EffectInstance plus the EffectID. Each // effect is stamped with a deterministic EffectID (step, ordinal, kind) and diff --git a/durable/effect.go b/durable/effect.go index be215cc..4aea65a 100644 --- a/durable/effect.go +++ b/durable/effect.go @@ -41,6 +41,13 @@ import ( // same order. That stable identity is what makes the dedup set meaningful across // the crash boundary. // +// A step an actor system drove — a Fire, a Tick, an actor delivery, or a service +// settle — dispatches the domain effects of the parent Fires the actor drove as its +// own: the step's own effects come first, then each actor-driven parent Fire's, in +// fire order (see drivenFireEffects). Replay re-fires the recorded Fires after the +// step's own work, in the same order, so the ordinal component places a driven +// Fire's effect identically on the live run and on every recovery. +// // # Write-ahead, exactly-once // // The ordering is the contract: @@ -169,7 +176,9 @@ func isDriverEffect(e state.Effect) bool { // dispatchableEffects filters a step's emitted effects to the domain effects the // handler applies and stamps each with its deterministic EffectID, preserving -// emission order. The ordinal counts only dispatchable effects, so a domain +// emission order. A step that an actor system drove names the driven Fires' effects +// after its own, in fire order (see drivenFireEffects), so their ordinals follow the +// step's own. The ordinal counts only dispatchable effects, so a domain // effect's id is independent of how many interleaved driver effects the step also // emitted — keeping it stable if the driver-effect set ever changes around it. func dispatchableEffects(step int, effects []state.Effect) []dispatchableEffect { diff --git a/durable/runner.go b/durable/runner.go index e5a084d..52f88b1 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -1204,7 +1204,9 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi } rec := &Record{Step: h.nextStep, Event: []byte(res.Trace.EventPayload), EventData: payload.data, EventDataError: payload.errMsg, Entries: append(h.drainClock(), driven...)} - des, err := h.recordStep(ctx, rec, res.Effects) + // The driven Fires' effects follow the step's own, in fire order, so their stamped + // ids and their dispatch order match replay's (see drivenFireEffects). + des, err := h.recordStep(ctx, rec, drivenFireEffects(res.Effects, fires)) if err != nil { return res, nil, nil, err } @@ -1216,8 +1218,7 @@ func (h *Handle[S, E, C]) fireStep(ctx context.Context, event E, opts []state.Fi // append durably names every effect that must be dispatched before any dispatch // happens, then appends rec and advances the next step. A step with effects is marked // dispatching, so no checkpoint compacts it until finishStep, which the caller runs -// after releasing the step lock, has dispatched them; a step with no effects to dispatch -// may run finishStep under the lock, as DeliverToActor does. The kernel has already +// after releasing the step lock, has dispatched them. The kernel has already // applied the step, so a failed encode or append fails the Handle; a failed checkpoint // doesn't, because the Record is durable. This relies on the Append running inline, // under the step lock, before the step returns: an Append deferred off this goroutine @@ -1420,7 +1421,9 @@ func (h *Handle[S, E, C]) tickStep(ctx context.Context) ([]state.FireResult[S], return results, nil, nil, h.fail(fmt.Errorf("durable: recording %q's parent Fires: %w", h.id, err)) } rec := &Record{Step: h.nextStep, Tick: true, TickSteps: len(results), Entries: append(h.drainClock(), driven...)} - des, err := h.recordStep(ctx, rec, effects) + // The driven Fires' effects follow the tick's own, in fire order, so their stamped + // ids and their dispatch order match replay's (see drivenFireEffects). + des, err := h.recordStep(ctx, rec, drivenFireEffects(effects, fires)) if err != nil { return results, nil, nil, err } @@ -2356,11 +2359,14 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { // it, running no service, actor or effect handler. Recover and StateAt both walk the // journal with it; Recover adds its deadline table, which mirror tracks, and effect // re-dispatch on top. A nil mirror tracks no deadlines. It returns the effects of the -// step's own work, a plain event's, a settlement's or a tick's timers', so Recover can -// re-dispatch their domain effects; nil for any other Record. +// step's own work, a plain event's, a settlement's or a tick's timers', followed by +// the parent Fires an actor drove within the step, in fire order, as the live step +// named them among its own (see drivenFireEffects), so Recover can re-dispatch their +// domain effects under the ids live stamped; nil for any other Record. // // - Parent Fires a Start's or Recover's spawns drove, recorded with the next step, -// re-fire first, before the step's own work. +// re-fire first, before the step's own work. Their effects are armed but not +// returned: no live path dispatches them, so Recover sends none. // - 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 @@ -2400,7 +2406,9 @@ func replayRecord[S comparable, E comparable, C any]( return stepEffects, fmt.Errorf("at step %d: %w", rec.Step, err) } // Parent Fires a Start's or Recover's spawns drove ran before the step's own work. - if err := replayActors(ctx, inst, cfg, sched, svc, rec, before, mirror, actorArms); err != nil { + // Their effects aren't returned: no live path dispatches them (see the + // Start-spawned note above). + if _, err := replayActors(ctx, inst, cfg, sched, svc, rec, before, mirror, actorArms); err != nil { return stepEffects, err } switch { @@ -2474,13 +2482,22 @@ 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 stepEffects, replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror, actorArms) -} - -// replayActors re-fires recorded parent transitions, in order. When actorArms, the -// version that wrote rec armed the timers and services an actor-driven Fire declares, -// so each one arms them, as the live run did. An older version armed none, and took no + // drove after it, such as a spawned actor's onError. Their effects follow the + // step's own, in fire order, as the live step named them, so Recover re-dispatches + // a driven Fire's domain effects under the ids live stamped. + driven, derr := replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror, actorArms) + if derr != nil { + return stepEffects, derr + } + return append(stepEffects, driven...), nil +} + +// replayActors re-fires recorded parent transitions, in order, and returns the effects +// each re-fired transition produced, in fire order, for the caller to fold into the +// step's dispatchable effects after the step's own, as the live step named them. +// 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, @@ -2492,19 +2509,21 @@ func replayActors[S comparable, E comparable, C any]( entries []decodedActorEntry, mirror *armMirror, actorArms bool, -) error { +) ([]state.Effect, error) { + var driven []state.Effect for _, entry := range entries { effects, err := replayActor(ctx, inst, cfg.eventCodec, cfg.eventDataDecoder, cfg.resultAliases, entry) if err != nil { - return fmt.Errorf("at step %d: %w", rec.Step, err) + return nil, fmt.Errorf("at step %d: %w", rec.Step, err) } if actorArms { replayArm(ctx, sched, svc, effects, mirror) } else { mirror.forget(effects) } + driven = append(driven, effects...) } - return nil + return driven, nil } // checkFormat fails when rec's journal Format is lower than the checkpoint's that replay diff --git a/durable/service.go b/durable/service.go index 014039c..d9c73fb 100644 --- a/durable/service.go +++ b/durable/service.go @@ -322,7 +322,9 @@ func (h *Handle[S, E, C]) serviceStep(ctx context.Context, id string) (state.Fir // Arming a timer the settle's state declares reads the clock, so the step carries // its reads. rec := &Record{Step: h.nextStep, Entries: append(append(h.drainClock(), h.drainServices()...), driven...)} - des, err := h.recordStep(ctx, rec, res.Effects) + // The driven Fires' effects follow the settle's own, in fire order, so their stamped + // ids and their dispatch order match replay's (see drivenFireEffects). + des, err := h.recordStep(ctx, rec, drivenFireEffects(res.Effects, fires)) if err != nil { if abort != nil { // The Handle already failed on the append; join the actor's abort so the diff --git a/state/settle_abort_test.go b/state/settle_abort_test.go index 412b090..5c6fc0f 100644 --- a/state/settle_abort_test.go +++ b/state/settle_abort_test.go @@ -291,55 +291,77 @@ func TestSettle_ATransformSettlingItsOwnActorIsRefused(t *testing.T) { } // TestWithSettleTransform_ARewrittenFailureNothingRoutesEscalates proves a -// transform can't make a child's failure vanish: a failure whose settle the -// transform rewrote into a success nothing routes — the invocation wired an -// onError but no onDone — escalates the ORIGINAL error to the parent, as the -// failure does with no transform at all, rather than settling a success nothing -// consumes and nothing observes. LastOutput still reports the rewritten outcome. +// transform can't make a child's failure vanish, whichever wiring the child +// arrived through: a failure whose settle the transform rewrote into a success +// nothing routes — the invocation wired an onError but no onDone — escalates the +// ORIGINAL error to the parent, as the failure does with no transform at all, +// rather than settling a success nothing consumes and nothing observes. The +// table runs both wirings: an actor a transition spawns (Spawn) and one a state +// invokes (InvokeActor, wired with only WithInvokeOnError). LastOutput still +// reports the rewritten outcome. func TestWithSettleTransform_ARewrittenFailureNothingRoutesEscalates(t *testing.T) { ctx := context.Background() - m := state.ForgeFor[*trec]("vanish"). - State("idle"). - State("supervising"). - Initial("idle"). - Transition("idle").On("start").GoTo("supervising").Spawn("child", "vanish-kid", state.WithSpawnOnError("childErr")). - Quench() - parent := m.Cast(&trec{}, state.WithInitialState[string]("idle")) - sys := state.NewActorSystem(parent).Register("child", settleChildBehavior()) - sys.WithSettleTransform(func(event string, output any, err error) (any, error, error) { - if err != nil { - // Recover it into a success nothing routes. - return "recovered", nil, nil - } - return output, err, nil - }) - res := parent.Fire(ctx, "start") - sys.Absorb(ctx, res.Effects) - if parent.Current() != "supervising" { - t.Fatalf("parent state = %q, want supervising", parent.Current()) - } + for _, tc := range []struct { + name string + wire func() *state.Machine[string, string, *trec] + }{ + {"a transition Spawn", func() *state.Machine[string, string, *trec] { + return state.ForgeFor[*trec]("vanish"). + State("idle"). + State("supervising"). + Initial("idle"). + Transition("idle").On("start").GoTo("supervising"). + Spawn("child", "vanish-kid", state.WithSpawnOnError("childErr")). + Quench() + }}, + {"a state InvokeActor", func() *state.Machine[string, string, *trec] { + return state.ForgeFor[*trec]("vanish"). + State("idle"). + State("supervising").InvokeActor("child", state.WithInvokeOnError("childErr"), state.WithInvokeID("vanish-kid")). + Initial("idle"). + Transition("idle").On("start").GoTo("supervising"). + Quench() + }}, + } { + t.Run(tc.name, func(t *testing.T) { + parent := tc.wire().Cast(&trec{}, state.WithInitialState[string]("idle")) + sys := state.NewActorSystem(parent).Register("child", settleChildBehavior()) + sys.WithSettleTransform(func(event string, output any, err error) (any, error, error) { + if err != nil { + // Recover it into a success nothing routes. + return "recovered", nil, nil + } + return output, err, nil + }) + res := parent.Fire(ctx, "start") + sys.Absorb(ctx, res.Effects) + if parent.Current() != "supervising" { + t.Fatalf("parent state = %q, want supervising", parent.Current()) + } - routed, ok := sys.SettleError(ctx, "vanish-kid", errors.New("boom")) - if ok || routed.Err != nil { - t.Fatalf("SettleError = %+v, %v; want nothing routed: the rewritten outcome has no onDone", routed, ok) - } - if parent.Current() != "supervising" { - t.Fatalf("parent state = %q, want supervising: nothing fired", parent.Current()) - } - if n := len(parent.Entity().notes); n != 0 { - t.Fatalf("the settle ran %d Assigns, want none", n) - } - // The ORIGINAL failure escalated — a transform may rewrite the outcome, not - // erase the failure — and the rewritten outcome is what LastOutput reports. - esc := sys.LastEscalation() - if esc == nil || esc.ActorID != "vanish-kid" || esc.Err == nil || esc.Err.Error() != "boom" { - t.Fatalf("LastEscalation = %+v, want the ORIGINAL boom escalated for the vanished failure", esc) - } - if out, got := sys.LastOutput(); !got || out != "recovered" { - t.Fatalf("LastOutput = %v, %v; want the rewritten outcome \"recovered\"", out, got) - } - if sys.IsRunning("vanish-kid") { - t.Fatal("the actor didn't settle") + routed, ok := sys.SettleError(ctx, "vanish-kid", errors.New("boom")) + if ok || routed.Err != nil { + t.Fatalf("SettleError = %+v, %v; want nothing routed: the rewritten outcome has no onDone", routed, ok) + } + if parent.Current() != "supervising" { + t.Fatalf("parent state = %q, want supervising: nothing fired", parent.Current()) + } + if n := len(parent.Entity().notes); n != 0 { + t.Fatalf("the settle ran %d Assigns, want none", n) + } + // The ORIGINAL failure escalated — a transform may rewrite the outcome, not + // erase the failure — and the rewritten outcome is what LastOutput reports. + esc := sys.LastEscalation() + if esc == nil || esc.ActorID != "vanish-kid" || esc.Err == nil || esc.Err.Error() != "boom" { + t.Fatalf("LastEscalation = %+v, want the ORIGINAL boom escalated for the vanished failure", esc) + } + if out, got := sys.LastOutput(); !got || out != "recovered" { + t.Fatalf("LastOutput = %v, %v; want the rewritten outcome \"recovered\"", out, got) + } + if sys.IsRunning("vanish-kid") { + t.Fatal("the actor didn't settle") + } + }) } }