Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions durable/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
31 changes: 12 additions & 19 deletions durable/checkpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -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)
Expand Down
22 changes: 9 additions & 13 deletions durable/checkpoint_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand All @@ -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)
}
Expand All @@ -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")
}
Expand Down
72 changes: 63 additions & 9 deletions durable/clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
//
Expand All @@ -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
Expand Down Expand Up @@ -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().
Expand All @@ -116,20 +131,21 @@ 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 {
mu sync.Mutex
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}
}
Expand All @@ -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++
Expand All @@ -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) }
Expand Down
2 changes: 1 addition & 1 deletion durable/clock_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Loading
Loading