diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index ca59d13..25606c4 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -17,7 +17,7 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. onError was refused because a context ended, so `Recover` can tell them from the actors that were running. A Store must keep an empty set distinct from nil. - **`Record.Format`** records the journal format of the version that wrote the Record, - which is 2 from this version. Replay arms the timers and services an actor-driven + which is 3 from this version. Replay arms the timers and services an actor-driven parent Fire's state declares only for a Record of format 1 or later. `Recover` sends a tick's and a service settle's effects, and replay hands a tick's timer transitions' effects to the service runner, only for a Record of format 2 or later. @@ -86,8 +86,10 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. entry with no event, replays as the zero event. An older `durable` also ignores the recorded ended actors and spawns them again, and replays a step that records actor entries as a delivery, skipping its event, settle or tick. It also spawns a running - actor as new, so a message the actor sent its parent as it started applies twice. Don't downgrade a Store this version has - written to. + actor as new, so a message the actor sent its parent as it started applies twice. An + older `durable`'s `Recover` re-arms a baseline's or checkpoint's timers only after the + tail, so it misses one a tail tick fired, with no error, and its `StateAt` ignores a + baseline's timers. 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 @@ -243,6 +245,32 @@ 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. +- **Timers survive recovery.** `Start` now arms the initial state's timers, which it never + did, so a new instance starting in a timed state fires a timer it didn't before. It + carries them in the baseline; an instance started earlier keeps its initial timer + unarmed. It arms them even when the initial entry failed, as it already starts that + state's services and actors. Recovery re-arms checkpointed timers before the tail + replays, so one fired in the tail isn't missed. `StateAt` re-arms baseline timers too, + so its result changes when one fires in the window, and it fails if a timer's event won't decode with + the options passed; `transport`'s time-travel view passes none, so it fails there for a + machine whose timer events need a custom codec. +- **A replayed tick must fire what it recorded.** `Recover` and `StateAt` now fail when a + tick of journal format 3 or later fires a different number of timers on replay than + its Record says, rather than replaying the following steps in another state. An older + Record isn't checked: an older version's recovery re-armed a checkpoint's timers after + the tail, so a journal it continued can record a timer the tail had fired or canceled + firing again. A canceled one it revived usually fired into a refusal, and replays to + the same state. If the state it was in then takes the timer's event, or the timer + fired twice, replay diverges from that run with no error, as that version's own replay + did. +- **A tick that fires nothing records nothing.** It used to append a Record every time, + so a timer loop grew the journal while a timer was pending. An idle `Tick` doesn't touch + the Store, so it can't report `ErrFenced` or a Store failure: a stale owner finds out on + its next real step. An idle tick also takes no step number and doesn't count toward + `WithCheckpointEvery`. Replay reads an older journal's idle tick Record as nothing fired. + A recorded reading no replayed step consumed is no longer returned to the first timer + armed after `Recover`. An older journal whose settle put its clock read in the next + Record can still arm a replayed timer at the wrong instant (#262). - **Effects reach the handler from `Start`, `Tick` and `RunService`.** They were only dispatched from `Fire`. `Start` applies the initial entry's effects after encoding the baseline and before writing it, and only if the entry succeeded. Those effects are diff --git a/durable/checkpoint.go b/durable/checkpoint.go index 1239204..b85fa13 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -23,10 +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, -// 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. +// re-arms it at that deadline rather than for 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 @@ -40,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 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 @@ -161,7 +161,7 @@ func decodeTimerEvent[E comparable](codec EventCodec[E], raw json.RawMessage) (E // mirrorArmed folds the ScheduleAfter/CancelScheduled effects of a replayed step // into the armed timer table at the recorded instant now, so recovery tracks which -// timers the tail replay re-established and at what deadlines. It is the replay-side +// timers are pending as the tail replays, and at what deadlines. It is the replay-side // analog of the Handle's live arming, sharing the recorded clock read rather than a // live one. func mirrorArmed(armed map[string]pendingTimer, effects []state.Effect, now time.Time) { @@ -175,27 +175,20 @@ 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. +// reArmEffects builds the ScheduleAfter effects that re-arm persisted timers at their +// recorded absolute deadlines, relative to now. now can be any fixed instant: the caller +// holds the scheduler's clock on it while absorbing the effects, so each timer's deadline +// comes out exact, and an elapsed one fires on the next Tick. Recovery calls it before +// the tail replays, because the tail can fire these timers. Returns the effects and the +// durable-side pending-timer table. func reArmEffects[E comparable]( codec EventCodec[E], wires []pendingTimerWire, - 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 nil, nil, fmt.Errorf("durable: decoding pending timer %q event: %w", w.ID, err) diff --git a/durable/checkpoint_internal_test.go b/durable/checkpoint_internal_test.go index 282ee6a..da813b9 100644 --- a/durable/checkpoint_internal_test.go +++ b/durable/checkpoint_internal_test.go @@ -81,22 +81,19 @@ 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) { +// TestReArmEffects_RemainingDelay confirms a persisted timer is re-armed with a delay +// that lands on its deadline from the instant passed. +func TestReArmEffects_RemainingDelay(t *testing.T) { now := time.Unix(0, 1_000_000_000).UTC() 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) + effects, seeded, err := reArmEffects[string](jsonEventCodec[string]{}, wires, 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)) + t.Fatalf("want the timer re-armed, got effects=%d seeded=%d", len(effects), len(seeded)) } sa, ok := effects[0].(state.ScheduleAfter) if !ok || sa.ID != "compacted" { @@ -107,15 +104,14 @@ func TestReArmEffects_SkipsAlreadyArmed(t *testing.T) { } } -// 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. +// TestReArmEffects_ElapsedDeadlineImmediate confirms reArmEffects gives a deadline at or +// before the instant passed a non-positive delay, which the scheduler arms as due. 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"`)}, } - effects, _, err := reArmEffects[string](jsonEventCodec[string]{}, wires, map[string]pendingTimer{}, now) + effects, _, err := reArmEffects[string](jsonEventCodec[string]{}, wires, now) if err != nil { t.Fatalf("reArmEffects: %v", err) } @@ -133,7 +129,7 @@ func TestReArmEffects_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)) + _, _, err := reArmEffects[string](jsonEventCodec[string]{}, wires, time.Unix(0, 0)) if err == nil { t.Fatal("want decode error for corrupt timer event, got nil") } diff --git a/durable/clock.go b/durable/clock.go index 7351d69..ff82905 100644 --- a/durable/clock.go +++ b/durable/clock.go @@ -12,10 +12,12 @@ import ( // its host driver (the state.Scheduler armed and ticked by the durable Handle) — // the kernel's Fire step never reads a clock. The Runner therefore wraps the real // state.Clock in a recordingClock on the live path and a replayClock on recovery, -// so every Now() reading the scheduler consumes is journaled and returned -// verbatim on replay. This makes timer firing wall-clock-independent: a recovered -// instance re-derives the same deadlines and fires the same timers at the same -// recorded instants, regardless of the wall clock at recovery time. +// so the Now() readings of each recorded step are journaled and returned verbatim +// on replay. Two kinds of reading belong to no step and aren't journaled: the one Start +// takes arming the initial state's timers, and an idle Tick's reads. This makes timer +// firing wall-clock-independent: a recovered instance re-derives the same deadlines and +// fires the same timers at the same recorded instants, regardless of the wall clock at +// recovery time. // // # What triggers a clock read // @@ -33,7 +35,9 @@ import ( // which they occurred (the step whose Fire/Tick produced them), in read order. // Replay is order-driven, not step-keyed: the replayClock walks every recorded // JournalClockRead across the loaded tail in recorded order and returns each -// reading once, so the scheduler re-derives identical deadlines. +// reading once, so the scheduler re-derives identical deadlines. Re-arming +// checkpointed timers holds the clock on a fixed instant instead, and replay skips +// the readings of an older journal's idle tick Record. // recordingClock wraps a real state.Clock and records every Now() reading as a // JournalClockRead into a shared buffer, in read order. After delegates to the @@ -98,6 +102,17 @@ func (c *recordingClock) markBuf() int { return len(*c.buf) } +// dropFrom discards the readings recorded at index i and after, under the clock mutex: +// an idle Tick drops its own reads this way and keeps the ones before them, which an +// earlier, still unrecorded parent Fire took. +func (c *recordingClock) dropFrom(i int) { + c.mu.Lock() + defer c.mu.Unlock() + if i >= 0 && i < len(*c.buf) { + *c.buf = (*c.buf)[:i] + } +} + // armReadingAt returns the clock reading recorded at index i, ok false when the // buffer holds no entry there (no read was appended). Taken under the clock mutex // so it does not race a concurrent Now(). @@ -116,8 +131,8 @@ func (c *recordingClock) armReadingAt(i int) (time.Time, bool) { // recordingClock: Now advances a cursor over the recorded JournalClockRead // 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 +// When the cursor is exhausted — a Now() once replay has consumed or skipped every +// reading, on live continuation after Recover — 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 { @@ -125,11 +140,12 @@ type replayClock struct { readings []int64 cursor int fallback state.Clock - last time.Time // the reading Now last returned + held *time.Time // a fixed reading set by hold, nil otherwise + last time.Time // the reading Now last returned outside a hold } // 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 (live continuation after Recover). func newReplayClock(readings []int64, fallback state.Clock) *replayClock { return &replayClock{readings: readings, fallback: fallback} } @@ -139,6 +155,9 @@ func newReplayClock(readings []int64, fallback state.Clock) *replayClock { func (c *replayClock) Now() time.Time { c.mu.Lock() defer c.mu.Unlock() + if c.held != nil { + return *c.held + } if c.cursor < len(c.readings) { c.last = time.Unix(0, c.readings[c.cursor]).UTC() c.cursor++ @@ -156,6 +175,41 @@ func (c *replayClock) lastRead() time.Time { return c.last } +// skipTo moves the cursor forward to reading n and never back, past readings no replayed +// step consumes. +func (c *replayClock) skipTo(n int) { + c.mu.Lock() + defer c.mu.Unlock() + if c.cursor < n { + c.cursor = n + } +} + +// clockReadCount returns how many clock readings rec holds. +func clockReadCount(rec *Record) int { + n := 0 + for _, e := range rec.Entries { + if e.Kind == state.JournalClockRead { + n++ + } + } + return n +} + +// hold makes Now return t without consuming a reading, until release. +func (c *replayClock) hold(t time.Time) { + c.mu.Lock() + defer c.mu.Unlock() + c.held = &t +} + +// release ends a hold. +func (c *replayClock) release() { + c.mu.Lock() + defer c.mu.Unlock() + c.held = nil +} + // After delegates to the fallback clock; replay drives elapses through Now + Tick // over the recorded readings, so After is never relied on during replay. func (c *replayClock) After(d time.Duration) <-chan time.Time { return c.fallback.After(d) } diff --git a/durable/clock_internal_test.go b/durable/clock_internal_test.go index a0a0124..af6ad2a 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 (live continuation after Recover). func TestReplayClock_ReturnsRecordedThenFallsThrough(t *testing.T) { readings := []int64{ clockEpoch.UnixNano(), diff --git a/durable/clock_test.go b/durable/clock_test.go index 85d24db..ab339ac 100644 --- a/durable/clock_test.go +++ b/durable/clock_test.go @@ -414,3 +414,97 @@ func recoverTimerBytes(t *testing.T, ctx context.Context, m *state.Machine[strin } return string(b) } + +// TestClock_StartInTimedState_ArmsTimer proves Start arms the `after` timer of the +// state an instance starts in, as a host absorbing InitialEffects does, and that recovery +// reaches the same state. +func TestClock_StartInTimedState_ArmsTimer(t *testing.T) { + ctx := context.Background() + m := timerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, *timerCtx]{durable.WithRunnerClock[string, string, *timerCtx](clk)} + runner := durable.NewRunner(m, store, opts...) + h, err := runner.Start(ctx, id, &timerCtx{}, state.WithInitialState("arming")) + if err != nil { + t.Fatalf("Start: %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 != "done" { + t.Fatalf("state %q 6s after starting in arming, want done", got) + } + + // A clock still at the start proves the timer replays at its recorded instant. + recovered, err := durable.Recover(ctx, m, store, id, durable.WithRunnerClock[string, string, *timerCtx](state.NewFakeClock(epoch))) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if live, got := handleSnapshot(t, h), handleSnapshot(t, recovered); got != live { + t.Fatalf("recovered instance differs from live:\n live: %s\n got: %s", live, got) + } +} + +// TestClock_TickWithNothingDue_AppendsNoRecord proves a timer loop ticking while a +// timer is pending but not yet due does not grow the journal. +func TestClock_TickWithNothingDue_AppendsNoRecord(t *testing.T) { + ctx := context.Background() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := state.NewFakeClock(epoch) + runner := durable.NewRunner(timerMachine(), store, durable.WithRunnerClock[string, string, *timerCtx](clk)) + h, err := runner.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) + } + for range 100 { + clk.Advance(10 * time.Millisecond) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + } + _, after, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(after) != len(before) { + t.Fatalf("100 ticks before the 5s timer was due grew the journal from %d to %d records", len(before), len(after)) + } +} + +// TestClock_TickWithNoTimer_AppendsNoRecord proves a timer loop ticking an instance with no +// timer armed does not grow the journal. +func TestClock_TickWithNoTimer_AppendsNoRecord(t *testing.T) { + ctx := context.Background() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := state.NewFakeClock(epoch) + runner := durable.NewRunner(timerMachine(), store, durable.WithRunnerClock[string, string, *timerCtx](clk)) + h, err := runner.Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for range 100 { + clk.Advance(10 * time.Millisecond) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(tail) != 0 { + t.Fatalf("100 ticks with no timer armed appended %d records", len(tail)) + } +} diff --git a/durable/doc.go b/durable/doc.go index 0cf8851..ea322b0 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -92,15 +92,14 @@ // // Clock (WithRunnerClock): a running instance reads time only through its host // scheduler, which arms and ticks delayed `after` transitions. The Runner wraps -// the real clock in a recording clock on the live path so every Now() reading the -// scheduler consumes is journaled as a JournalClockRead in the step's Record. +// the real clock in a recording clock on the live path so the Now() readings of a step +// are journaled as JournalClockRead entries in its Record. An idle Tick records nothing. // On recovery a replay clock returns those readings in order, making timer-driven // transitions wall-clock-independent: the same timers fire at the same recorded // 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. +// checkpoint compaction: the baseline and each checkpoint persist the absolute +// deadlines of the timers armed at that instant, and recovery re-arms them at those +// deadlines before the tail replays, so a tail step can fire, cancel or replace them. // // 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/effects_dropped_store_test.go b/durable/effects_dropped_store_test.go index 204ee2c..c18ea13 100644 --- a/durable/effects_dropped_store_test.go +++ b/durable/effects_dropped_store_test.go @@ -158,3 +158,34 @@ func TestRecover_OlderVersionsFireEffectIsSentWithoutEnvelopes(t *testing.T) { } assertAppliedOnceAsLive(t, live, healthy, 1) } + +// asFormatOne copies src's journal for id into a fresh MemStore with the checkpoint and +// every Record of journal format 1, older than tickDriversFormat: a version that still +// recorded idle ticks and left a settle's clock read for the next Record, so a test can +// hand-build the Records such a version left. +func asFormatOne(t *testing.T, src *durable.MemStore, id durable.InstanceID) *durable.MemStore { + t.Helper() + return asFormat(t, src, id, 1) +} + +// asFormat copies src's journal for id into a fresh MemStore with the checkpoint and +// every Record of journal format `format`, as a version that wrote it left them. +func asFormat(t *testing.T, src *durable.MemStore, id durable.InstanceID, format int) *durable.MemStore { + t.Helper() + ctx := context.Background() + snap, recs, err := src.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + dst := durable.NewMemStore() + if err = dst.Checkpoint(ctx, id, withCheckpointFormat(t, snap, format), -1); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + for _, rec := range recs { + rec.Format = format + if _, err = dst.Append(ctx, id, rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + return dst +} diff --git a/durable/idle_tick_pending_test.go b/durable/idle_tick_pending_test.go new file mode 100644 index 0000000..b2ece6b --- /dev/null +++ b/durable/idle_tick_pending_test.go @@ -0,0 +1,58 @@ +package durable_test + +import ( + "context" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestIdleTick_KeepsAPendingParentFiresRead proves an idle Tick, the first call after +// Start or Recover, keeps the clock read a pending parent Fire took arming its timer. The +// Fire is the "go" event the goer actor sends as it spawns, which moves the parent to a +// state with a 10s timer; the next recorded step journals it. A Recover after that step +// replays the arming at its read, so the timer is due 10s after it. +func TestIdleTick_KeepsAPendingParentFiresRead(t *testing.T) { + ctx := context.Background() + for _, from := range []string{"Start", "Recover"} { + t.Run(from, func(t *testing.T) { + m := armedMachine() + clk := state.NewFakeClock(epoch) + store, id := durable.NewMemStore(), durable.InstanceID("pending") + h, err := durable.NewRunner(m, store, armedOptions(clk, from == "Start")...).Start(ctx, id, actorCtx{}, state.WithInitialState("going")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if from == "Recover" { + clk.Advance(time.Hour) + if h, err = durable.Recover(ctx, m, store, id, armedOptions(clk, true)...); err != nil { + t.Fatalf("Recover: %v", err) + } + } + if got := h.Instance().Current(); got != "armed" { + t.Fatalf("state %q, want armed by the goer's go", got) + } + fired, err := h.Tick(ctx) + if err != nil || len(fired) != 0 { + t.Fatalf("idle Tick = %d fired, %v, want none", len(fired), err) + } + 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 go's read", got) + } + }) + } +} diff --git a/durable/runner.go b/durable/runner.go index f70da28..f125c41 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -38,8 +38,8 @@ import ( // // The first nondeterministic source recorded as Record.Entries is the clock: a // Runner owns each instance's delayed-transition scheduler and wraps the clock -// (WithRunnerClock) so every reading the scheduler consumes — arming a timer's -// deadline or testing dueness — is journaled and returned verbatim on recovery, +// (WithRunnerClock) so the readings a recorded step's scheduler consumes — arming a +// timer's deadline or testing dueness — are 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 on the live path @@ -81,7 +81,7 @@ func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st // Handle is a live durable instance: the recovered or freshly started kernel // Instance bound to its Runner and InstanceID, so subsequent Fires continue to // record. It owns the instance's delayed-transition scheduler and the recording -// clock that journals every reading the scheduler consumes, so timer-driven +// clock that journals the readings each recorded step consumes, so timer-driven // transitions are durable and replay wall-clock-independent. Obtain a Handle from // Runner.Start or Recover. // @@ -562,6 +562,10 @@ 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. // +// Start arms the initial state's `after` timers and carries them in the baseline, so a +// Tick fires them and recovery re-arms them. It arms them even when the initial entry +// failed, as it already starts that state's services and actors. +// // 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 @@ -587,8 +591,8 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt return nil, fmt.Errorf("durable: probing instance %q: %w", id, err) } - // Install the recording clock so every reading the delayed-transition - // scheduler consumes is journaled for replay. The clock seam is wired at Cast + // Install the recording clock so the readings the delayed-transition scheduler + // takes during a step are journaled for replay. The clock seam is wired at Cast // (WithClock); the scheduler reads it when arming and ticking timers. buf := make([]state.JournalEntry, 0) recClock := newRecordingClock(r.cfg.clock, &buf) @@ -600,6 +604,20 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt castOpts := append([]state.CastOption[S]{state.WithClock[S](recClock), state.WithUnboundedHistory[S]()}, opts...) inst := r.machine.Cast(input, castOpts...) + // Arm the timers of the state the instance starts in, and carry their deadlines in + // the baseline, which is what a recovery re-arms them from. The arming clock read + // belongs to no step, so it doesn't reach the first Record. + initial := inst.InitialEffects() + sched := state.NewScheduler(inst) + timers := map[string]pendingTimer{} + if hasTimerEffect(initial) { + sched.Absorb(ctx, initial) + reads := recClock.drain() + if n := len(reads); n > 0 { + mirrorArmed(timers, initial, time.Unix(0, reads[n-1].ClockUnixNano).UTC()) + } + } + // Encode a baseline checkpoint at baselineStep (below the first fired step), so the // instance is reconstructable from the Store before any event is fired. The baseline // is the cast snapshot; the tail then accumulates fired steps on top of it. Encoding @@ -608,9 +626,9 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt if err != nil { return nil, fmt.Errorf("durable: marshaling start snapshot for %q: %w", id, err) } - // Wrap the baseline snapshot in a checkpoint envelope (no timers armed yet) so + // Wrap the baseline snapshot in a checkpoint envelope, with the timers Start armed, so // every checkpoint a recover loads carries the same durable envelope shape. - baseEnv, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap, Format: journalFormat}, nil) + baseEnv, err := marshalCheckpoint(checkpointEnvelope{Snapshot: snap, Format: journalFormat}, timers) if err != nil { return nil, fmt.Errorf("durable: marshaling start checkpoint envelope for %q: %w", id, err) } @@ -619,7 +637,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // re-derive these effects after the baseline, so they're at-least-once. An entry that // failed applies none, as a failed Fire dispatches none. if inst.InitialErr() == nil { - if err := r.applyStartEffects(ctx, id, dispatchableEffects(baselineStep, inst.InitialEffects())); err != nil { + if err := r.applyStartEffects(ctx, id, dispatchableEffects(baselineStep, initial)); err != nil { return nil, err } } @@ -652,9 +670,9 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt id: id, inst: inst, nextStep: 0, - sched: state.NewScheduler(inst), + sched: sched, recClock: recClock, - timers: map[string]pendingTimer{}, + timers: timers, svc: svc, svcBuf: &svcBuf, actors: actors, @@ -1122,9 +1140,10 @@ func (h *Handle[S, E, C]) finishStep(ctx context.Context, rec *Record, des []dis // due order, re-firing the delayed events through the durable instance and // recording the clock readings the tick consumed. A host calls it from its own // timer loop (with a real clock) or a test calls it after advancing a fake clock. -// It records one tick barrier — carrying the consumed clock readings and the -// count of timers fired — so recovery re-derives the same timers at their -// recorded instants. Each fired transition's effects go to the service runner and the +// When a timer fired it records one tick barrier — carrying the consumed clock readings +// and the count of timers fired — so recovery re-derives the same timers at their +// recorded instants. A tick that fires nothing records nothing and doesn't touch the +// Store. Each fired transition's effects go to the service runner and the // actor system too, as a Fire's do: a timer that leaves a state stops its services and // its actors, and one that enters a state starts and spawns them. The tick journals the // parent Fires an actor it spawned drove, and a context's ending that refuses one fails @@ -1141,9 +1160,10 @@ func (h *Handle[S, E, C]) finishStep(ctx context.Context, rec *Record, des []dis // 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. As -// Fire does, it dispatches the fired timers' domain effects once the tick is recorded; a -// failed dispatch fails the Handle with ErrHandleFailed, and Recover retries the effect. +// reason, such as a failing guard, is recorded, and replay meets the same refusal; Tick +// reports it only in that timer's FireResult.Err, not in its own error. As Fire does, it +// dispatches the fired timers' domain effects once the tick is recorded; a failed +// dispatch fails the Handle with ErrHandleFailed, and Recover retries the effect. func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], error) { if err := h.acquire(ctx); err != nil { return nil, err @@ -1178,15 +1198,29 @@ func (h *Handle[S, E, C]) tickStep(ctx context.Context) ([]state.FireResult[S], if err := h.refuse(ctx); err != nil { return nil, nil, nil, err } + mark := -1 + if h.recClock != nil { + mark = h.recClock.markBuf() + } results := h.sched.Tick(ctx) // A context that ended partway can make the kernel refuse a due timer's Fire after // the scheduler consumed it. Journaling that would commit on recovery what live never // applied, so record nothing: Recover re-arms the timers. // A tick that fired no timer consumed nothing, so an ended ctx can't have cost it - // anything: it records as usual. + // anything: it returns below as an idle tick. if err := consumedCanceled(ctx, len(results) > 0, append(resultErrs(results), parentFireErrs(h.actorFires.take())...)...); err != nil { return results, nil, nil, h.fail(fmt.Errorf("durable: ticking %q: %w", h.id, err)) } + // A tick that fired nothing changes nothing, so it records nothing. Its own clock + // reads go too: recorded, they'd be readings no replayed step consumes. Reads taken + // before it stay: they belong to a parent Fire that an actor spawned by Start or + // Recover drove, which the next step records. + if len(results) == 0 { + if mark >= 0 { + h.recClock.dropFrom(mark) + } + return results, nil, nil, nil + } // 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 @@ -1198,12 +1232,10 @@ func (h *Handle[S, E, C]) tickStep(ctx context.Context) ([]state.FireResult[S], } mirrorScheduled(h.timers, h.sched, results[i].Effects) } - if len(results) > 0 { - // Drop from the table the timers the tick fired, the ones the scheduler no longer - // holds: one that came due between the tick's reads, and a chained one it armed - // and fired, so a checkpoint after the tick doesn't persist a fired timer. - dropUnscheduled(h.timers, h.sched) - } + // 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) // Hand each fired transition's effects to the service runner, in fire order, and only // then to the actor system, in fire order, as a Fire that produced every transition's // effects does: a timer that leaves a state stops its services and actors, and one @@ -1244,11 +1276,6 @@ 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...)} - // A tick that read no clock and fired nothing records nothing: there is no - // nondeterminism to journal and no step was produced. - if len(rec.Entries) == 0 && rec.TickSteps == 0 { - return results, nil, nil, nil - } des, err := h.recordStep(ctx, rec, effects) if err != nil { return results, nil, nil, err @@ -1582,7 +1609,9 @@ func (h *Handle[S, E, C]) respawn(ctx context.Context, effects []state.Effect, u // effect not yet marked dispatched, so it returns ErrEffectDispatch and no Handle while // the effect handler keeps failing. With an effect handler wired, it refuses a Store // that isn't a DispatchStore with ErrNoDispatchStore before it loads anything, whether -// or not an effect is waiting. +// or not an effect is waiting. It re-arms the checkpoint's timers before replaying the +// tail, and fails when a tick of journal format 3 or later fires a different number of +// timers on replay than it recorded. 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) @@ -1650,10 +1679,10 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // from the final configuration's StartEffects. 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 mirrors the scheduler's pending timers, with their recorded deadlines: the + // checkpoint's, re-armed before the tail, then as the tail arms, cancels and fires + // them. It seeds the Handle's table 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 @@ -1664,6 +1693,24 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S mirror.settle(sv) } + // Re-arm the timers pending at the checkpoint before the tail replays, because the + // tail can fire them. Their deadlines are absolute, so any fixed instant works as the + // arming clock read, and holding the replay clock on one keeps this read from + // consuming a recorded reading. A tail step that re-arms one replaces it. + armedAt := time.Unix(0, 0).UTC() + reEffects, reSeeded, reErr := reArmEffects(r.cfg.eventCodec, persistedTimers, armedAt) + if reErr != nil { + return nil, fmt.Errorf("durable: re-arming pending timers for %q: %w", id, reErr) + } + if len(reEffects) > 0 { + repClock.hold(armedAt) + sched.Absorb(ctx, reEffects) + repClock.release() + } + for id, pt := range reSeeded { + armed[id] = pt + } + // 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. @@ -1672,6 +1719,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // and hadn't ended, recorded alongside ended. Nil means none was recorded. unstarted := env.UnstartedActors + reads := 0 // clock readings through the current Record 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. @@ -1685,10 +1733,15 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S if err := checkFormat(env.Format, rec); err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } + reads += clockReadCount(rec) stepEffects, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, mirror, armsActorFires(rec)) if err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } + // Leave none of the Record's readings for the next one. A Record this version + // wrote replays exactly its own; an older one can leave some, such as a tick + // whose recorded timer replay keeps canceled, or an idle tick's. + repClock.skipTo(reads) if rec.EndedActors != nil { ended = rec.EndedActors } @@ -1716,38 +1769,16 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } + // Skip any reading no replayed step consumed, so live continuation reads the real + // clock: an older journal can leave one, such as a settle's read it put in the next + // Record. + repClock.skipTo(reads) + // Drain any clock readings the replay re-recorded after the cursor exhausted // (none in the common case where replay consumes exactly the recorded // readings): they belong to no new step and must not leak into the next Fire. buf = buf[:0] - // 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 @@ -2147,7 +2178,11 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { // the same deadlines come due and the same timers fire at their recorded instants. // Each fired transition starts or stops its services, as the live Tick did, for a // Record of tickDriversFormat or later, and its recorded parent Fires re-fire after -// the tick. +// the tick. For a Record of timersFirstFormat or later, a tick that fires a +// different number of timers than the Record's TickSteps fails the replay. +// - A tick Record with TickSteps zero, which only an older version wrote, fires +// nothing. After every Record the caller skips any reading it left +// (replayClock.skipTo). // - 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. @@ -2197,8 +2232,23 @@ func replayRecord[S comparable, E comparable, C any]( replayArm(ctx, sched, nil, effects, mirror) stepEffects = append(stepEffects, effects...) } + case rec.Tick && rec.TickSteps == 0: + // Only a version from before idle ticks stopped recording wrote a tick that fired + // nothing. Don't tick: a timer re-armed from a checkpoint could be due by its + // readings, and the Record says nothing fired. The caller skips the readings. case rec.Tick: ticked := sched.Tick(ctx) + // A replayed tick of timersFirstFormat or later fires exactly the timers the live + // one did, so a different count means the journal isn't one this replay can + // reproduce: fail rather than replay the following steps in another state. An + // older Record can legitimately differ (see timersFirstFormat), so it isn't + // checked. A ctx that ended can stop the tick short, so its error comes first. + if rec.Format >= timersFirstFormat && len(ticked) != rec.TickSteps { + if err := ctx.Err(); err != nil { + return stepEffects, err + } + return stepEffects, fmt.Errorf("replaying the tick at step %d: it fired %d timer(s), but the journal records %d", rec.Step, len(ticked), rec.TickSteps) + } mirrorTick(mirror, sched, ticked) for i := range ticked { if rec.Format >= tickDriversFormat { @@ -2271,17 +2321,21 @@ func sendsReplayedEffects(rec *Record) bool { } // journalFormat is the format this version writes in every Record and checkpoint. It is -// dispatchedStepsFormat. actorArmsFormat is the first format that arms the timers and +// timersFirstFormat. actorArmsFormat is the first format that arms the timers and // services an actor-driven parent Fire's state declares. dispatchedStepsFormat is the // first that dispatches a tick's and a service settle's domain effects, so Recover sends // them. tickDriversFormat is the first whose Tick hands its timer transitions' effects // to the service runner and the actor system, so replay starts and stops their services -// as it did. +// as it did. timersFirstFormat is the first whose Recover re-arms a checkpoint's timers +// before the tail, so its replayed ticks fire exactly the timers they record. An older +// version's recovery re-armed them after the tail, so a journal it continued can record +// a tick replay can't reproduce: a timer the tail had fired or canceled, fired again. const ( actorArmsFormat = 1 dispatchedStepsFormat = 2 tickDriversFormat = 2 - journalFormat = dispatchedStepsFormat + timersFirstFormat = 3 + journalFormat = timersFirstFormat ) // replayArm arms the timers and services a replayed Fire's effects declare, as the live diff --git a/durable/runner_options.go b/durable/runner_options.go index 52b2687..3ab17b8 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -81,8 +81,8 @@ func WithEventCodec[S comparable, E comparable, C any](codec EventCodec[E]) Opti // WithRunnerClock injects the real time seam the Runner records on the live path // and replays on recovery. A durable instance reads time only through its host // scheduler (which arms and ticks delayed `after` transitions); the Runner wraps -// this clock in a recording clock so every reading is journaled, and substitutes -// a replay clock on recovery so timers fire at their recorded instants +// this clock in a recording clock so each recorded step's readings are journaled, and +// substitutes a replay clock on recovery so timers fire at their recorded instants // independent of the wall clock at recovery time. It defaults to // state.SystemClock(); supply a deterministic fake (state.NewFakeClock) in a test. func WithRunnerClock[S comparable, E comparable, C any](c state.Clock) Option[S, E, C] { diff --git a/durable/service_test.go b/durable/service_test.go index 60f0187..eba2dc1 100644 --- a/durable/service_test.go +++ b/durable/service_test.go @@ -487,10 +487,582 @@ func fetchThenWaitMachine(fn state.ServiceFn[svcCtx]) *state.Machine[string, str Initial("idle"). Transition("idle").On("start").GoTo("loading"). Transition("loading").On("ok").GoTo("waiting").Do("notify"). + Transition("waiting").On("poke").GoTo("waiting"). Transition("waiting").After(5 * time.Second).On("elapsed").GoTo("done"). Quench() } +// TestService_TimerArmedBySettle_ReplaysOnRecover proves a timer armed by a service +// result survives recovery, with an idle tick between the settle and the tick that +// fires it. +func TestService_TimerArmedBySettle_ReplaysOnRecover(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchThenWaitMachine(fn) + store := durable.NewMemStore() + id := durable.InstanceID("fetch-1") + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + 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) + } + clk.Advance(time.Second) // the settle's read differs from the earlier ones + mustRunService(t, h, state.InvokeID("fetchThenWait", "loading", 0)) + for _, d := range []time.Duration{2 * time.Second, 4 * time.Second} { // idle, then due + clk.Advance(d) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + } + if got := h.Instance().Current(); got != "done" { + t.Fatalf("live state %q, want done", got) + } + + // A clock still at the start proves the timer replays at its recorded instant. + recovered, err := durable.Recover(ctx, m, store, id, append(opts, durable.WithRunnerClock[string, string, svcCtx](state.NewFakeClock(epoch)))...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if live, got := handleSnapshot(t, h), handleSnapshot(t, recovered); got != live { + t.Fatalf("recovered instance differs from live:\n live: %s\n got: %s", live, got) + } + if got := atomic.LoadInt64(&calls); got != 1 { + t.Fatalf("service ran %d times, want 1: recovery replays the recorded result", got) + } +} + +// TestStateAt_TimerArmedBySettle_Fires proves a historical read arms a timer from a +// recorded service result, so it fires in the replayed window as it did live. +func TestStateAt_TimerArmedBySettle_Fires(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchThenWaitMachine(fn) + store := durable.NewMemStore(durable.WithHistory()) + id := durable.InstanceID("fetch-1") + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + 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) + } + mustRunService(t, h, state.InvokeID("fetchThenWait", "loading", 0)) + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + view, err := durable.StateAt(ctx, m, store, id, 2, opts...) // the tick's barrier + if err != nil { + t.Fatalf("StateAt: %v", err) + } + if got := view.Instance().Current(); got != "done" { + t.Fatalf("StateAt state %q, want done", got) + } +} + +// TestRecover_TimerArmedBySettle_SurvivesALaterCheckpoint proves recovery keeps a timer +// armed by a replayed service result in the table the next checkpoint persists, so a +// second recovery from that checkpoint still fires it. +func TestRecover_TimerArmedBySettle_SurvivesALaterCheckpoint(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchThenWaitMachine(fn) + store := durable.NewMemStore() + id := durable.InstanceID("fetch-1") + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + durable.WithCheckpointEvery[string, string, svcCtx](3), + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, 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) + } + mustRunService(t, h, state.InvokeID("fetchThenWait", "loading", 0)) + + first, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("first Recover: %v", err) + } + for range 3 { // cross a checkpoint boundary after the settle has replayed + if _, err = first.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + } + + second, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + clk.Advance(6 * time.Second) + if _, err = second.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := second.Instance().Current(); got != "done" { + t.Fatalf("state %q after the second recovery, want done", got) + } +} + +// fetchChainMachine arms a timer on a service result, then chains a second one. +func fetchChainMachine(fn state.ServiceFn[svcCtx]) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("fetchChain"). + Service("fetch", fn). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("ok")). + State("waiting"). + State("next"). + State("done"). + Initial("idle"). + Transition("idle").On("start").GoTo("loading"). + Transition("loading").On("ok").GoTo("waiting"). + Transition("waiting").On("poke").GoTo("waiting"). + Transition("waiting").After(5 * time.Second).On("first").GoTo("next"). + Transition("next").After(5 * time.Second).On("second").GoTo("done"). + Quench() +} + +// olderSettle splits a settle Record as an older journal wrote it: the Record without its +// clock read, and that read, which the older code left for the next Record to carry. +func olderSettle(settle durable.Record) (durable.Record, state.JournalEntry) { + var read state.JournalEntry + var kept []state.JournalEntry + for _, e := range settle.Entries { + if e.Kind == state.JournalClockRead { + read = e + continue + } + kept = append(kept, e) + } + settle.Entries = kept + return settle, read +} + +// clockReadAt is a recorded clock read d after epoch. +func clockReadAt(d time.Duration) state.JournalEntry { + return state.JournalEntry{Kind: state.JournalClockRead, ClockUnixNano: epoch.Add(d).UnixNano()} +} + +// startFetchChain starts a fetchChainMachine and settles its service. +func startFetchChain( + t *testing.T, + m *state.Machine[string, string, svcCtx], + store durable.Store, + id durable.InstanceID, + opts []durable.Option[string, string, svcCtx], +) *durable.Handle[string, string, svcCtx] { + t.Helper() + ctx := context.Background() + 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) + } + mustRunService(t, h, state.InvokeID("fetchChain", "loading", 0)) + return h +} + +// appendAll appends recs to store, failing the test on any error. +func appendAll(t *testing.T, store durable.Store, id durable.InstanceID, recs ...durable.Record) { + t.Helper() + for _, rec := range recs { + if _, err := store.Append(context.Background(), id, rec); err != nil { + t.Fatalf("Append: %v", err) + } + } +} + +// TestRecover_OlderJournal_SettleReadInIdleTick_KeepsReplayClockAligned proves replay stays +// on the recorded readings when an older journal carries a settle's clock read in the idle +// tick Record after it. Replay consumes that read at the settle, so skipping the idle tick +// must not consume it again, or the last tick reads the live clock and fires a timer no +// Record holds. +func TestRecover_OlderJournal_SettleReadInIdleTick_KeepsReplayClockAligned(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchChainMachine(fn) + clk := state.NewFakeClock(epoch) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + } + store := durable.NewMemStore() + h := startFetchChain(t, m, store, id, opts) + clk.Advance(6 * time.Second) + if _, err := h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + + settle, settleRead := olderSettle(tail[1]) + firstIdle := durable.Record{Step: 2, Tick: true, Entries: []state.JournalEntry{settleRead, clockReadAt(time.Second)}} + secondIdle := durable.Record{Step: 3, Tick: true, Entries: []state.JournalEntry{clockReadAt(2 * time.Second)}} + tick := tail[2] + tick.Step = 4 + older := durable.NewMemStore() + if _, err = durable.NewRunner(m, older, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + appendAll(t, older, id, tail[0], settle, firstIdle, secondIdle, tick) + + clk.Advance(94 * time.Second) // the wall clock is far past every timer at recovery + older = asFormatOne(t, older, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "next" { + t.Fatalf("recovered state %q, want next", got) + } +} + +// TestRecover_OlderJournal_TickPassesAnEarlierSettleRead proves a tail tick fires its +// timer when an older journal left a read at the front of its Record that no replayed +// settle consumed, because a checkpoint compacted the settle away. +func TestRecover_OlderJournal_TickPassesAnEarlierSettleRead(t *testing.T) { + t.Skip("an older journal's settle clock read in the next Record can arm a replayed timer at the wrong instant; #262") + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchChainMachine(fn) + clk := state.NewFakeClock(epoch) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + } + // One run takes the checkpoint at the settle; a second, with none, gives the tick Record. + checkpointed := durable.NewMemStore() + startFetchChain(t, m, checkpointed, id, append(opts[:2:2], durable.WithCheckpointEvery[string, string, svcCtx](2))) + snapshot, compacted, err := checkpointed.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(compacted) != 0 { + t.Fatalf("tail holds %d records, want the settle checkpointed", len(compacted)) + } + store := durable.NewMemStore() + h := startFetchChain(t, m, store, id, opts) + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + + tick := tail[2] + tick.Entries = append([]state.JournalEntry{clockReadAt(0)}, tick.Entries...) + older := durable.NewMemStore() + if _, err = durable.NewRunner(m, older, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + appendAll(t, older, id, durable.Record{Step: 0}, durable.Record{Step: 1}) + if err = older.Checkpoint(ctx, id, snapshot, 1); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + appendAll(t, older, id, tick) + + older = asFormatOne(t, older, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "next" { + t.Fatalf("recovered state %q, want next", got) + } + view, err := durable.StateAt(ctx, m, older, id, tick.Step, opts...) + if err != nil { + t.Fatalf("StateAt: %v", err) + } + if got := view.Instance().Current(); got != "next" { + t.Fatalf("StateAt state %q, want next", got) + } +} + +// TestRecover_OlderJournal_SettleSkipsAnUnusedRead proves a replayed settle arms from its +// own reading, not a stale one an older journal left in an earlier Record that no Absorb +// consumed. +func TestRecover_OlderJournal_SettleSkipsAnUnusedRead(t *testing.T) { + t.Skip("an older journal's settle clock read in the next Record can arm a replayed timer at the wrong instant; #262") + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchChainMachine(fn) + clk := state.NewFakeClock(epoch) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + } + store := durable.NewMemStore() + startFetchChain(t, m, store, id, opts) + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + + fire := tail[0] + fire.Entries = append([]state.JournalEntry{clockReadAt(0)}, fire.Entries...) // unused + settle, _ := olderSettle(tail[1]) + older := durable.NewMemStore() + if _, err = durable.NewRunner(m, older, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + appendAll(t, older, id, fire, settle, + durable.Record{Step: 2, Tick: true, Entries: []state.JournalEntry{clockReadAt(time.Second)}}) + + older = asFormatOne(t, older, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + clk.Advance(5*time.Second + 500*time.Millisecond) // the timer is due at 6s, from the settle's read + for range 2 { // a misaligned replay leaves a reading for the first + fired, err := recovered.Tick(ctx) + if err != nil { + t.Fatalf("Tick: %v", err) + } + if len(fired) != 0 { + t.Fatalf("Tick fired %d timers before the deadline, want 0", len(fired)) + } + } +} + +// TestRecover_OlderJournal_SettleReadLostToARestart_LeavesTheNextStepsReads proves a +// read-less settle doesn't consume the next Record's reading when a restart lost its own. +// That reading stands in for the lost one, and the tick after it still fires what it +// recorded. +func TestRecover_OlderJournal_SettleReadLostToARestart_LeavesTheNextStepsReads(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchChainMachine(fn) + clk := state.NewFakeClock(epoch) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + } + store := durable.NewMemStore() + h := startFetchChain(t, m, store, id, opts) + clk.Advance(6 * time.Second) + if _, err := h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + + settle, _ := olderSettle(tail[1]) // the restart lost its read + older := durable.NewMemStore() + if _, err = durable.NewRunner(m, older, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + tick := tail[2] + tick.Step = 3 + appendAll(t, older, id, tail[0], settle, + durable.Record{Step: 2, Tick: true, Entries: []state.JournalEntry{clockReadAt(time.Second)}}, tick) + + older = asFormatOne(t, older, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "next" { + t.Fatalf("recovered state %q, want next", got) + } + view, err := durable.StateAt(ctx, m, older, id, tick.Step, opts...) + if err != nil { + t.Fatalf("StateAt: %v", err) + } + if got := view.Instance().Current(); got != "next" { + t.Fatalf("StateAt state %q, want next", got) + } +} + +// TestRecover_OlderJournal_TailEndingOnASettle_CarriesItsRead proves recovery keeps the +// read it took for a settle that ended an older journal: the next step's Record carries +// it, so a later recovery arms that timer at the same instant. +func TestRecover_OlderJournal_TailEndingOnASettle_CarriesItsRead(t *testing.T) { + t.Skip("an older journal's settle clock read in the next Record can arm a replayed timer at the wrong instant; #262") + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchChainMachine(fn) + clk := state.NewFakeClock(epoch) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + } + store := durable.NewMemStore() + startFetchChain(t, m, store, id, opts) + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + settle, _ := olderSettle(tail[1]) + older := durable.NewMemStore() + if _, err = durable.NewRunner(m, older, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + appendAll(t, older, id, tail[0], settle) + + clk.Advance(3 * time.Second) + older = asFormatOne(t, older, id) + first, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("first Recover: %v", err) + } + clk.Advance(6 * time.Second) // due at 8s, from the recovery's read + if _, err = first.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := first.Instance().Current(); got != "next" { + t.Fatalf("live state %q, want next", got) + } + second, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if got := second.Instance().Current(); got != "next" { + t.Fatalf("recovered state %q, want next", got) + } +} + +// TestRecover_OlderJournal_LeftoverReadStaysOutOfTheLiveClock proves a reading no step +// consumed at the end of a tail doesn't reach the live clock, so a timer armed after +// recovery measures from the real time. +func TestRecover_OlderJournal_LeftoverReadStaysOutOfTheLiveClock(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchChainMachine(fn) + clk := state.NewFakeClock(epoch) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + } + store := durable.NewMemStore() + 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: %v", err) + } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + fire := tail[0] + fire.Entries = append([]state.JournalEntry{clockReadAt(0)}, fire.Entries...) // no Absorb used it + older := durable.NewMemStore() + if _, err = durable.NewRunner(m, older, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + appendAll(t, older, id, fire) + + clk.Advance(94 * time.Second) + older = asFormatOne(t, older, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + mustRunService(t, recovered, state.InvokeID("fetchChain", "loading", 0)) // arms 5s, due at 99s + clk.Advance(time.Second) + fired, err := recovered.Tick(ctx) + if err != nil { + t.Fatalf("Tick: %v", err) + } + if len(fired) != 0 { + t.Fatalf("Tick fired %d timers before the deadline, want 0", len(fired)) + } +} + +// TestRecover_OlderJournal_SettleTimerReachesTheNextCheckpoint proves a timer armed by an +// older settle Record, which holds no clock read, still reaches the Handle's table, so the +// next checkpoint persists it and a second recovery fires it. +func TestRecover_OlderJournal_SettleTimerReachesTheNextCheckpoint(t *testing.T) { + ctx := context.Background() + var calls int64 + fn := counterService(&calls) + m := fetchChainMachine(fn) + clk := state.NewFakeClock(epoch) + id := durable.InstanceID("fetch-1") + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + durable.WithCheckpointEvery[string, string, svcCtx](6), + } + store := durable.NewMemStore() + startFetchChain(t, m, store, id, opts) + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + + settle, settleRead := olderSettle(tail[1]) + older := durable.NewMemStore() + if _, err = durable.NewRunner(m, older, opts...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + appendAll(t, older, id, tail[0], settle, + durable.Record{Step: 2, Tick: true, Entries: []state.JournalEntry{settleRead, clockReadAt(time.Second)}}) + + older = asFormatOne(t, older, id) + first, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("first Recover: %v", err) + } + for range 3 { // cross a checkpoint boundary after the settle has replayed + if _, err = first.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + } + second, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + clk.Advance(6 * time.Second) + if _, err = second.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + if got := second.Instance().Current(); got != "next" { + t.Fatalf("state %q after the second recovery, want next", got) + } +} + // 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. diff --git a/durable/store.go b/durable/store.go index fddc867..033cd3d 100644 --- a/durable/store.go +++ b/durable/store.go @@ -84,8 +84,10 @@ type Record struct { Tick bool // TickSteps is the number of timer transitions the tick at this barrier fired - // (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. + // (zero only in a journal from before idle ticks stopped recording). It lets replay + // advance its step accounting across a re-derived tick without a recorded Event per + // timer. From journal format 3, replay fails when the re-derived tick fires a + // different number. TickSteps int // EndedActors, when set, holds the child-machine actors the instance's state @@ -122,7 +124,9 @@ type Record struct { // format 2 the live run dispatched a tick's and a service settle's domain effects, so // Recover sends them, and a Tick handed its timer transitions' effects to the service // runner and the actor system, so replay starts and stops their services as it did; - // an older Record replays as that version ran it. A Store keeps it as it keeps Step. + // an older Record replays as that version ran it. From format 3 Recover re-arms a + // checkpoint's timers before the tail, and replay fails on a tick that fires a + // different number of timers than TickSteps. A Store keeps it as it keeps Step. Format int `json:",omitempty"` } diff --git a/durable/tick_steps_check_test.go b/durable/tick_steps_check_test.go new file mode 100644 index 0000000..f2129e7 --- /dev/null +++ b/durable/tick_steps_check_test.go @@ -0,0 +1,147 @@ +package durable_test + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// leavableTimerMachine has pendingTimerMachine's states and 10s timer, without its +// action, plus a "leave" from waiting back to idle, which cancels the timer. +func leavableTimerMachine() *state.Machine[string, string, *timerCtx] { + return state.ForgeFor[*timerCtx]("leavableTimer"). + State("idle"). + State("waiting"). + State("done").Final(). + Initial("idle"). + Transition("idle").On("arm").GoTo("waiting"). + Transition("waiting").On("poke").GoTo("waiting"). + Transition("waiting").On("leave").GoTo("idle"). + Transition("waiting").After(10 * time.Second).On("elapsed").GoTo("done"). + Quench() +} + +// checkpointedTimer starts m in idle, arms its timer and pokes twice, so that with the +// caller's WithCheckpointEvery(3) a checkpoint carries the pending timer. It then fires +// each event in then. +func checkpointedTimer(t *testing.T, m *state.Machine[string, string, *timerCtx], opts []durable.Option[string, string, *timerCtx], then ...string) (*durable.MemStore, durable.InstanceID) { + t.Helper() + ctx := context.Background() + store, id := durable.NewMemStore(), durable.InstanceID("timer-1") + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for _, ev := range append([]string{"arm", "poke", "poke"}, then...) { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire(%s): %v", ev, err) + } + } + return store, id +} + +// TestRecover_ATickThatFiresFewerTimersThanRecorded_Fails proves Recover refuses a +// Record this version wrote whose tick replay can't reproduce: it records a +// fired timer, but nothing is due at its readings. +func TestRecover_ATickThatFiresFewerTimersThanRecorded_Fails(t *testing.T) { + ctx := context.Background() + m := leavableTimerMachine() + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](state.NewFakeClock(epoch)), + durable.WithCheckpointEvery[string, string, *timerCtx](3), + } + store, id := checkpointedTimer(t, m, opts, "leave") + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + last := tail[len(tail)-1] + read := clockReadAt(11 * time.Second) + bad := durable.Record{Step: last.Step + 1, Tick: true, TickSteps: 1, Format: last.Format, Entries: []state.JournalEntry{read, read, read}} + if _, err = store.Append(ctx, id, bad); err != nil { + t.Fatalf("Append: %v", err) + } + want := "fired 0 timer(s), but the journal records 1" + if _, err = durable.Recover(ctx, m, store, id, opts...); err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("Recover: %v, want the tick's fired count refused", err) + } +} + +// TestRecover_AnOlderRecoverysRevivedTimer_Recovers proves an older journal whose tick +// fired a timer the tail had canceled still recovers, to the state the older version +// reached. That version re-armed a checkpoint's timers after the tail, so its recovery +// revived the canceled timer, and a later tick fired it into a refusal, recorded as one +// fired timer. Replay keeps it canceled and fires nothing, which changes no state. +func TestRecover_AnOlderRecoverysRevivedTimer_Recovers(t *testing.T) { + ctx := context.Background() + m := leavableTimerMachine() + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](state.NewFakeClock(epoch)), + durable.WithCheckpointEvery[string, string, *timerCtx](3), + } + store, id := checkpointedTimer(t, m, opts, "leave") + older := asFormat(t, store, id, 2) + _, tail, err := older.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + read := clockReadAt(11 * time.Second) + revived := durable.Record{Step: tail[len(tail)-1].Step + 1, Tick: true, TickSteps: 1, Format: 2, Entries: []state.JournalEntry{read, read, read}} + if _, err = older.Append(ctx, id, revived); err != nil { + t.Fatalf("Append: %v", err) + } + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "idle" { + t.Fatalf("recovered in %q, want idle: the revived timer's Fire was refused", got) + } +} + +// TestRecover_AnOlderRecoverysRevivedTimer_RecoversAfterMoreSteps proves the revived +// tick's readings that replay doesn't use stay with its Record: once the recovered Handle +// arms and fires its timer, a second Recover replays those steps at their own readings. +func TestRecover_AnOlderRecoverysRevivedTimer_RecoversAfterMoreSteps(t *testing.T) { + ctx := context.Background() + m := leavableTimerMachine() + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](3), + } + store, id := checkpointedTimer(t, m, opts, "leave") + older := asFormat(t, store, id, 2) + _, tail, err := older.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + read := clockReadAt(11 * time.Second) + revived := durable.Record{Step: tail[len(tail)-1].Step + 1, Tick: true, TickSteps: 1, Format: 2, Entries: []state.JournalEntry{read, read, read}} + if _, err = older.Append(ctx, id, revived); err != nil { + t.Fatalf("Append: %v", err) + } + clk.Advance(20 * time.Second) + h, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err = h.Fire(ctx, "arm"); err != nil { // due at 30s + t.Fatalf("Fire(arm): %v", err) + } + clk.Advance(11 * time.Second) + if fired, tickErr := h.Tick(ctx); tickErr != nil || len(fired) != 1 { + t.Fatalf("Tick = %d fired, %v, want 1", len(fired), tickErr) + } + again, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + if got := again.Instance().Current(); got != "done" { + t.Fatalf("recovered in %q, want done", got) + } +} diff --git a/durable/timer_checkpoint_test.go b/durable/timer_checkpoint_test.go index 9d3ac77..bf34cc8 100644 --- a/durable/timer_checkpoint_test.go +++ b/durable/timer_checkpoint_test.go @@ -492,3 +492,546 @@ func TestTick_DropsEachTimerItFired(t *testing.T) { } } } + +// TestTimerCheckpoint_FiredAfterCheckpoint_ByteIdentical proves a timer persisted by +// a checkpoint and fired later in the tail, after an idle tick, replays at its +// recorded instant instead of being missed. +func TestTimerCheckpoint_FiredAfterCheckpoint_ByteIdentical(t *testing.T) { + ctx := context.Background() + m := pendingTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](3), + } + runner := durable.NewRunner(m, store, opts...) + h, err := runner.Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for _, ev := range []string{"arm", "poke", "poke"} { // checkpoint lands with the timer pending + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire(%s): %v", ev, err) + } + } + _, 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 have compacted them", len(tail)) + } + for _, d := range []time.Duration{5 * time.Second, 6 * time.Second} { // idle, then due + clk.Advance(d) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + } + + if got := h.Instance().Current(); got != "done" { + t.Fatalf("live state %q, want done", got) + } + + // A clock still at the start proves the timer replays at its recorded instant. + recovered, err := durable.Recover(ctx, m, store, id, append(opts, durable.WithRunnerClock[string, string, *timerCtx](state.NewFakeClock(epoch)))...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if live, got := handleSnapshot(t, h), handleSnapshot(t, recovered); got != live { + t.Fatalf("recovered instance differs from live:\n live: %s\n got: %s", live, got) + } +} + +// TestStateAt_TimerArmedAtStart_Fires proves a historical read re-arms the timers a +// baseline carries, so a timer armed by Start fires in the replayed window. +func TestStateAt_TimerArmedAtStart_Fires(t *testing.T) { + ctx := context.Background() + m := timerMachine() + store := durable.NewMemStore(durable.WithHistory()) + id := durable.InstanceID("timer-1") + clk := 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("arming")) + if err != nil { + t.Fatalf("Start: %v", err) + } + clk.Advance(6 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + view, err := durable.StateAt(ctx, m, store, id, 0, opts...) + if err != nil { + t.Fatalf("StateAt: %v", err) + } + if got := view.Instance().Current(); got != "done" { + t.Fatalf("StateAt state %q, want done", got) + } +} + +// TestRecover_OlderIdleTickRecord_FiresNothing proves an idle tick Record from an older +// journal replays as nothing fired, even with a due re-armed timer. +func TestRecover_OlderIdleTickRecord_FiresNothing(t *testing.T) { + ctx := context.Background() + m := pendingTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](3), + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for _, ev := range []string{"arm", "poke", "poke"} { // the checkpoint carries the timer + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire(%s): %v", ev, err) + } + } + // An older build recorded this idle tick with a reading past the timer's deadline. + late := epoch.Add(time.Hour).UnixNano() + idle := durable.Record{Step: 3, Tick: true, Entries: []state.JournalEntry{{Kind: state.JournalClockRead, ClockUnixNano: late}}} + if _, err = store.Append(ctx, id, idle); err != nil { + t.Fatalf("Append: %v", err) + } + store = asFormatOne(t, store, id) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := recovered.Instance().Current(); got != "waiting" { + t.Fatalf("recovered in %q, want waiting: the Record says nothing fired", got) + } +} + +// driftingClock moves by step on every read, as a real clock moves during a tick. +type driftingClock struct { + now time.Time + step time.Duration +} + +func (c *driftingClock) Now() time.Time { + t := c.now + c.now = c.now.Add(c.step) + return t +} + +func (c *driftingClock) After(time.Duration) <-chan time.Time { return nil } + +// twoTimerMachine holds two timers on a parent state. Each fires into one of parent's +// children, so firing one cancels neither. +func twoTimerMachine() *state.Machine[string, string, *timerCtx] { + return state.ForgeFor[*timerCtx]("twoTimers"). + State("idle"). + SuperState("parent"). + Initial("p1"). + SubState("p1"). + SubState("p2"). + SubState("p3"). + EndSuperState(). + Initial("idle"). + Transition("idle").On("go").GoTo("parent"). + Transition("parent").On("poke").GoTo("p1"). + Transition("parent").After(10 * time.Second).On("first").GoTo("p2"). + Transition("parent").After(10*time.Second + 10*time.Millisecond).On("second").GoTo("p3"). + Quench() +} + +// tickAcrossTwoDeadlines starts a twoTimerMachine and ticks it so the tick's first read +// finds one timer due and its second read finds the other. +func tickAcrossTwoDeadlines( + t *testing.T, + m *state.Machine[string, string, *timerCtx], + store durable.Store, + id durable.InstanceID, + clk *driftingClock, + opts []durable.Option[string, string, *timerCtx], +) { + t.Helper() + ctx := context.Background() + 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, "go"); err != nil { + t.Fatalf("Fire: %v", err) + } + clk.now, clk.step = epoch.Add(10*time.Second+5*time.Millisecond), 20*time.Millisecond + fired, err := h.Tick(ctx) + if err != nil { + t.Fatalf("Tick: %v", err) + } + if len(fired) != 2 { + t.Fatalf("Tick fired %d timers, want 2", len(fired)) + } + clk.step = 0 +} + +// slowChainMachine has a chained timer armed after a slow action, and a second region +// whose timer fires between the chained timer's start and its real deadline. +func slowChainMachine(clk *driftingClock, other time.Duration) *state.Machine[string, string, *timerCtx] { + return state.ForgeFor[*timerCtx]("slowChain"). + Action("slow", func(state.ActionCtx[*timerCtx]) (state.Effect, error) { + clk.now = clk.now.Add(200 * time.Millisecond) + return nil, nil + }). + State("idle"). + SuperState("live"). + Region("first"). + Initial("a1"). + SubState("a1"). + SubState("a2"). + SubState("a3"). + EndRegion(). + Region("second"). + Initial("b1"). + SubState("b1"). + SubState("b2"). + EndRegion(). + EndSuperState(). + Initial("idle"). + Transition("idle").On("arm").GoTo("live"). + Transition("a1").After(10 * time.Second).On("x").GoTo("a2").Do("slow"). + Transition("a2").After(5 * time.Second).On("c").GoTo("a3"). + Transition("b1").After(other).On("y").GoTo("b2"). + Transition("b1").On("poke").GoTo("b1"). + Quench() +} + +// TestTick_ChainedTimerAfterSlowAction_SurvivesRecovery proves the Handle holds a chained +// timer at the deadline the scheduler armed, after the action ran. An earlier deadline +// would drop it when a later tick passes that instant, and recovery would lose it. +func TestTick_ChainedTimerAfterSlowAction_SurvivesRecovery(t *testing.T) { + ctx := context.Background() + clk := &driftingClock{now: epoch, step: 100 * time.Microsecond} + other := 15*time.Second - 100*time.Microsecond + m := slowChainMachine(clk, other) + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](1), + } + 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: %v", err) + } + for _, at := range []time.Duration{10 * time.Second, other} { + clk.now = epoch.Add(at) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + clk.now = epoch.Add(16 * time.Second) + fired, err := recovered.Tick(ctx) + if err != nil { + t.Fatalf("recovered Tick: %v", err) + } + if len(fired) != 1 { + t.Fatalf("recovered Tick fired %d timers, want the chained timer", len(fired)) + } +} + +// TestRecover_ChainedTimerAfterSlowAction_NotFiredEarly proves a checkpointed chained +// timer keeps its real deadline, so a tail tick doesn't fire it before live did. +func TestRecover_ChainedTimerAfterSlowAction_NotFiredEarly(t *testing.T) { + ctx := context.Background() + clk := &driftingClock{now: epoch, step: 100 * time.Microsecond} + other := 15*time.Second - 100*time.Microsecond + m := slowChainMachine(clk, other) + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](2), + } + 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: %v", err) + } + clk.now = epoch.Add(10 * 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) + } + clk.now = epoch.Add(other) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if live, got := handleSnapshot(t, h), handleSnapshot(t, recovered); got != live { + t.Fatalf("recovered instance differs from live:\n live: %s\n got: %s", live, got) + } +} + +// TestRecover_ReplayedChainedTimer_KeepsItsDeadline proves a replayed tick mirrors a +// chained timer at the deadline live armed, so the next checkpoint persists that deadline. +func TestRecover_ReplayedChainedTimer_KeepsItsDeadline(t *testing.T) { + ctx := context.Background() + clk := &driftingClock{now: epoch, step: 100 * time.Microsecond} + m := slowChainMachine(clk, time.Minute) + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](6), + } + 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: %v", err) + } + clk.now = epoch.Add(10 * time.Second) + if _, err = h.Tick(ctx); err != nil { + t.Fatalf("Tick: %v", err) + } + first, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("first Recover: %v", err) + } + for range 3 { // cross a checkpoint boundary after the tick has replayed + if _, err = first.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + } + second, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + clk.now = epoch.Add(15*time.Second + 100*time.Millisecond) // before 15.2s, the real deadline + fired, err := second.Tick(ctx) + if err != nil { + t.Fatalf("recovered Tick: %v", err) + } + if len(fired) != 0 { + t.Fatalf("recovered Tick fired %d timers before the deadline, want 0", len(fired)) + } +} + +// TestRecover_OlderJournal_TailEndingOnIdleTicks_LeavesNoReadings proves a tail ending on +// idle tick Records leaves none of their readings for the live clock, so the first Tick +// after recovery reads the real time and fires what is due. +func TestRecover_OlderJournal_TailEndingOnIdleTicks_LeavesNoReadings(t *testing.T) { + ctx := context.Background() + m := pendingTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := 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: %v", err) + } + for step := 1; step <= 3; step++ { + read := state.JournalEntry{Kind: state.JournalClockRead, ClockUnixNano: epoch.Add(time.Duration(step) * time.Second).UnixNano()} + idle := durable.Record{Step: step, Tick: true, Entries: []state.JournalEntry{read}} + if _, err = store.Append(ctx, id, idle); err != nil { + t.Fatalf("Append: %v", err) + } + } + + clk.Advance(20 * time.Second) + store = asFormatOne(t, store, id) + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + fired, err := recovered.Tick(ctx) + if err != nil { + t.Fatalf("Tick: %v", err) + } + if len(fired) != 1 { + t.Fatalf("first Tick after recovery fired %d timers, want 1", len(fired)) + } +} + +// TestRecover_OlderJournal_FireArmsFromItsOwnRead proves a replayed Fire arms its timer +// from its own reading, the last in its Record, past a read an older journal left in front. +func TestRecover_OlderJournal_FireArmsFromItsOwnRead(t *testing.T) { + t.Skip("an older journal's settle clock read in the next Record can arm a replayed timer at the wrong instant; #262") + ctx := context.Background() + m := pendingTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := 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) + } + clk.Advance(time.Second) + if _, err = h.Fire(ctx, "arm"); err != nil { + t.Fatalf("Fire: %v", err) + } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + + stale := state.JournalEntry{Kind: state.JournalClockRead, ClockUnixNano: epoch.UnixNano()} + fire := tail[0] + fire.Entries = append([]state.JournalEntry{stale}, fire.Entries...) + older := durable.NewMemStore() + if _, err = durable.NewRunner(m, older, opts...).Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = older.Append(ctx, id, fire); err != nil { + t.Fatalf("Append: %v", err) + } + + older = asFormatOne(t, older, id) + recovered, err := durable.Recover(ctx, m, older, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + clk.Advance(9*time.Second + 500*time.Millisecond) // the timer is due at 11s + for range 2 { // a misaligned replay leaves a reading for the first + fired, err := recovered.Tick(ctx) + if err != nil { + t.Fatalf("Tick: %v", err) + } + if len(fired) != 0 { + t.Fatalf("Tick fired %d timers before the deadline, want 0", len(fired)) + } + } +} + +// TestTick_TimerArmedAndFiredInOneTick_NotPersisted proves a timer a tick both arms and +// fires leaves the table, so a checkpoint doesn't persist it for recovery to fire again. +func TestTick_TimerArmedAndFiredInOneTick_NotPersisted(t *testing.T) { + ctx := context.Background() + m := state.ForgeFor[*timerCtx]("zeroDelay"). + State("idle"). + State("wait"). + SuperState("parent"). + Initial("p1"). + SubState("p1"). + SubState("p2"). + SubState("p3"). + EndSuperState(). + Initial("idle"). + Transition("idle").On("arm").GoTo("wait"). + Transition("wait").After(10 * time.Second).On("go").GoTo("parent"). + Transition("parent").After(0).On("zero").GoTo("p2"). + Transition("p2").On("poke").GoTo("p3"). + Quench() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](1), + } + 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: %v", err) + } + clk.Advance(10 * 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) + } + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + fired, err := recovered.Tick(ctx) + if err != nil { + t.Fatalf("recovered Tick: %v", err) + } + if len(fired) != 0 { + t.Fatalf("recovered Tick fired %d timers, want 0", len(fired)) + } +} + +// TestTick_TimerDueAfterTheFirstRead_NotPersisted proves a timer that comes due between a +// tick's clock reads leaves the table with the others it fired, so a checkpoint doesn't +// persist it and recovery doesn't fire it again. +func TestTick_TimerDueAfterTheFirstRead_NotPersisted(t *testing.T) { + ctx := context.Background() + m := twoTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := &driftingClock{now: epoch} + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](1), + } + tickAcrossTwoDeadlines(t, m, store, id, clk, opts) + + recovered, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + again, err := recovered.Tick(ctx) + if err != nil { + t.Fatalf("recovered Tick: %v", err) + } + if len(again) != 0 { + t.Fatalf("recovered Tick fired %d timers, want 0", len(again)) + } +} + +// TestRecover_TimerDueAfterTheFirstRead_NotPersisted proves the same when the tick is +// replayed: the replayed tick drops the timer, so the next checkpoint doesn't persist it. +func TestRecover_TimerDueAfterTheFirstRead_NotPersisted(t *testing.T) { + ctx := context.Background() + m := twoTimerMachine() + store := durable.NewMemStore() + id := durable.InstanceID("timer-1") + clk := &driftingClock{now: epoch} + opts := []durable.Option[string, string, *timerCtx]{ + durable.WithRunnerClock[string, string, *timerCtx](clk), + durable.WithCheckpointEvery[string, string, *timerCtx](6), + } + tickAcrossTwoDeadlines(t, m, store, id, clk, opts) + + first, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("first Recover: %v", err) + } + for range 3 { // cross a checkpoint boundary after the tick has replayed + if _, err = first.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke): %v", err) + } + } + second, err := durable.Recover(ctx, m, store, id, opts...) + if err != nil { + t.Fatalf("second Recover: %v", err) + } + again, err := second.Tick(ctx) + if err != nil { + t.Fatalf("recovered Tick: %v", err) + } + if len(again) != 0 { + t.Fatalf("recovered Tick fired %d timers, want 0", len(again)) + } +} diff --git a/durable/timetravel.go b/durable/timetravel.go index 82518af..66b647d 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "time" "github.com/stablekernel/crucible/state" ) @@ -90,10 +91,10 @@ func (v *TimeTravelView[S, E, C]) Snapshot() state.Snapshot[S, E, C] { return v. func (v *TimeTravelView[S, E, C]) Step() int { return v.step } // StateAt reconstructs a durable instance's state AS OF the recorded step, read-only: -// it restores the start baseline and replays the recorded driving events, service -// settlements, actor transitions, and clock reads forward up to step, returning a -// detached view of the instance at that point. It runs no service, re-instantiates -// no actor, reads no wall clock, and dispatches no domain effect — every result is a +// it restores the start baseline, re-arms the timers the baseline carries, and replays +// the recorded driving events, service settlements, actor transitions, and clock reads +// forward up to step, returning a detached view of the instance at that point. It runs +// no service, re-instantiates no actor, reads no wall clock, and dispatches no domain effect — every result is a // pure replay of recorded values — and it mutates neither the live instance nor the // Store. The same functional options a Runner takes are accepted (the event codec, // the service registry and actor palette needed to settle recorded results, the @@ -102,7 +103,9 @@ func (v *TimeTravelView[S, E, C]) Step() int { return v.step } // // step must be in [BaselineStep, lastRecordedStep]; a step outside that range // reports ErrStepOutOfRange, an unknown instance reports ErrInstanceNotFound, and an -// ended ctx reports its error. +// ended ctx reports its error. It also fails when a baseline timer's event won't decode +// with the event codec passed, and when a tick of journal format 3 or later fires a +// different number of timers on replay than it recorded. func StateAt[S comparable, E comparable, C any]( ctx context.Context, m *state.Machine[S, E, C], @@ -133,12 +136,13 @@ func StateAt[S comparable, E comparable, C any]( bounded := boundRecords(records, step) repClock := newReplayClock(clockReadings(bounded), cfg.clock) - inst, err := restoreBaseline(m, baseline, repClock) + env := unmarshalCheckpoint(baseline) + inst, err := restoreBaseline(m, env, repClock) if err != nil { return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } - if err := replayThrough(ctx, inst, &cfg, bounded, unmarshalCheckpoint(baseline).Format); err != nil { + if err := replayThrough(ctx, inst, &cfg, bounded, env, repClock); 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 @@ -195,15 +199,14 @@ func lastStep(records []Record) int { // restoreBaseline unwraps the baseline checkpoint envelope and restores a detached // kernel instance from it under the bounded replay clock, so the reconstruction -// reads recorded instants rather than the wall clock. The baseline carries no armed -// timers (it is the pre-event cast), so its envelope's timer table is empty and only -// the snapshot matters here. +// reads recorded instants rather than the wall clock. The timers the baseline carries +// are re-armed by replayThrough. func restoreBaseline[S comparable, E comparable, C any]( m *state.Machine[S, E, C], - baseline []byte, + env checkpointEnvelope, repClock state.Clock, ) (*state.Instance[S, E, C], error) { - snap, err := state.UnmarshalSnapshot[S, E, C](unmarshalCheckpoint(baseline).Snapshot) + snap, err := state.UnmarshalSnapshot[S, E, C](env.Snapshot) if err != nil { return nil, fmt.Errorf("unmarshaling baseline snapshot: %w", err) } @@ -229,15 +232,31 @@ func replayThrough[S comparable, E comparable, C any]( inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], bounded []Record, - format int, + env checkpointEnvelope, + repClock *replayClock, ) error { sched := state.NewScheduler(inst) + // Re-arm the baseline's timers before the window replays, because it can fire them. + // As in Recover, the deadlines are absolute, so a held instant keeps this read from + // consuming a recorded reading. + armedAt := time.Unix(0, 0).UTC() + reEffects, _, err := reArmEffects(cfg.eventCodec, env.Timers, armedAt) + if err != nil { + return fmt.Errorf("re-arming baseline timers: %w", err) + } + if len(reEffects) > 0 { + repClock.hold(armedAt) + sched.Absorb(ctx, reEffects) + repClock.release() + } + svc := newReplayServiceRunner(inst, cfg) if svc != nil { svc.Absorb(ctx, inst.StartEffects()) } + reads := 0 // clock readings through the current Record 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. @@ -246,12 +265,15 @@ 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 { + if err := checkFormat(env.Format, &bounded[i]); err != nil { return err } + reads += clockReadCount(&bounded[i]) if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, armsActorFires(&bounded[i])); err != nil { return err } + // Leave none of the Record's readings for the next one, as Recover does. + repClock.skipTo(reads) } // 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.