From 3ff699f992b925b9e32049c2c32a6db80a7717b1 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 5 Nov 2026 09:23:39 -0700 Subject: [PATCH 1/2] fix(durable): land checkpoints when tick barriers step over the interval A tick barrier spans several step ordinals, so WithCheckpointEvery could miss its multiple forever and the tail grew without limit. A checkpoint now lands on any step that crosses a boundary. Relates to #214. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 6 ++++ durable/runner.go | 15 +++++---- durable/runner_options.go | 17 ++++++---- durable/timer_checkpoint_test.go | 57 +++++++++++++++++++++++++++++--- 4 files changed, 78 insertions(+), 17 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 25606c4..435b61d 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -245,6 +245,12 @@ 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. +- **`WithCheckpointEvery` now bounds the tail of a timer-driven instance.** A `Tick` that + fires timers takes several step ordinals, so it could skip the interval forever and the + tail grew without limit. A checkpoint now lands on the first step that reaches or passes + the interval. Such an instance now compacts, so on a Store without `HistoryStore`, + `StateAt` can't reach the steps before its latest checkpoint: it returns the + checkpoint's later state with a nil error, or `ErrStepOutOfRange` if the tail is empty. - **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 diff --git a/durable/runner.go b/durable/runner.go index f125c41..ffacf6d 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -1309,11 +1309,11 @@ func (h *Handle[S, E, C]) offerCheckpointLocked(ctx context.Context, rec *Record if h.out.failed != nil { return nil } - if h.checkpointDue(rec.Step) && rec.Snapshot != nil && (h.out.pending == nil || rec.Step > h.out.pending.step) { + if h.checkpointDue(rec) && rec.Snapshot != nil && (h.out.pending == nil || rec.Step > h.out.pending.step) { h.out.pending = &dueCheckpoint{step: rec.Step, snapshot: rec.Snapshot} } cp := h.out.pending - if cp == nil || (cp.waitDue && !h.checkpointDue(rec.Step)) { + if cp == nil || (cp.waitDue && !h.checkpointDue(rec)) { return nil } for step := range h.out.dispatching { @@ -1343,9 +1343,12 @@ func (h *Handle[S, E, C]) offerCheckpointLocked(ctx context.Context, rec *Record return nil } -// checkpointDue reports whether the checkpoint policy lands a checkpoint at step. -func (h *Handle[S, E, C]) checkpointDue(step int) bool { - return h.runner.cfg.checkpointEvery > 0 && (step+1)%h.runner.cfg.checkpointEvery == 0 +// checkpointDue reports whether rec crosses a checkpoint boundary. It compares the +// ordinals rec spans rather than testing rec's own Step, because a tick barrier consumes +// several ordinals and can step over the one a fixed multiple would land on. +func (h *Handle[S, E, C]) checkpointDue(rec *Record) bool { + every := h.runner.cfg.checkpointEvery + return every > 0 && rec.followingStep()/every > rec.Step/every } // appendStep marshals the due checkpoint snapshot into rec (so the Record carries it) @@ -1365,7 +1368,7 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) // They ran before the step's own work, so they come first. rec.Entries = append(before, rec.Entries...) } - if h.checkpointDue(step) { + if h.checkpointDue(rec) { snap, err := state.MarshalSnapshot(h.inst.Snapshot()) if err != nil { return fmt.Errorf("durable: marshaling checkpoint at step %d for %q: %w", step, h.id, err) diff --git a/durable/runner_options.go b/durable/runner_options.go index 3ab17b8..ca498e1 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -16,9 +16,10 @@ type Option[S comparable, E comparable, C any] func(*runnerConfig[S, E, C]) // runnerConfig holds resolved Option state for a Runner. type runnerConfig[S comparable, E comparable, C any] struct { - // checkpointEvery is the checkpoint policy: persist a full Snapshot and - // compact the journal tail every N fired steps. Zero (the default) takes no - // periodic checkpoint, so recovery replays from the start baseline. + // checkpointEvery is the checkpoint policy: persist a full Snapshot and compact the + // journal tail after each step that brings the next ordinal to or past a multiple of + // N. Zero (the default) takes no periodic checkpoint, so recovery replays from the + // start baseline. checkpointEvery int // eventCodec reconstructs a recorded event for replay; it defaults to JSON. eventCodec EventCodec[E] @@ -54,10 +55,12 @@ type runnerConfig[S comparable, E comparable, C any] struct { } // WithCheckpointEvery sets the checkpoint policy: the Runner persists a full -// Snapshot and compacts the journal tail every n fired steps, bounding both the -// stored tail and the replay length on recovery. A non-positive n disables -// periodic checkpointing (the default), so recovery replays the whole run from -// the start baseline. +// Snapshot and compacts the journal tail after each step that brings the next step +// ordinal to or past a multiple of n, so n=8 lands on Step 7 for plain steps. This bounds +// both the stored tail and the replay length on recovery. Each recorded step takes one +// ordinal, except a Tick that fires timers, which takes one plus one per timer fired. A +// non-positive n disables periodic checkpointing (the default), so recovery replays the +// whole run from the start baseline. func WithCheckpointEvery[S comparable, E comparable, C any](n int) Option[S, E, C] { return func(c *runnerConfig[S, E, C]) { if n > 0 { diff --git a/durable/timer_checkpoint_test.go b/durable/timer_checkpoint_test.go index bf34cc8..f37704c 100644 --- a/durable/timer_checkpoint_test.go +++ b/durable/timer_checkpoint_test.go @@ -753,7 +753,7 @@ func TestRecover_ChainedTimerAfterSlowAction_NotFiredEarly(t *testing.T) { id := durable.InstanceID("timer-1") opts := []durable.Option[string, string, *timerCtx]{ durable.WithRunnerClock[string, string, *timerCtx](clk), - durable.WithCheckpointEvery[string, string, *timerCtx](2), + durable.WithCheckpointEvery[string, string, *timerCtx](3), // the first tick checkpoints, the second stays in the tail } h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, &timerCtx{}, state.WithInitialState("idle")) if err != nil { @@ -766,13 +766,17 @@ func TestRecover_ChainedTimerAfterSlowAction_NotFiredEarly(t *testing.T) { 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) } + _, tail, err := store.Load(ctx, id) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(tail) == 0 { + t.Fatal("tail is empty, want the second tick left for replay") + } recovered, err := durable.Recover(ctx, m, store, id, opts...) if err != nil { t.Fatalf("Recover: %v", err) @@ -1035,3 +1039,48 @@ func TestRecover_TimerDueAfterTheFirstRead_NotPersisted(t *testing.T) { t.Fatalf("recovered Tick fired %d timers, want 0", len(again)) } } + +// TestTimerCheckpoint_BarriersCannotStepOverTheInterval proves a checkpoint still lands +// when tick barriers keep stepping over the configured multiple. +func TestTimerCheckpoint_BarriersCannotStepOverTheInterval(t *testing.T) { + ctx := context.Background() + m := pollingMachine() + store := durable.NewMemStore() + id := durable.InstanceID("poll-1") + clk := state.NewFakeClock(epoch) + opts := []durable.Option[string, string, *runCtx]{ + durable.WithRunnerClock[string, string, *runCtx](clk), + durable.WithCheckpointEvery[string, string, *runCtx](8), + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, id, &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + // Two Fires put the barriers on even steps, so none lands on the step before a multiple + // of 8, where a plain run checkpoints. + for _, ev := range []string{"start", "poke"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire(%s): %v", ev, err) + } + } + for range 50 { + clk.Advance(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) + } + if len(tail) > 8 { + t.Fatalf("tail holds %d records after 50 ticks, want the checkpoint to bound it", len(tail)) + } + 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) + } +} From 30deaf1076652108af5f9a021949c8584dd4753a Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Tue, 17 Nov 2026 18:19:20 -0700 Subject: [PATCH 2/2] docs(durable): say which step a checkpoint lands on WithCheckpointEvery's godoc now says a checkpoint lands after a step whose span crosses a multiple of n, and that an idle Tick takes no ordinal. The CHANGELOG says what StateAt returns with an empty tail. The cadence test also ticks the recovered Handle. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 5 +++-- durable/runner_options.go | 17 +++++++++-------- durable/timer_checkpoint_test.go | 6 ++++++ 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 435b61d..5a59703 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -248,9 +248,10 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. - **`WithCheckpointEvery` now bounds the tail of a timer-driven instance.** A `Tick` that fires timers takes several step ordinals, so it could skip the interval forever and the tail grew without limit. A checkpoint now lands on the first step that reaches or passes - the interval. Such an instance now compacts, so on a Store without `HistoryStore`, + a multiple of n. Such an instance now compacts, so on a Store without `HistoryStore`, `StateAt` can't reach the steps before its latest checkpoint: it returns the - checkpoint's later state with a nil error, or `ErrStepOutOfRange` if the tail is empty. + checkpoint's later state with a nil error. With an empty tail, any step after + `BaselineStep` returns `ErrStepOutOfRange`. - **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 diff --git a/durable/runner_options.go b/durable/runner_options.go index ca498e1..1c3cb3d 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -17,9 +17,9 @@ type Option[S comparable, E comparable, C any] func(*runnerConfig[S, E, C]) // runnerConfig holds resolved Option state for a Runner. type runnerConfig[S comparable, E comparable, C any] struct { // checkpointEvery is the checkpoint policy: persist a full Snapshot and compact the - // journal tail after each step that brings the next ordinal to or past a multiple of - // N. Zero (the default) takes no periodic checkpoint, so recovery replays from the - // start baseline. + // journal tail after each step whose span crosses a multiple of N: the step starts + // below it and the next ordinal reaches or passes it. Zero (the default) takes no + // periodic checkpoint, so recovery replays from the start baseline. checkpointEvery int // eventCodec reconstructs a recorded event for replay; it defaults to JSON. eventCodec EventCodec[E] @@ -55,11 +55,12 @@ type runnerConfig[S comparable, E comparable, C any] struct { } // WithCheckpointEvery sets the checkpoint policy: the Runner persists a full -// Snapshot and compacts the journal tail after each step that brings the next step -// ordinal to or past a multiple of n, so n=8 lands on Step 7 for plain steps. This bounds -// both the stored tail and the replay length on recovery. Each recorded step takes one -// ordinal, except a Tick that fires timers, which takes one plus one per timer fired. A -// non-positive n disables periodic checkpointing (the default), so recovery replays the +// Snapshot and compacts the journal tail after each step whose span crosses a multiple +// of n: the step starts below it and the next step ordinal reaches or passes it, so n=8 +// lands on Step 7 for plain steps. This bounds both the stored tail and the replay length +// on recovery. Each recorded step takes one ordinal, except a Tick that fires timers, +// which takes one plus one per timer fired. An idle Tick records nothing and takes no +// ordinal. A non-positive n disables periodic checkpointing (the default), so recovery replays the // whole run from the start baseline. func WithCheckpointEvery[S comparable, E comparable, C any](n int) Option[S, E, C] { return func(c *runnerConfig[S, E, C]) { diff --git a/durable/timer_checkpoint_test.go b/durable/timer_checkpoint_test.go index f37704c..76cf442 100644 --- a/durable/timer_checkpoint_test.go +++ b/durable/timer_checkpoint_test.go @@ -1083,4 +1083,10 @@ func TestTimerCheckpoint_BarriersCannotStepOverTheInterval(t *testing.T) { 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) } + // The recovered Handle's re-armed timer fires, and its tick appends. + clk.Advance(time.Second) + fired, err := recovered.Tick(ctx) + if err != nil || len(fired) != 1 { + t.Fatalf("recovered Tick = %d fired, %v, want 1", len(fired), err) + } }