Documentation
¶
Overview ¶
Package durable is the host-side durable-execution runtime for the Crucible state kernel. It records the nondeterministic results a running instance consumes and persists them, so an instance can be checkpointed, crash, and resume by replaying recorded values back through the kernel's pure transition function rather than re-invoking their external sources.
The package is additive over the state kernel: it consumes the kernel's already-reserved persistence seams — Snapshot.Journal ([]state.JournalEntry), the EffectEnvelope.EffectID correlation slot, and the injectable Clock, ServiceRunner, and ActorSystem drivers — without requiring any change to the kernel, which stays pure and stdlib-only.
Guarantees ¶
Deterministic replay: an instance recovered from its Store reaches exactly the same configuration, context, and history as a run that never crashed, because recovery replays the exact recorded driving events and nondeterministic results through the same pure transition function.
Exactly-once effects: a domain effect emitted by a step (Runner.Start's initial entry is at-least-once, and a parent transition an actor drives isn't dispatched) is applied exactly once over the instance's lifetime — the live run plus any number of recoveries — even though the runtime's replay loop is at-least-once. The exception is a crash or failed mark after the handler returned, or a handoff between owners, where an effect can apply twice, so keep handlers idempotent on EffectInstance plus the EffectID. Each effect is stamped with a deterministic EffectID (step, ordinal, kind) and deduplicated through the Store's dispatch set.
Durability across restart: every Fire step is written to the Store before it is acknowledged (write-ahead append), so a crash after a successful Fire never loses the step. A periodic Snapshot checkpoint bounds the tail that recovery must replay, so recovery cost is proportional to the tail length, not the whole run.
Caveats ¶
Payloads are serialized at the journal boundary. Event, service done-data, actor done-data, and actor messages are recorded as their JSON form; a parent reducer that type-asserts a non-JSON Go type from AssignCtx.Event observes the JSON-decoded shape on a replayed onDone. A WithEventData payload is decoded from its JSON form live as well as on replay, so a reducer gets the same value both ways; WithEventDataDecoder decodes it as the type the caller passed.
The kernel stays pure and dependency-free. The durable module is host-side: database drivers, cloud SDKs, and I/O libraries live in the caller or in out- of-tree Store backends, never in this module. The in-tree MemStore and FileStore are stdlib-only reference implementations.
Store ¶
Store is the persistence seam. A durable instance is an ordered log of Records (one per Fire step) layered over periodic full-Snapshot checkpoints. Load reconstructs an instance from its latest checkpoint plus the journal and effect tail recorded after it.
MemStore is the in-memory reference implementation: thread-safe, stdlib-only, not durable across process restarts. Use it for tests, examples, and single- process development.
FileStore is the on-disk reference implementation: a directory of per-instance subdirectories, each holding an append-only journal, an atomic checkpoint, an idempotency ledger, a dispatched-effect log and, once fenced, a fence file. Each Append flushes to stable storage; each Checkpoint uses write-temp+rename for crash-safe atomicity. Use FileStore when you need durability across restarts without a database.
Persistent database backends (PostgreSQL, DynamoDB, and the like) implement the Store interface out of tree, so heavy drivers never burden this module's dependency or vulnerability surface.
Runner / Handle / Recover ¶
Runner is the durable wrapper around a state.Machine. Wire one with a Store, then call Start to create a fresh instance (persisting a baseline checkpoint) or Fire to drive events statelessly (loading, replaying, and re-recording for each call). For a hot path that fires many events in sequence, obtain a Handle from Start or Recover and call Handle.Fire directly, avoiding a Store round- trip between steps.
Recover reconstructs a durable instance purely from the Store: it loads the latest checkpoint Snapshot and the tail of Records after it, restores the snapshot under a replay clock (firing nothing), and replays the tail's recorded driving events through the kernel to reach the live tip. The returned Handle continues recording subsequent fires.
The three nondeterministic seams ¶
A state machine is a pure function of its inputs. The durable runtime isolates each source of nondeterminism behind a seam, records the result the first time, and replays it verbatim on every subsequent recovery — so the kernel's transition function is never re-invoked for a value it has already consumed.
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 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: 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 replayed back through the same kernel settle seam — that service is never re-invoked and the same onDone or onError event re-fires with the same data. A result that wasn't recorded has nothing to replay, so the service runs again when the host calls RunService.
Child-machine actors (WithActorPalette): an actor's behavior runs on the live path; each parent transition the delivery drives is journaled as a JournalActorMessage. On recovery the recorded transition is re-fired directly through the parent with the recorded done-data, so a settled actor never re-runs. Each step records the declared actors that ran and ended, settled or stopped, and Recover doesn't spawn those. An InvokeActor actor still running at recovery restarts from its initial state, because its own state isn't journaled, and a Spawn actor doesn't return.
Idempotent effect dispatch ¶
A transition may emit a domain effect — sending an email, charging a card, publishing a message — as an Effect value the kernel routes out through FireResult.Effects without applying. The Runner applies it through the caller- supplied EffectHandler (WithEffectHandler), exactly once over the instance's lifetime, with the exceptions under Exactly-once effects above.
Each emitted effect is stamped with a deterministic EffectID derived from its step, its emission ordinal within that step, and its kind — every component a pure function of the recorded run, so the same effect carries the same id on the live path and on every recovery. The Runner write-ahead appends the step Record (carrying those ids) before dispatching, then applies each effect whose id is not already in the Store's dispatched set and marks it as it succeeds. A crash between append and dispatch leaves the effect recorded but un-marked, so recovery redispatches it; a crash after dispatch finds the id marked and skips it.
The dispatched set lives in a Store that implements DispatchStore, as MemStore and FileStore do. A Runner with an effect handler requires one: Start, Recover and the stateless Runner.Fire refuse any other Store with ErrNoDispatchStore before writing anything or calling the handler. Without a handler, any Store works and no effect is applied.
Kernel driver effects (services, timers, actors) are absorbed by their host drivers and never reach the handler.
Time-travel reader ¶
StateAt reconstructs a durable instance's state as of any recorded step, read- only: it restores the start baseline and replays recorded events forward up to the requested step, running no service, re-instantiating no actor, reading no wall clock, and dispatching no domain effect. The Store is consulted only through reads; neither the recorded log nor the dispatched set is touched.
Time-travel requires the full Record history through the target step. A Store that compacts its journal at each checkpoint can no longer reach a compacted step. A Store opts into full history by implementing HistoryStore; the in-tree MemStore does so under WithHistory. StateAt falls back to Load (latest checkpoint plus tail) when the Store does not implement HistoryStore.
Example ¶
Example shows the Store round-trip a durable instance relies on: append the per-step journal as an instance advances, checkpoint a full Snapshot to compact the tail, then load the checkpoint plus the post-checkpoint tail to reconstruct the instance.
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/stablekernel/crucible/durable"
"github.com/stablekernel/crucible/state"
)
func main() {
ctx := context.Background()
store := durable.NewMemStore()
const id = durable.InstanceID("order-42")
// Record two steps of nondeterministic results as the instance fires.
for step := range 2 {
_, err := store.Append(ctx, id, durable.Record{
Step: step,
Entries: []state.JournalEntry{{
Step: step,
Kind: state.JournalServiceResult,
CorrelationID: fmt.Sprintf("charge-%d", step),
Payload: json.RawMessage(`{"ok":true}`),
}},
})
if err != nil {
panic(err)
}
}
// Checkpoint a full snapshot through step 0, compacting that step's tail.
snap, err := state.MarshalSnapshot(state.Snapshot[string, string, map[string]any]{
Machine: "order",
Current: "charging",
Configuration: []string{"charging"},
Context: map[string]any{"orderID": "42"},
})
if err != nil {
panic(err)
}
if cpErr := store.Checkpoint(ctx, id, snap, 0); cpErr != nil {
panic(cpErr)
}
// Load reconstructs from the checkpoint plus the post-checkpoint tail.
loaded, tail, err := store.Load(ctx, id)
if err != nil {
panic(err)
}
restored, err := state.UnmarshalSnapshot[string, string, map[string]any](loaded)
if err != nil {
panic(err)
}
fmt.Println("checkpoint state:", restored.Current)
fmt.Println("tail steps:", len(tail))
fmt.Println("first tail step:", tail[0].Step)
}
Output: checkpoint state: charging tail steps: 1 first tail step: 1
Index ¶
- Constants
- Variables
- func AppendFence(opts ...AppendOption) int64
- func AppendIdempotencyKey(opts ...AppendOption) string
- func CheckpointFence(opts ...CheckpointOption) int64
- func DecodeAs[T any](data []byte) (any, error)
- func JournalPath(root string, id InstanceID) string
- func Steps(ctx context.Context, st Store, id InstanceID) ([]int, error)
- type ActorSet
- type AppendOption
- type CheckpointOption
- type DispatchStore
- type EffectHandler
- type EventCodec
- type EventDataDecoder
- type FileStore
- func (s *FileStore) Append(_ context.Context, id InstanceID, rec Record, opts ...AppendOption) (int64, error)
- func (s *FileStore) Checkpoint(_ context.Context, id InstanceID, snapshot []byte, throughStep int, ...) error
- func (s *FileStore) Dispatched(_ context.Context, id InstanceID) (map[string]bool, error)
- func (s *FileStore) LastStep(_ context.Context, id InstanceID) (int, bool, error)
- func (s *FileStore) Load(_ context.Context, id InstanceID) ([]byte, []Record, error)
- func (s *FileStore) MarkDispatched(_ context.Context, id InstanceID, effectIDs ...string) error
- type FileStoreOption
- type Handle
- func (h *Handle[S, E, C]) ActorRef(id string) (state.ActorRef, bool)
- func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef, event any) (bool, error)
- func (h *Handle[S, E, C]) DeliverToActorByID(ctx context.Context, id string, event any) (bool, error)
- func (h *Handle[S, E, C]) Drain(ctx context.Context) error
- func (h *Handle[S, E, C]) Fire(ctx context.Context, event E, opts ...state.FireOption) (state.FireResult[S], error)
- func (h *Handle[S, E, C]) ID() InstanceID
- func (h *Handle[S, E, C]) Instance() *state.Instance[S, E, C]
- func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.FireResult[S], bool, error)
- func (h *Handle[S, E, C]) Tick(ctx context.Context) ([]state.FireResult[S], error)
- func (h *Handle[S, E, C]) View(ctx context.Context, fn func(*state.Instance[S, E, C])) error
- type HistoryStore
- type InstanceID
- type MemStore
- func (s *MemStore) Append(_ context.Context, id InstanceID, rec Record, opts ...AppendOption) (int64, error)
- func (s *MemStore) Checkpoint(_ context.Context, id InstanceID, snapshot []byte, throughStep int, ...) error
- func (s *MemStore) Dispatched(_ context.Context, id InstanceID) (map[string]bool, error)
- func (s *MemStore) History(_ context.Context, id InstanceID) ([]byte, []Record, error)
- func (s *MemStore) LastStep(_ context.Context, id InstanceID) (int, bool, error)
- func (s *MemStore) Load(_ context.Context, id InstanceID) ([]byte, []Record, error)
- func (s *MemStore) MarkDispatched(_ context.Context, id InstanceID, effectIDs ...string) error
- type MemStoreOption
- type Option
- func WithActorPalette[S comparable, E comparable, C any](palette map[string]state.ActorBehavior) Option[S, E, C]
- func WithCheckpointEvery[S comparable, E comparable, C any](n int) Option[S, E, C]
- func WithEffectHandler[S comparable, E comparable, C any](h EffectHandler) Option[S, E, C]
- func WithEventCodec[S comparable, E comparable, C any](codec EventCodec[E]) Option[S, E, C]
- func WithEventDataDecoder[S comparable, E comparable, C any](d EventDataDecoder[E]) Option[S, E, C]
- func WithMaxEventDataBytes[S comparable, E comparable, C any](n int) Option[S, E, C]
- func WithOwnerFence[S comparable, E comparable, C any](token int64) Option[S, E, C]
- func WithRunnerClock[S comparable, E comparable, C any](c state.Clock) Option[S, E, C]
- func WithServiceRegistry[S comparable, E comparable, C any](reg *state.Registry[C]) Option[S, E, C]
- type Record
- type Runner
- type StepReporter
- type Store
- type TimeTravelView
Examples ¶
Constants ¶
const BaselineStep = baselineStep
BaselineStep is the step that addresses an instance's start baseline — its state immediately after Start, before any event fired. StateAt(ctx, m, st, id, BaselineStep) reconstructs the freshly cast instance.
Variables ¶
var ( // ErrInstanceNotFound is reported by Store.Load for an instance that has // never been written. ErrInstanceNotFound = errors.New(errorPrefix + errorInstanceNotFound) // ErrStepOutOfOrder is reported by Store.Append when a Record's Step does not // strictly follow the instance's highest recorded Step (and is not an // idempotent re-append of an already-recorded Step). ErrStepOutOfOrder = errors.New(errorPrefix + errorStepOutOfOrder) // ErrStepConflict is reported by Store.Append when a Step is already recorded // with a different Record: the writer's view of the instance has diverged from // the journal, usually because another writer got there first. The Record was // not written. ErrStepConflict = errors.New(errorPrefix + errorStepConflict) // ErrFenced is reported by Store.Append and Store.Checkpoint for a write whose // fence token is lower than the highest the Store has seen for the instance: // a newer owner has taken the instance over. Nothing is written. ErrFenced = errors.New(errorPrefix + errorFenced) // ErrEventDataEncoding wraps a Handle.Fire refused before the kernel ran, because // its state.WithEventData payload has no JSON form that decodes again, decodes as a // different type than the caller passed (see WithEventDataDecoder), panics while // encoding (such as an error that's a typed nil), or exceeds WithMaxEventDataBytes. // Nothing applied, so the Handle stays usable. ErrEventDataEncoding = errors.New(errorPrefix + errorEventDataEncoding) // ErrRecordTooLarge is reported by FileStore.Append for a Record whose journal line // exceeds the store's line limit, which a later Load could not read back, even // without its Snapshot. No journal line is written, but a Handle's kernel has already // applied the step, so the Handle fails with ErrHandleFailed. ErrRecordTooLarge = errors.New(errorPrefix + errorRecordTooLarge) // ErrHandleFailed is reported by a Handle's Fire, Tick, RunService, DeliverToActor // and View, on the call that failed the Handle and every later one. It wraps the // cause, which is one of: // - a step applied to the live instance but may not have been recorded; // - a Tick, RunService or DeliverToActor ran while its context ended, so a Fire it // drove may have been refused: it had already consumed the timer, service or // delivery, so it can't simply refuse the way Fire does; // - a step, Fire included, drove a Fire that a context's ending refused, such as a // spawned actor's onError: Recover restores the state from before the step, so a // Fire's event must be fired again; // - host code panicked during a step; // - an effect handler failed. // Call Handle.Drain, then Recover a new Handle with the same options to continue, // unless the cause is ErrFenced: then a newer owner holds the instance, so stop. ErrHandleFailed = errors.New(errorPrefix + errorHandleFailed) // ErrReentrantStep is reported by a Handle's Fire, Tick, RunService, DeliverToActor // and View when called with the context a step passed to host code, such as a // service's context or the Ctx a guard, action or reducer gets: the step holds the // Handle's lock, so waiting would deadlock. Nothing applied. Effect handlers run // after the lock is released and may call back in. Drain reports it when called // from inside a step or an effect handler. ErrReentrantStep = errors.New(errorPrefix + errorReentrantStep) // ErrCheckpointNotAdvancing is reported by Store.Checkpoint when throughStep // does not advance beyond the instance's current checkpoint. ErrCheckpointNotAdvancing = errors.New(errorPrefix + errorCheckpointNotAdvancing) // ErrInstanceExists is reported by Runner.Start when the InstanceID is already // present in the Store, so a fresh Start does not clobber a recorded instance. ErrInstanceExists = errors.New(errorPrefix + errorInstanceExists) // ErrEffectDispatch wraps a failure returned by the caller-supplied effect // handler (WithEffectHandler) while applying an emitted effect, or a panic in it, // and an error or panic in the Store's dispatch tracking (DispatchStore's // Dispatched or MarkDispatched), with the cause in its chain. The effect was // persisted (write-ahead) but not marked dispatched, so the Handle fails with // ErrHandleFailed wrapping it, and Recover dispatches it again; a failure in // Runner.Start leaves no instance. Recover fails with this error while the handler, // or the dispatch tracking, still does, so retrying Recover can succeed once they // recover. An effect handler wired with a Store that isn't a DispatchStore is // refused with ErrNoDispatchStore instead, which this doesn't match. Callers match // this with errors.Is to tell a dispatch failure from a kernel transition or a // Record's persistence error. ErrEffectDispatch = errors.New(errorPrefix + errorEffectDispatch) // ErrNoDispatchStore is returned by Start, Recover and the stateless Runner.Fire, // before they read or write the Store or call the handler, for an effect handler // (WithEffectHandler) wired with a Store that doesn't implement DispatchStore, // which has no dispatch tracking. It is a permanent configuration error: retrying // doesn't help. Wire a Store that implements DispatchStore, as MemStore and // FileStore do, or drop WithEffectHandler. It doesn't match ErrEffectDispatch, so a // caller that retries Recover on a dispatch failure doesn't loop on it. ErrNoDispatchStore = errors.New(errorPrefix + errorNoDispatchStore) )
Sentinel errors a Store or a Handle reports. Callers match them with errors.Is.
var ErrStepOutOfRange = errors.New(errorPrefix + errorStepOutOfRange)
ErrStepOutOfRange is reported by StateAt when the requested step is below the start baseline or beyond the instance's last recorded step. Callers match it with errors.Is.
Functions ¶
func AppendFence ¶
func AppendFence(opts ...AppendOption) int64
AppendFence returns the fence token opts carry, or zero when there is none. It is how a Store backend outside this package reads the token.
func AppendIdempotencyKey ¶
func AppendIdempotencyKey(opts ...AppendOption) string
AppendIdempotencyKey returns the explicit key opts carry, or "" when there is none. It is how a Store backend outside this package honors WithIdempotencyKey.
func CheckpointFence ¶
func CheckpointFence(opts ...CheckpointOption) int64
CheckpointFence returns the fence token opts carry, or zero when there is none. It is how a Store backend outside this package reads the token.
func DecodeAs ¶
DecodeAs decodes a recorded payload into a T, the usual body of an EventDataDecoder case: DecodeAs[Order] hands Assign an Order. DecodeAs[any] gives JSON's own form: a struct arrives as map[string]any and a number as float64.
func JournalPath ¶
func JournalPath(root string, id InstanceID) string
JournalPath returns the append-only journal file path for an instance under a FileStore rooted at root. It is exported so tests and tooling can inspect or fault-inject the on-disk journal directly.
func Steps ¶
Steps enumerates the recorded step ordinals of an instance, in order, so a caller can drive StateAt across the run (for example to render an audit timeline). It reports only externally fired and service/actor steps — the ordinals a StateAt target may name — and is read-only. An unknown instance reports ErrInstanceNotFound.
Types ¶
type ActorSet ¶
type ActorSet struct {
// IDs are the actors' ids, sorted.
IDs []string `json:"ids"`
}
ActorSet is a set of child-machine actor ids at a point in a durable instance's journal.
type AppendOption ¶
type AppendOption func(*appendConfig)
AppendOption configures a single Store.Append call. It is the additive extension point for per-append behavior the durable runner layers on later (for example, an explicit idempotency key distinct from the Record's Step).
func WithFence ¶
func WithFence(token int64) AppendOption
WithFence carries the writer's fence token on an Append: an increasing number, issued by the host with each ownership of the instance. A Store refuses a token lower than the highest it has seen for the instance with ErrFenced (see Store). A non-positive token is the same as no token, which a fenced instance refuses. WithCheckpointFence is the Checkpoint counterpart; a Runner sets both from WithOwnerFence.
func WithIdempotencyKey ¶
func WithIdempotencyKey(key string) AppendOption
WithIdempotencyKey sets an explicit idempotency key for an Append, overriding the default of deduplicating on the Record's Step alone. Two Appends carrying the same key for the same instance collapse to one, with no comparison of the Records. An empty key is ignored (the Step-based default applies). Keys starting "step:" are reserved for the Store's own per-Step key.
type CheckpointOption ¶
type CheckpointOption func(*checkpointConfig)
CheckpointOption configures a single Store.Checkpoint call. It is the additive extension point for per-checkpoint policy a backend may layer on, so that policy can arrive without breaking the Store interface. Time-travel retention, which an earlier per-checkpoint flag covered, is now a store-level capability (the HistoryStore seam, MemStore's WithHistory).
func WithCheckpointFence ¶
func WithCheckpointFence(token int64) CheckpointOption
WithCheckpointFence carries the writer's fence token on a Checkpoint, with the same meaning as WithFence on an Append. A non-positive token is the same as no token, which a fenced instance refuses.
type DispatchStore ¶
type DispatchStore interface {
// MarkDispatched records that the effects named by effectIDs have been applied
// for the instance. It is idempotent: re-marking an id is a no-op.
MarkDispatched(ctx context.Context, id InstanceID, effectIDs ...string) error
// Dispatched returns the set of effect ids already applied for the instance as
// a membership map. An instance with none reports an empty (non-nil) map.
Dispatched(ctx context.Context, id InstanceID) (map[string]bool, error)
}
DispatchStore is the dedup seam for idempotent effect dispatch: the Store tracks which effect ids an instance has applied, so a (re)dispatch skips the ones that already landed. It is an additive, optional capability — the core Store interface is unchanged; a backend opts in by implementing these two methods. A Runner with an effect handler (WithEffectHandler) requires it: Start, Recover and the stateless Runner.Fire refuse a Store that doesn't implement it with ErrNoDispatchStore, before any Store write or handler call. A Runner with no handler dispatches nothing and needs neither method. The in-tree MemStore and FileStore implement it. A persistent backend marks an id in the same transaction that records its side-effect acknowledgement to keep the guarantee tight.
type EffectHandler ¶
EffectHandler applies one emitted domain effect, identified by its stamped EffectID. The Runner calls it once per EffectID over the lifetime of an instance (see WithEffectHandler), with three exceptions: a repeated Start can apply the initial entry's effects again (see Runner.Start), an effect applies again if the handler returned but the mark didn't land, and two owners can run it at once during a handoff. An id is unique only within its instance: EffectInstance reads the instance from ctx. A non-nil error leaves the effect un-marked for Recover to retry, and fails the Handle with ErrHandleFailed wrapping ErrEffectDispatch and the error.
type EventCodec ¶
type EventCodec[E comparable] interface { // Decode reconstructs the event value from its recorded payload. An empty // payload decodes to the zero event. Decode(payload []byte) (E, error) }
EventCodec encodes and decodes an event value E to and from its structured JSON form, the inverse of the kernel's Trace.EventPayload marshaling. It is the seam by which Recover reconstructs the exact event to re-Fire. The default codec uses encoding/json; supply a custom one with WithEventCodec for events the default cannot round-trip.
type EventDataDecoder ¶
type EventDataDecoder[E comparable] func(event E, data []byte) (any, error)
EventDataDecoder rebuilds a state.WithEventData payload from its recorded JSON form, for the live Fire and for every replay of it. It gets the event the payload rode with, so one decoder serves a machine whose events carry different payload types. Return the payload as the same type the caller passed: a Fire whose payload decodes as another type is refused with ErrEventDataEncoding. Only the top-level type is checked, so a []any of structs still arrives as a []any of maps. An untyped nil payload arrives as nil without reaching the decoder; a typed nil, such as a nil pointer or map, encodes as null and is refused as a type mismatch. The default decodes with DecodeAs[any]. Supply one with WithEventDataDecoder.
type FileStore ¶
type FileStore struct {
// contains filtered or unexported fields
}
FileStore is an on-disk Store: a directory of per-instance subdirectories, each holding an append-only journal of Records, the instance's latest Snapshot checkpoint, an append-only idempotency ledger, and an append-only set of dispatched effect ids. It is stdlib-only and durable across process restarts — a fresh FileStore opened over the same directory reconstructs every instance from disk, with no carried in-memory state — so it is the persistent reference backend the in-memory MemStore is the volatile counterpart to.
On-disk layout ¶
Under the store's root directory, each instance lives in its own subdirectory named by a filesystem-safe encoding of its InstanceID:
<root>/<encoded-id>/journal.log append-only, one JSON Record per line <root>/<encoded-id>/checkpoint.snap latest checkpoint Snapshot bytes <root>/<encoded-id>/checkpoint.meta latest checkpoint throughStep <root>/<encoded-id>/applied.log append-only idempotency ledger, one JSON line per key (key, seq, digest) <root>/<encoded-id>/dispatched.log append-only dispatched effect ids <root>/<encoded-id>/fence highest fence token seen, once there is one
The journal is the source of truth for the post-checkpoint Record tail; the checkpoint files hold the compacted prefix's Snapshot; the applied ledger preserves an idempotency key even after its Record is compacted out of the journal; the dispatched log backs the DispatchStore dedup set.
Atomicity and crash-safety ¶
An Append writes one complete newline-terminated JSON line to the journal and flushes it to stable storage before returning, so a successful Append is durable. A crash mid-write can leave a torn (newline-less or unparseable) trailing line; on reopen the loader reads complete lines and stops at the first torn trailing record, discarding it without corrupting the intact prefix. A Checkpoint writes the Snapshot and its throughStep through a write-temp+rename, which is atomic on POSIX filesystems, then rewrites the journal to only the post-checkpoint tail (also via temp+rename), so a concurrent reopen never observes a checkpoint torn against its tail.
All methods are safe for concurrent use; a per-instance mutex serializes writes to one instance's files while distinct instances proceed independently.
A directory belongs to one open FileStore at a time. Each keeps an in-memory index it never re-reads, so two over one directory, in one process or two, can overwrite each other: conflicting steps can reach the journal and the fence can go down. FileStore's fencing holds only between writers sharing one FileStore. A multi-process host needs a networked backend.
func NewFileStore ¶
func NewFileStore(dir string, opts ...FileStoreOption) (*FileStore, error)
NewFileStore opens (creating if absent) a FileStore rooted at dir. Existing instance subdirectories under dir are discovered lazily on first access and reconstructed from their files, so reopening over a populated directory carries every recorded instance forward. Construction is configured through functional options; with none supplied it returns a ready store.
func (*FileStore) Append ¶
func (s *FileStore) Append(_ context.Context, id InstanceID, rec Record, opts ...AppendOption) (int64, error)
Append implements Store. It is atomic and idempotent per (id, key), durably writing a complete journal line before returning.
func (*FileStore) Checkpoint ¶
func (s *FileStore) Checkpoint(_ context.Context, id InstanceID, snapshot []byte, throughStep int, opts ...CheckpointOption) error
Checkpoint implements Store. It atomically persists snapshot at throughStep (temp+rename) and compacts the on-disk journal to only the post-checkpoint tail. throughStep must advance beyond the current checkpoint.
func (*FileStore) Dispatched ¶
Dispatched returns the set of effect ids already applied for the instance as a membership map. An instance never written reports an empty (non-nil) set. It satisfies the DispatchStore seam.
func (*FileStore) LastStep ¶
LastStep reports the highest Step recorded for id, across its checkpoint and its tail, so FileStore is a StepReporter.
func (*FileStore) Load ¶
Load implements Store. It returns the latest checkpoint plus the post- checkpoint Record tail in Step order, or ErrInstanceNotFound.
func (*FileStore) MarkDispatched ¶
MarkDispatched records that the effects named by effectIDs have been applied for the instance, appending each new id durably. It is idempotent and satisfies the DispatchStore seam.
type FileStoreOption ¶
type FileStoreOption func(*fileStoreConfig)
FileStoreOption configures FileStore construction. It keeps NewFileStore extensible — new construction-time knobs (on-disk encoding, sync policy, retention) arrive as additive options rather than new positional parameters.
type Handle ¶
type Handle[S comparable, E comparable, C any] struct { // contains filtered or unexported fields }
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 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.
Fire, Tick, RunService and DeliverToActor are safe to call from different goroutines: each holds the Handle's step lock while it applies to the kernel and writes its Record, including any service or actor it runs. A step's domain effects dispatch after it releases the lock, so an effect handler may call back into the Handle. Effects of steps on different goroutines can dispatch in either order. Steps fired one after another dispatch in order, except that a step fired from inside an effect handler dispatches before the rest of that handler's step. A checkpoint waits until every step at or before it has dispatched, so it never compacts an effect still being sent. An effect handler that panics fails the Handle like one that returns an error.
Code that runs under the lock (a service, guard, action, reducer or actor behavior) can't act on the Handle itself; to act on the Handle when a step happens, an action returns an effect, and its handler runs after the lock and may call back. A call back during a live step that carries the step's context, as a service gets and a guard, action or reducer finds in its input's Ctx, returns ErrReentrantStep at once. One without that context deadlocks, and so does one under middleware that passed down a context not derived from the step's. A step waiting for the lock returns its context's error once the context ends, and changes nothing. View reads the instance under the lock; Instance returns it outside the lock. A stateless Runner.Fire builds its own Handle, so it isn't serialized with this one.
A step that applied to the kernel but may not have been recorded leaves the Handle out of step with the journal, and so does one that panicked in host code; the panic reaches the caller after the Handle fails. So does a RunService or DeliverToActor whose context ended during the step, a Tick whose context ended while its timers fired, and any step, Fire included, that drove a Fire refused because a context ended, the caller's or one middleware derived from it. A message to an actor that the actor refused because the step's context ended doesn't fail it: the message is lost, as actor deliveries are across Recover. That call and every later one return ErrHandleFailed, wrapping the cause, which can be a context that ended during the Store write. Before recovering, call Drain: a step on another goroutine may still be recording, which a recovered Handle wouldn't load, or sending an effect, which it would send again. Recovering a healthy Handle's instance instead needs this Handle's calls to have returned first. Recover a new Handle with the same options to continue. A service whose result wasn't recorded is in flight again, so RunService runs it a second time. A running InvokeActor actor restarts from its initial state on any Recover, losing every delivery so far, and a Spawn actor doesn't return. If the cause is ErrFenced, a newer owner holds the instance: stop, because recovering won't help. A failed effect dispatch fails the Handle the same way, and Recover retries the effect.
func Recover ¶
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)
Recover reconstructs a durable instance purely from the Store: it loads the latest checkpoint Snapshot and the journal/effect tail after it, Restores the snapshot (firing nothing, no IO), and replays the tail's recorded driving events through the kernel to reach the instance's live state. The returned Handle continues recording subsequent Fires. Recover reports ErrInstanceNotFound for an instance that was never started, and the context's error if ctx ends before the journal is replayed, or a context's ending refuses a parent Fire an actor it spawned drove. A ctx that ends once the actors are spawned, with no Fire refused, doesn't fail it, as for Start: their behaviors already ran. It applies any recorded 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. 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 (*Handle[S, E, C]) ActorRef ¶
ActorRef returns the ActorRef for the running actor under id, and whether such an actor is running, so a host can address a spawned child for DeliverToActor. It is a thin pass-through to the underlying ActorSystem; a handle with no actor palette wired runs no actors and always reports false.
func (*Handle[S, E, C]) DeliverToActor ¶
func (h *Handle[S, E, C]) DeliverToActor(ctx context.Context, ref state.ActorRef, event any) (bool, error)
DeliverToActor routes event into the running actor identified by ref, runs the actor (settling it when it reaches its final state), records each parent transition the delivery drove, and persists the produced step. The actor behavior is resolved and run against the palette supplied with WithActorPalette; the done-data, error, or parent-driving message it routes is journaled as a JournalActorMessage correlated by the actor id so recovery replays it without re-instantiating the actor.
It returns whether the actor was found running: false for a ref that names no live actor (already settled, stopped, or never spawned), or false and an error when no palette is wired, the Handle has failed, or ctx ended before the delivery. Once the actor ran it returns true with any error. A result that won't encode, a ctx that ended by the end of the delivery, or a parent Fire refused because a context ended (ctx, or one middleware derived from it) returns ErrHandleFailed and records nothing: a ctx that ended before the actor handled the event made the kernel refuse the actor's own Fire, and the event was lost. On a recovered Handle an InvokeActor actor restarts from its initial state, and a Spawn actor doesn't return. A failed Append also returns ErrHandleFailed, but the write may have landed anyway, and Recover finds out which. If another goroutine failed the Handle while this step was recording, it returns true and ErrHandleFailed saying the step was recorded. A failed Checkpoint returns the plain error, and the delivery is recorded. Resending a recorded delivery repeats any message it sends the parent.
Example ¶
ExampleHandle_DeliverToActor shows the actor record/replay seam: a child shipping actor runs once on the live path (its done-data recorded), and on recovery the recorded done-data is replayed back through the same parent onDone without re-running the actor — so the recovered instance reaches the same state and context, and the actor's run count never advances past one. (A delivery whose context ends partway records nothing, and a recovered Handle restarts the actor.)
package main
import (
"context"
"fmt"
"github.com/stablekernel/crucible/durable"
"github.com/stablekernel/crucible/state"
)
// fulfillmentCtx is a small JSON-marshalable context for the actor example.
type fulfillmentCtx struct {
Tracking string `json:"tracking"`
}
// fulfillmentMachine supervises a child shipping actor: it spawns the actor on
// entering supervising and folds the actor's done-data (a tracking number) into
// context on its onDone.
func fulfillmentMachine() *state.Machine[string, string, *fulfillmentCtx] {
return state.ForgeFor[*fulfillmentCtx]("fulfillment").
Reducer("track", func(in state.AssignCtx[*fulfillmentCtx]) *fulfillmentCtx {
c := in.Entity
if tr, ok := in.Event.(string); ok {
c.Tracking = tr
}
return c
}).
Actor("ship").
State("supervising").InvokeActor("ship", state.WithInvokeOnDone("shipped"), state.WithInvokeOnError("failed")).
State("complete").Final().
State("aborted").Final().
Initial("supervising").
Transition("supervising").On("shipped").GoTo("complete").Assign("track").
Transition("supervising").On("failed").GoTo("aborted").
Quench()
}
func main() {
ctx := context.Background()
var runs int
palette := map[string]state.ActorBehavior{
"ship": func(map[string]any) (state.ActorInstance, error) {
child := state.ForgeFor[*fulfillmentCtx]("shipper").
State("packing").
State("shipped").Final().
Initial("packing").
Transition("packing").On("dispatch").GoTo("shipped").
Quench()
inst := child.Cast(&fulfillmentCtx{}, state.WithInitialState[string]("packing"))
return state.NewActor(inst, func(*state.Instance[string, string, *fulfillmentCtx]) any {
runs++
return fmt.Sprintf("TRK-%d", runs)
}), nil
},
}
m := fulfillmentMachine()
store := durable.NewMemStore()
const id = durable.InstanceID("ship-1")
runner := durable.NewRunner(m, store, durable.WithActorPalette[string, string, *fulfillmentCtx](palette))
h, err := runner.Start(ctx, id, &fulfillmentCtx{}, state.WithInitialState("supervising"))
if err != nil {
panic(err)
}
// Drive the shipping actor to completion: it runs once and routes its tracking
// number through the parent onDone.
ref, ok := h.ActorRef(state.ActorID("fulfillment", "supervising", 0))
if !ok {
panic("no actor ref")
}
if _, err = h.DeliverToActor(ctx, ref, "dispatch"); err != nil {
panic(err)
}
// Recover: the recorded done-data is replayed; the actor is not run again.
recovered, err := durable.Recover(ctx, m, store, id,
durable.WithActorPalette[string, string, *fulfillmentCtx](palette))
if err != nil {
panic(err)
}
snap := recovered.Instance().Snapshot()
fmt.Println("recovered state:", snap.Current)
fmt.Println("recovered tracking:", snap.Context.Tracking)
fmt.Println("actor runs:", runs)
}
Output: recovered state: complete recovered tracking: TRK-1 actor runs: 1
func (*Handle[S, E, C]) DeliverToActorByID ¶
func (h *Handle[S, E, C]) DeliverToActorByID(ctx context.Context, id string, event any) (bool, error)
DeliverToActorByID is DeliverToActor keyed by raw actor id, for a host that tracks ids rather than refs.
func (*Handle[S, E, C]) Drain ¶
Drain waits until no step of h is still recording and no domain effect of h is still being dispatched, or ctx ends. Call it after ErrHandleFailed and before Recover: a step on another goroutine may still be appending its Record, which a recovered Handle wouldn't load, or sending an effect it recorded, which a recovered Handle would send again because it isn't marked yet. Drain first waits for the step lock, so a step that was recording has finished, then for dispatch. Once the Handle has failed, no step can start, so Drain covers every step and effect. On a healthy Handle it covers only work already under way: a step can start after Drain returns, so before handing the instance to a new Handle, stop driving this one and let its calls return. It returns ctx's error if ctx ends first, at once if ctx has already ended: then nothing is drained, so don't Recover until Drain returns nil. Give it a context of its own, not the failed call's. It returns ErrReentrantStep, without waiting, when called from inside a step or an effect handler of h, whose own work it would wait on forever. A call from a goroutine an effect handler started, without the handler's context, can't be told apart and waits for that handler; one from a goroutine a service or a View callback started, without the step's context, waits for that step.
func (*Handle[S, E, C]) Fire ¶
func (h *Handle[S, E, C]) Fire(ctx context.Context, event E, opts ...state.FireOption) (state.FireResult[S], error)
Fire drives one event through the Handle's live instance and records the step: it Fires the kernel, appends a Record carrying the driving event at the step's ordinal (write-ahead, before returning), and — when the checkpoint policy is due — persists a full Snapshot and compacts the tail. A kernel transition error journals nothing (no step was produced) and is returned to the caller. A failed checkpoint returns the result and that error: the step is recorded and its effects sent, the Handle carries on, and the next step the policy makes due checkpoints. A checkpoint this step wrote for an earlier one, which failed because ctx ended, isn't reported, since this step succeeded. If another goroutine failed the Handle while this step was recording, Fire returns ErrHandleFailed saying the step was recorded; Recover sends its effects. It applies the step's domain effects after the append and before any checkpoint; a failed dispatch fails the Handle with ErrHandleFailed.
A Fire the kernel refuses, because ctx ended or for any other reason, returns that error, records nothing and leaves the Handle usable. When the event applies, an actor the step spawned can fail and route its onError through the instance; if a context ending, ctx or one derived from it, refuses that onError, Fire fails the Handle with ErrHandleFailed and records nothing, though the event applied. Recover restores the state from before the event, so fire it again on the recovered Handle, and don't act on the result Fire returned with that error. Only a parent Fire a context refused fails the step: a Fire that drove none records, even if ctx ends after the kernel applied it. A message to an actor, or an actor's start, that the actor refused because ctx ended is lost, as actor deliveries are across Recover; failing the step would have the retry run the actors' behaviors, and their side effects, again. A panic in host code during the step fails the Handle, then reaches the caller: recover it, then Drain and Recover as for ErrHandleFailed.
A forwardTo on the event's transition forwards the event to the actor it names.
A state.WithEventData payload reaches the transition's Assign as the Runner's EventDataDecoder rebuilds it from the payload's JSON form, live and on replay alike, so both see the same value. Decode it as the type the caller passed: a payload that decodes as another type refuses the Fire with ErrEventDataEncoding before the kernel runs. The default decoder gives JSON's own form, so it refuses a struct or an int until WithEventDataDecoder covers that event. An error arrives as an error with the same message, with any invalid UTF-8 replaced, though errors.Is no longer matches it. Keep its message, not the error, in context: a checkpoint turns an error into a map, and Recover fails on an error-typed field. A payload that can't take this form, an error whose Error panics (such as a typed nil), or one over WithMaxEventDataBytes, also refuses the Fire with ErrEventDataEncoding before the kernel runs. The payload is read on the calling goroutine with no lock of its own, so don't mutate it concurrently with Fire.
func (*Handle[S, E, C]) ID ¶
func (h *Handle[S, E, C]) ID() InstanceID
ID returns the InstanceID the Handle records under.
func (*Handle[S, E, C]) Instance ¶
Instance returns the underlying kernel Instance the Handle wraps, for reads such as Configuration, Snapshot, or Current. Drive it through the Handle's Fire (or the Runner's) so steps continue to be recorded; firing the bare Instance bypasses durability. It's outside the Handle's step lock, so read it only while no step is running, or use View. After ErrHandleFailed it shows state the journal may not hold.
func (*Handle[S, E, C]) RunService ¶
func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.FireResult[S], bool, error)
RunService runs the in-flight invoked service identified by id, records its outcome, and settles it — firing the invocation's onDone (on success) or onError (on failure) event through the durable instance and recording the produced step. The service is resolved and executed against the registry supplied with WithServiceRegistry; its result or error is journaled as a JournalServiceResult correlated by id so recovery replays it without re-invoking the service. The outcome reaches the machine JSON-decoded, live as on replay, and the journal holds that form: a struct is a map, an integer a float64 that loses precision above 2^53. An error is message-only: an error with the same message, which errors.Is and errors.As no longer match, live or on replay. So onError's Assign and the ServiceRunner's LastError see a plain error even for an unbound service's *state.UnboundRefError.
It returns the routed FireResult and true, or the zero result and false when id names no in-flight service (already settled, stopped, or never started). It returns false and an error when no registry is wired, the Handle has failed, or ctx ended before the service started.
Once the service has run, it returns true with any error. A result that won't encode, a result whose JSON form won't decode, such as a number beyond float64, a ctx that ended during the service or while its settle's effects were absorbed (even after a clean settle), or a Fire the settle drove refused because a context ended (ctx, or one middleware derived from it) returns ErrHandleFailed and records nothing: a recovered Handle has the service in flight again, and RunService runs it a second time. A KindedEffect the settle emits whose payload won't marshal doesn't fail it: it is recorded by id and kind, as recordEffects says, and dispatches as any effect does. A failed Append also returns ErrHandleFailed, but the write may have landed anyway: Recover finds out, and the service runs again only if the result isn't in the journal. If another goroutine failed the Handle while this step was recording, it returns the result, true and ErrHandleFailed saying the step was recorded. Every ErrHandleFailed also matches its cause, so test for ErrHandleFailed first, then ErrFenced, as the Handle doc says. A failed Checkpoint returns the plain error, and the result is recorded. A failed effect dispatch also returns ErrHandleFailed, but the result is recorded: Recover retries the effect and the service doesn't run again.
A result whose JSON form won't decode, or that has no JSON form, such as a chan, is refused only after its settle applied: the onDone Assign runs once on an internal stand-in for the result (for one with no JSON form, the raw result), and the state onDone enters starts its actors and services. Only then does RunService return ErrHandleFailed, recording nothing, and after Recover the service runs again, its onDone Assign with it. An Assign that asserts the payload's type unchecked panics on the stand-in, which refuses the settle's Fire, and RunService still returns ErrHandleFailed. So keep a service's result JSON round-trippable, and have an onDone Assign check the payload's type rather than assume it.
Example ¶
ExampleHandle_RunService shows the invoked-service record/replay seam: a pricing service runs once on the live path (its returned quote recorded), and on recovery the recorded quote is replayed back through the same settle seam without re-invoking the service — so the recovered instance reaches the same state and context, and the service's call count never advances past one. (A turn whose context ends partway records nothing, and a recovered Handle runs it again.)
package main
import (
"context"
"fmt"
"github.com/stablekernel/crucible/durable"
"github.com/stablekernel/crucible/state"
)
// quoteCtx is a small JSON-marshalable context for the invoked-service example.
type quoteCtx struct {
Quote string `json:"quote"`
}
// quoteMachine invokes a pricing service on entering quoting, folding the returned
// quote into context on its onDone.
func quoteMachine(fn state.ServiceFn[*quoteCtx]) *state.Machine[string, string, *quoteCtx] {
return state.ForgeFor[*quoteCtx]("quote").
Service("price", fn).
Reducer("save", func(in state.AssignCtx[*quoteCtx]) *quoteCtx {
c := in.Entity
if q, ok := in.Event.(string); ok {
c.Quote = q
}
return c
}).
State("cart").
State("quoting").Invoke("price", state.WithInvokeOnDone("priced"), state.WithInvokeOnError("failed")).
State("quoted").Final().
State("rejected").Final().
Initial("cart").
Transition("cart").On("checkout").GoTo("quoting").
Transition("quoting").On("priced").GoTo("quoted").Assign("save").
Transition("quoting").On("failed").GoTo("rejected").
Quench()
}
func main() {
ctx := context.Background()
var calls int
fn := func(context.Context, state.ServiceCtx[*quoteCtx]) (any, error) {
calls++
return fmt.Sprintf("quote-%d", calls), nil
}
reg := state.NewRegistry[*quoteCtx]().Service("price", fn)
m := quoteMachine(fn)
store := durable.NewMemStore()
const id = durable.InstanceID("quote-1")
runner := durable.NewRunner(m, store, durable.WithServiceRegistry[string, string, *quoteCtx](reg))
h, err := runner.Start(ctx, id, "eCtx{}, state.WithInitialState("cart"))
if err != nil {
panic(err)
}
if _, err = h.Fire(ctx, "checkout"); err != nil {
panic(err)
}
// Run the pricing service: it executes once and routes its result through onDone.
if _, _, err = h.RunService(ctx, state.InvokeID("quote", "quoting", 0)); err != nil {
panic(err)
}
// Recover: the recorded quote is replayed; the service is not run again.
recovered, err := durable.Recover(ctx, m, store, id,
durable.WithServiceRegistry[string, string, *quoteCtx](reg))
if err != nil {
panic(err)
}
snap := recovered.Instance().Snapshot()
fmt.Println("recovered state:", snap.Current)
fmt.Println("recovered quote:", snap.Context.Quote)
fmt.Println("service calls:", calls)
}
Output: recovered state: quoted recovered quote: quote-1 service calls: 1
func (*Handle[S, E, C]) Tick ¶
Tick advances the Handle's delayed-transition scheduler: it fires every timer whose recorded deadline is at or before the recording clock's current time, in 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. 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 the Handle and records nothing, as for Fire. A message to an actor refused because ctx ended is lost, as for Fire. A forwardTo on a timer's transition forwards the timer's event, rebuilt with the Runner's event codec. If the codec can't rebuild it, Tick forwards nothing, records the tick and dispatches its effects as usual, and returns the results with the codec's error; the Handle carries on. It returns the FireResults of the timers it fired, in order. A failed checkpoint returns them with that error, and the Handle carries on. If another goroutine failed the Handle while this step was recording, it returns them with ErrHandleFailed saying the step was recorded. If ctx ends while the due timers fire, or a context derived from it (by middleware, say) refuses a timer's Fire, it fails the 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; 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 (*Handle[S, E, C]) View ¶
View runs fn with the live instance while it holds the Handle's step lock, so the read can't race a step on another goroutine. fn must not call back into the Handle, and must not keep the instance past its return. View returns ctx's error if ctx ends before the lock is free, ErrReentrantStep if ctx is a step's own context, and ErrHandleFailed once the Handle has failed, without running fn.
type HistoryStore ¶
type HistoryStore interface {
// History returns the instance's start baseline snapshot bytes (the BaselineStep
// checkpoint, nil if the instance was never started through a Runner) together
// with the full ordered Record log — every Record ever appended, in Step order,
// including those a checkpoint later compacted out of the live tail. It reports
// ErrInstanceNotFound for an instance that was never written.
History(ctx context.Context, id InstanceID) (baseline []byte, records []Record, err error)
}
HistoryStore is the optional time-travel seam: a Store that retains an instance's start baseline snapshot and its full ordered Record log, so a reader can reconstruct the state as of any recorded step even after checkpoint compaction discarded that step from the live tail. It is additive, like DispatchStore — the core Store interface is unchanged; a backend opts in by implementing this method, and StateAt uses it when present, falling back to Load otherwise. The in-tree MemStore implements it when constructed WithHistory.
type InstanceID ¶
type InstanceID string
InstanceID is the stable identity of one durable instance: the key under which a Store records and reconstructs that instance's checkpoint and journal/effect tail. It is host-assigned and opaque to the Store.
func EffectInstance ¶
func EffectInstance(ctx context.Context) (InstanceID, bool)
EffectInstance returns the instance an EffectHandler call belongs to, from the ctx the handler received. A handler that keeps its own dedupe record must key on this plus the effect id, because effect ids repeat across instances.
type MemStore ¶
type MemStore struct {
// contains filtered or unexported fields
}
MemStore satisfies Store and is safe for concurrent use by multiple goroutines.
func NewMemStore ¶
func NewMemStore(opts ...MemStoreOption) *MemStore
NewMemStore returns an in-memory Store. Construction is configured through functional options (see WithInitialCapacity); with none supplied it returns a ready, empty store.
func (*MemStore) Append ¶
func (s *MemStore) Append(_ context.Context, id InstanceID, rec Record, opts ...AppendOption) (int64, error)
Append implements Store. It is atomic and idempotent per (id, key), where key is the Record Step by default or the WithIdempotencyKey value when supplied.
func (*MemStore) Checkpoint ¶
func (s *MemStore) Checkpoint(_ context.Context, id InstanceID, snapshot []byte, throughStep int, opts ...CheckpointOption) error
Checkpoint implements Store. It persists snapshot as the instance's checkpoint at throughStep and compacts the tail through that step. throughStep must advance beyond the current checkpoint. Time-travel retention is a store-level capability (NewMemStore with WithHistory), so no CheckpointOption changes what Load returns here.
func (*MemStore) Dispatched ¶
Dispatched returns the set of effect ids already applied for the instance, as a membership map. An instance never written reports an empty (non-nil) set rather than an error: the dedup query is a pure read of "what has landed", orthogonal to whether any Record exists yet. It satisfies the DispatchStore seam.
func (*MemStore) History ¶
History implements HistoryStore for a MemStore constructed WithHistory: it returns the instance's start baseline snapshot and its full ordered Record log, including Records a checkpoint compacted out of the live tail, so a time-travel read can reconstruct any recorded step. Without WithHistory the baseline is nil and the returned log is the live (compacted) tail, sufficient only for steps at or after the latest checkpoint. It reports ErrInstanceNotFound for an unknown instance.
func (*MemStore) LastStep ¶
LastStep reports the highest Step recorded for id, across its checkpoint and its tail, so MemStore is a StepReporter.
func (*MemStore) Load ¶
Load implements Store. It returns the latest checkpoint plus the post- checkpoint Record tail in Step order, or ErrInstanceNotFound.
func (*MemStore) MarkDispatched ¶
MarkDispatched records that the effects named by effectIDs have been applied for the instance, so a subsequent (re)dispatch skips them. It is atomic and idempotent: re-marking an already-marked id is a no-op, and a partially marked batch is completed without error. It satisfies the DispatchStore seam.
type MemStoreOption ¶
type MemStoreOption func(*memStoreConfig)
MemStoreOption configures MemStore construction. It keeps NewMemStore extensible — new construction-time knobs arrive as additive options rather than new positional parameters.
func WithHistory ¶
func WithHistory() MemStoreOption
WithHistory makes a MemStore retain each instance's start baseline snapshot and full ordered Record log, even across checkpoint compaction, so the time-travel reader (StateAt) can reconstruct the instance's state as of any recorded step. It implements the HistoryStore seam. The default discards compacted Records to bound memory; enable this for audit, debugging, or replay-inspection workloads.
func WithInitialCapacity ¶
func WithInitialCapacity(steps int) MemStoreOption
WithInitialCapacity pre-sizes each instance's Record buffer to the given number of steps, trading a little memory for fewer reallocations on instances with a known step count. A non-positive value is ignored.
type Option ¶
type Option[S comparable, E comparable, C any] func(*runnerConfig[S, E, C])
Option configures a Runner (and, through Recover, a one-shot reconstruction). It is generic over the machine's state, event, and context types so an event codec can be type-safe.
func WithActorPalette ¶
func WithActorPalette[S comparable, E comparable, C any](palette map[string]state.ActorBehavior) Option[S, E, C]
WithActorPalette binds the child-machine actor behaviors the Runner spawns and runs on the live path and resolves on recovery, keyed by the actor src name (the name passed to InvokeActor or the Spawn built-in). A durable actor's behavior runs live and its done-data, error, or parent-driving message is recorded; on recovery the recorded result is replayed back through the same parent transition and that behavior is never re-instantiated, so the palette is consulted only to run an actor whose result isn't recorded. Supply it for any machine that spawns child actors; a machine that spawns none needs none. Each behavior is the actor-model analog of a ServiceFn, registered by the same src name the machine declares.
func WithCheckpointEvery ¶
func WithCheckpointEvery[S comparable, E comparable, C any](n int) Option[S, E, C]
WithCheckpointEvery sets the checkpoint policy: the Runner persists a full 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 WithEffectHandler ¶
func WithEffectHandler[S comparable, E comparable, C any](h EffectHandler) Option[S, E, C]
WithEffectHandler binds the seam the Runner calls to apply each emitted domain effect — an email, a charge, a published message: any side effect a transition emits as a domain Effect value. Effects from a parent transition an actor drives aren't dispatched. The handler needs a Store that is a DispatchStore, as MemStore and FileStore are: with any other Store, Start, Recover and the stateless Runner.Fire refuse the configuration with ErrNoDispatchStore before they write to the Store or call the handler. A durable effect from a step is applied exactly once over the whole lifetime of an instance (the live run plus any number of recoveries), except that it can apply twice after a crash or failed mark once the handler returned, or during a handoff, so keep the handler idempotent on EffectInstance plus the id. It is deduped by a deterministic EffectID: the Runner stamps each emitted effect, write-ahead persists the step Record carrying those ids, then invokes the handler for every id not already marked dispatched, marking each as it succeeds. A handler error or panic fails the Handle with ErrHandleFailed, wrapping ErrEffectDispatch, and leaves the effect un-marked, so Recover retries it (at-least-once until it succeeds; exactly-once once it does).
The handler receives the stamped EffectID and the live effect value. It is nil by default: without it the Runner records effect ids but dispatches nothing, so an event-driven user is unaffected. Kernel driver effects (services, timers, actors) are NOT routed here — they are absorbed by the ServiceRunner, Scheduler, and ActorSystem; only domain effects reach the handler.
func WithEventCodec ¶
func WithEventCodec[S comparable, E comparable, C any](codec EventCodec[E]) Option[S, E, C]
WithEventCodec overrides the event codec the Runner uses to reconstruct a recorded event for replay, for events the default encoding/json codec cannot round-trip. The default codec decodes through encoding/json, the inverse of the kernel's Trace.EventPayload marshaling.
func WithEventDataDecoder ¶
func WithEventDataDecoder[S comparable, E comparable, C any](d EventDataDecoder[E]) Option[S, E, C]
WithEventDataDecoder sets how a recorded state.WithEventData payload is decoded for the live Fire and every replay of it. Without one, a payload decodes with DecodeAs[any], so only a payload JSON already gives back as itself (a string, bool, float64, map[string]any or []any) is accepted; a struct, an int or a typed slice is refused with ErrEventDataEncoding until the decoder covers its event. A nil decoder is ignored.
func WithMaxEventDataBytes ¶
func WithMaxEventDataBytes[S comparable, E comparable, C any](n int) Option[S, E, C]
WithMaxEventDataBytes sets the largest state.WithEventData payload Handle.Fire accepts, measured as its JSON form; for an error, its message's JSON form. A larger one refuses the Fire with ErrEventDataEncoding before the kernel runs. It defaults to 8 MiB, which leaves a payload room in FileStore's journal line; raise it for a Store with no such limit. The cap covers the payload only, so a Record can still exceed a line with its Event, Entries or Effects, and FileStore then reports ErrRecordTooLarge after the kernel ran. A non-positive n is ignored.
func WithOwnerFence ¶
func WithOwnerFence[S comparable, E comparable, C any](token int64) Option[S, E, C]
WithOwnerFence sets the fence token a Runner carries on every Append and Checkpoint, so a Handle that has lost the instance to a newer owner gets ErrFenced instead of committing. Pass the token the host's lease issued; a retry by the same owner keeps the same token. A non-positive token is the same as no token, which a fenced instance refuses. MarkDispatched is not fenced, so during a handoff an effect handler can run concurrently for one effect id.
The token applies to every instance the Runner drives, so a host with a token per instance passes it to Recover, or builds a Runner per instance. No fence token is written at recovery: a Store first sees the token on the owner's first write, and a stale write that lands before that one surfaces to the owner as ErrStepConflict.
func WithRunnerClock ¶
func WithRunnerClock[S comparable, E comparable, C any](c state.Clock) Option[S, E, C]
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 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 WithServiceRegistry ¶
func WithServiceRegistry[S comparable, E comparable, C any](reg *state.Registry[C]) Option[S, E, C]
WithServiceRegistry binds the invoked-service implementations the Runner runs on the live path and resolves on recovery. A durable service runs live and its result is recorded; on recovery the recorded result is replayed through the same settle seam and that service is never re-invoked, so the registry is consulted only to execute a service whose result isn't recorded. Supply it for any machine that declares `invoke` states; a purely event-driven or timer-driven machine needs none. The registry binds the same ServiceFns the machine declares, by name (state.NewRegistry().Service(name, fn)).
type Record ¶
type Record struct {
// Step is the ordinal this Record was produced at. Ordinals rise with each Record,
// and a tick barrier consumes one per timer it fired plus its own, so they don't
// index the instance's Traces. It is the per-instance idempotency key: a
// Store treats a second Append of the same Record at the same Step as
// already-applied.
Step int
// Event is the structured, JSON form of the driving event the Fire at this
// Step consumed — the kernel's Trace.EventPayload, captured verbatim. Replay
// reconstructs the exact event from this payload and re-Fires it to advance
// the restored instance one step, so the recorded run reaches byte-identical
// state without re-deriving the event from its human-readable label. It is
// empty for a Record that carries only a checkpoint or only nondeterministic
// Entries (an event with no JSON form is omitted, matching the kernel's
// additive EventPayload contract).
Event []byte
// EventData is the JSON form of the payload the Fire at this Step carried
// through state.WithEventData, or empty when it carried none. The live Fire and
// a replay both decode it through the Runner's EventDataDecoder, so the transition's
// Assign sees the same value.
EventData []byte `json:",omitempty"`
// EventDataError is the message of an error payload, which has no useful JSON
// form. The live Fire and a replay both supply an error with this message.
EventDataError *string `json:",omitempty"`
// Entries are the nondeterministic results recorded during this step — the
// invoked-service done/error payloads, actor messages, clock reads, and
// randomness draws the kernel consumed — in the order they resolved. Replay
// returns these verbatim instead of re-invoking their sources.
Entries []state.JournalEntry
// Effects are the effects the step emitted, each with its deterministically
// stamped EffectID, persisted before dispatch so a crash between persist and
// dispatch is recoverable: Recover re-dispatches, deduped by EffectID. A
// KindedEffect whose payload won't marshal is recorded by EffectID and Kind with no
// Payload, as an effect that isn't a KindedEffect is, and its Meta holds the
// marshal error's message under "crucible.marshalError". Replay re-derives every
// effect's value, so none is rebuilt from its envelope.
Effects []state.EffectEnvelope
// Snapshot, when non-empty, is a full marshaled state.Snapshot captured at
// this step — a checkpoint the instance can be reconstructed from without
// replaying the whole journal from the start. It is produced by
// state.MarshalSnapshot and consumed by state.UnmarshalSnapshot; the Store
// treats it as opaque bytes.
Snapshot []byte
// Tick marks a scheduler-tick barrier rather than an externally fired step: a
// Record produced when the durable Handle ticked its delayed-transition
// scheduler, carrying the clock readings that tick consumed (in Entries) and
// the count of timer steps it produced (TickSteps). Replay re-derives the
// timers by re-ticking the recovered scheduler against those recorded
// readings rather than re-firing the events directly, so each timer fires at
// its recorded instant. It is false for externally fired steps, which carry a
// driving Event instead.
Tick bool
// TickSteps is the number of timer transitions the tick at this barrier fired
// (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
// declared once this step ended that ran and have ended, settled or stopped, or
// whose spawn failed and whose onError applied, or was refused for a reason
// other than a context ending (the journal holds that onError, or the refusal
// replay meets again), so Recover doesn't spawn them again. An actor whose spawn
// failed with no onError declared isn't one, and
// neither is one whose onError a context's ending refused, since the step that
// drove it records nothing: Recover tries both again. The first step after Start records the
// set, and later steps record it when they change it. It is nil otherwise, for a
// machine with no actor palette, and on a Record from before this field. An empty
// set is not nil: a Store must keep it, though it treats other empty fields as nil.
EndedActors *ActorSet `json:",omitempty"`
// UnstartedActors, when set, holds the child-machine actors the instance's state
// declared once this step ended that aren't running and haven't ended: their latest
// spawn failed with no onError declared, or its onError was refused because a
// context ended, which
// left the step that drove it recording nothing. Recover
// spawns them as new, so the messages they send the parent as they start apply and
// are journaled. A declared actor in neither set was running, or a Recover's respawn
// of it failed, and the journal holds every parent Fire its start drove, so Recover
// spawns it again without letting those reach the parent. It's
// recorded as EndedActors is: with the first step after Start, then when a step
// changes it, and an empty set is not nil. When the journal holds none, as on a
// Record from before this field, Recover lets every spawn reach the parent.
UnstartedActors *ActorSet `json:",omitempty"`
// Format is the journal format of the durable version that wrote the Record: zero on a
// Record from before this field, and 1 from the version that arms the timers and
// services an actor-driven parent Fire's state declares. Replay arms them only for a
// Record of format 1 or later, since an older run took no clock read for them. From
// 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. 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"`
}
Record is one durable append: the unit a Store persists for a single Fire step. It carries the nondeterministic results recorded during the step (Entries), the effects the step emitted (Effects, each carrying a stamped EffectID for idempotent dispatch), and optionally a full marshaled Snapshot checkpoint taken at this step. A Record is identified within its instance by its Step ordinal; appending the same Record at the same Step twice is a no-op, and appending a different one is rejected (see Store.Append).
The Stores compare Records by a digest of their JSON form, taken through cloneRecord. A new field needs `json:",omitempty"`, or every digest changes and a retried Append after an upgrade reads as a conflict. It must also be copied in cloneRecord, or the digest ignores it. The same applies to state.JournalEntry and state.EffectEnvelope.
type Runner ¶
type Runner[S comparable, E comparable, C any] struct { // contains filtered or unexported fields }
Runner is the durable wrapper around a state.Machine: it drives the kernel's pure transition function while recording each step to a Store, so an instance can be checkpointed, crash, and resume by replaying the recorded driving events rather than re-deriving them.
A Runner is created with NewRunner and bound to one machine and one Store; it is safe to drive many instances (distinguished by InstanceID) through a single Runner. The recording model is write-ahead: every Fire persists its Record before returning, so a crash after a successful Fire never loses the step.
Record / replay model ¶
For an event-driven machine every transition is a pure function of (configuration, context, event payload, machine definition). The only input a Runner must record to reproduce a run is therefore the driving event and any payload it carried: each Fire appends a Record{Step, Event} where Step is the step's ordinal and Event is the kernel's structured Trace.EventPayload, plus the payload's JSON form for a state.WithEventData Fire. Periodically — governed by the checkpoint policy (WithCheckpointEvery) — the Runner also persists a full marshaled Snapshot and compacts the journal tail through that step, so recovery replays only the tail after the latest checkpoint rather than the whole run.
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 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 (Handle.RunService, against the registry supplied with WithServiceRegistry) and its result is journaled as a JournalServiceResult; on recovery the recorded result is replayed back through the kernel's settle seam, so that service is never re-invoked and the same onDone / onError event re-fires with the same data. A result that wasn't recorded has nothing to replay, so the service runs again when the host calls RunService.
Child-machine actors are the third recorded seam: an actor's behavior runs on the live path (Handle.DeliverToActor, against the palette supplied with WithActorPalette) and each parent transition the delivery drives — the actor's onDone / onError, or a message it sends — is journaled as a JournalActorMessage; on recovery the recorded transition is replayed by re-firing the parent directly with the recorded done-data, so the actor behavior is never re-instantiated. A Fire's or RunService's Record also journals the settles and failed spawns' onErrors its absorb drove, replayed after its own work, and the step after Start or Recover journals the ones their spawns drove, replayed first. A purely event-driven machine records no Entries.
Example ¶
ExampleRunner shows the durable record/replay loop: start an instance, fire a sequence of events through the Runner (each step recorded write-ahead), then recover a fresh instance purely from the Store and observe it reaches the same state and context the live run did.
package main
import (
"context"
"fmt"
"github.com/stablekernel/crucible/durable"
"github.com/stablekernel/crucible/state"
)
// orderCtx is a small JSON-marshalable context for the Runner example.
type orderCtx struct {
Charges int `json:"charges"`
}
// orderMachine is a flat event-driven order machine: pending -> charged -> done.
func orderMachine() *state.Machine[string, string, *orderCtx] {
return state.ForgeFor[*orderCtx]("order").
Action("charge", func(c state.ActionCtx[*orderCtx]) (state.Effect, error) {
c.Entity.Charges++
return nil, nil
}).
State("pending").
State("charged").
State("done").Final().
Initial("pending").
Transition("pending").On("pay").GoTo("charged").Do("charge").
Transition("charged").On("ship").GoTo("done").
Quench()
}
func main() {
ctx := context.Background()
m := orderMachine()
store := durable.NewMemStore()
const id = durable.InstanceID("order-7")
// Start records a baseline checkpoint; each Fire appends the driving event,
// and the checkpoint policy compacts the tail every two steps.
runner := durable.NewRunner(m, store, durable.WithCheckpointEvery[string, string, *orderCtx](2))
if _, err := runner.Start(ctx, id, &orderCtx{}, state.WithInitialState("pending")); err != nil {
panic(err)
}
for _, ev := range []string{"pay", "ship"} {
if _, err := runner.Fire(ctx, id, ev); err != nil {
panic(err)
}
}
// Recover reconstructs the instance from the Store alone — Load the checkpoint,
// Restore it, replay the recorded tail.
recovered, err := durable.Recover(ctx, m, store, id)
if err != nil {
panic(err)
}
snap := recovered.Instance().Snapshot()
fmt.Println("recovered state:", snap.Current)
fmt.Println("recovered charges:", snap.Context.Charges)
}
Output: recovered state: done recovered charges: 1
Example (DurableTimer) ¶
ExampleRunner_durableTimer shows a time-dependent machine recorded and replayed through the clock seam: the live run arms a one-hour reminder and fires it by advancing a fake clock; recovery on a different wall-clock baseline replays the recorded clock readings, so the reminder fires at its recorded instant and the recovered instance matches the live one — wall-clock-independent.
package main
import (
"context"
"fmt"
"time"
"github.com/stablekernel/crucible/durable"
"github.com/stablekernel/crucible/state"
)
// timerOrderCtx is a small JSON-marshalable context for the durable-timer example.
type timerOrderCtx struct {
Reminded bool `json:"reminded"`
}
// reminderMachine sends a reminder a fixed delay after an order is placed, driven
// by a delayed (`after`) transition.
func reminderMachine() *state.Machine[string, string, *timerOrderCtx] {
return state.ForgeFor[*timerOrderCtx]("reminder").
Action("remind", func(c state.ActionCtx[*timerOrderCtx]) (state.Effect, error) {
c.Entity.Reminded = true
return nil, nil
}).
State("new").
State("waiting").
State("reminded").Final().
Initial("new").
Transition("new").On("place").GoTo("waiting").
Transition("waiting").After(time.Hour).On("due").GoTo("reminded").Do("remind").
Quench()
}
func main() {
ctx := context.Background()
m := reminderMachine()
store := durable.NewMemStore()
const id = durable.InstanceID("order-9")
start := time.Date(2025, 6, 1, 9, 0, 0, 0, time.UTC)
clk := state.NewFakeClock(start)
runner := durable.NewRunner(m, store, durable.WithRunnerClock[string, string, *timerOrderCtx](clk))
h, err := runner.Start(ctx, id, &timerOrderCtx{}, state.WithInitialState("new"))
if err != nil {
panic(err)
}
if _, err = h.Fire(ctx, "place"); err != nil {
panic(err)
}
clk.Advance(2 * time.Hour) // past the one-hour reminder deadline
if _, err = h.Tick(ctx); err != nil {
panic(err)
}
// Recover on a wall clock days later: the reminder still fired at its recorded
// instant, so the recovered instance reaches the same state.
recovered, err := durable.Recover(ctx, m, store, id,
durable.WithRunnerClock[string, string, *timerOrderCtx](state.NewFakeClock(start.Add(72*time.Hour))))
if err != nil {
panic(err)
}
snap := recovered.Instance().Snapshot()
fmt.Println("recovered state:", snap.Current)
fmt.Println("reminded:", snap.Context.Reminded)
}
Output: recovered state: reminded reminded: true
func NewRunner ¶
func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st Store, opts ...Option[S, E, C]) *Runner[S, E, C]
NewRunner binds a machine and a Store into a durable Runner. Behavior is tuned with functional options — the checkpoint policy (WithCheckpointEvery) and the event codec (WithEventCodec) — each additive and defaulting to a working baseline (no periodic checkpoint, JSON event encoding).
func (*Runner[S, E, C]) Fire ¶
func (r *Runner[S, E, C]) Fire(ctx context.Context, id InstanceID, event E, opts ...state.FireOption) (state.FireResult[S], error)
Fire drives one event through a durable instance identified by id, loading and replaying it from the Store first, then recording the step. Handle.Fire describes how a state.WithEventData payload is handled, and when it's refused. Loading can return ErrEffectDispatch before the event fires, as Recover can, or ErrNoDispatchStore for an effect handler with a Store that isn't a DispatchStore. It is the stateless entry point (no Handle required); for a hot path that fires many events in sequence, hold a Handle from Start or Recover and use Handle.Fire to avoid reloading between steps. Calls on one id aren't serialized, and must not overlap each other or a live Handle.
func (*Runner[S, E, C]) Start ¶
func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opts ...state.CastOption[S]) (*Handle[S, E, C], error)
Start creates and registers a fresh durable instance: it casts the machine on input, persists a baseline checkpoint so the instance is loadable from the first step, and returns a live Handle. Cast options (for example state.WithInitialState) configure the initial configuration. Starting an 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 Recover the instance rather than Start it again. A ctx that ends with no Fire refused doesn't fail Start.
Start applies the initial entry's domain effects before the baseline write, and only if the entry succeeded: a failed entry still returns a Handle and a nil error, and Instance().InitialErr reports it. They're at-least-once, unlike a step's: a handler failure or a failed baseline write leaves no instance, so calling Start again re-applies every effect, as does a crash before the baseline. Overlapping Starts on one id, including a stale owner's, each apply them before the Store refuses all but one. To dedupe, key on EffectInstance plus the effect id. A handler wired only at Recover never sees them. With an effect handler wired, Start refuses a Store that isn't a DispatchStore with ErrNoDispatchStore, before it reads or writes the Store or calls the handler.
type StepReporter ¶
type StepReporter interface {
// LastStep returns the highest Step recorded for id, across its checkpoint and its
// tail, and false when it holds none. Recover calls it only for an instance Load just
// found, and fails on any error it returns.
LastStep(ctx context.Context, id InstanceID) (step int, ok bool, err error)
}
StepReporter is an optional Store capability: the highest Step recorded for an instance, across its checkpoint and its tail. Recover asks for it when a checkpoint from before checkpoints carried the next step leaves no Record to number from, so the next step lands past every recorded one. MemStore and FileStore implement it. A Store without it falls back to the restored Trace count, which can number a step the Store already holds, so every Append then fails with ErrStepOutOfOrder.
type Store ¶
type Store interface {
// Append persists rec for the instance and returns its monotonic per-instance
// append sequence. Appending the same Record at a Step already recorded for the
// instance is a no-op that returns the existing sequence (idempotency); a
// different Record there is rejected with ErrStepConflict. Records must be
// appended in increasing Step order; an out-of-order Step is rejected with
// ErrStepOutOfOrder. A fence token below the highest seen is rejected with
// ErrFenced. A Store with a size limit reports a Record over it, as FileStore does
// with ErrRecordTooLarge.
Append(ctx context.Context, id InstanceID, rec Record, opts ...AppendOption) (seq int64, err error)
// Load returns the instance's latest checkpoint Snapshot bytes (nil if the
// instance has been appended to but never checkpointed) together with the
// tail of Records appended after that checkpoint, in Step order. It reports
// ErrInstanceNotFound for an instance that has never been written.
Load(ctx context.Context, id InstanceID) (snapshot []byte, tail []Record, err error)
// Checkpoint persists snapshot as the instance's checkpoint at throughStep and
// compacts the journal/effect tail through that step, so a subsequent Load
// returns this Snapshot plus only the Records appended after throughStep. A
// Checkpoint that does not advance throughStep beyond the current checkpoint
// is rejected with ErrCheckpointNotAdvancing. A fence token below the highest
// seen is rejected with ErrFenced.
Checkpoint(ctx context.Context, id InstanceID, snapshot []byte, throughStep int, opts ...CheckpointOption) error
}
Store is the durable-execution persistence seam. It records an instance's per-step Records and periodic Snapshot checkpoints, and reconstructs the instance from the latest checkpoint plus the tail of Records appended after it. The in-memory MemStore is the reference implementation; persistent backends implement the same contract.
Contract ¶
Ordering: Records for an instance are totally ordered by Step. Append accepts Records in increasing Step order; Load returns the post-checkpoint tail in that same Step order. A Store preserves the relative order of Entries and Effects within each Record verbatim.
Idempotency: Append is idempotent per (InstanceID, Step). Appending the same Record at a Step already present is a no-op — the stored Record is retained unchanged and the original append sequence is returned — so an at-least-once caller (a crash-and-retry between persist and acknowledge) never double-applies a step. Appending a different Record at that Step is rejected with ErrStepConflict, because two writers disagree about the step and dropping one would acknowledge a step the journal doesn't hold. The idempotency record for a Step survives a Checkpoint that compacts that Step away, so a delayed retry of an already-checkpointed Step is still recognized rather than rejected as out of order, and a different Record there is still a conflict. Two Records are the same when every field matches, with a nil and an empty field counting as equal, except EventDataError, where nil means no error and an empty message is an error, and EndedActors and UnstartedActors, where nil means none recorded and an empty set means none. An Append carrying WithIdempotencyKey (a backend reads it with AppendIdempotencyKey) dedups on that key alone, so the caller vouches for the Record: no comparison is made. Keys starting "step:" are reserved for the Store's own per-Step key. A Step recorded under an explicit key is not recognized by a later Append without that key, or with a different one: that Append returns ErrStepOutOfOrder.
Fencing: an Append or Checkpoint may carry a fence token (WithFence, WithCheckpointFence; a backend reads it with AppendFence and CheckpointFence). A Store keeps the highest token it has seen per instance, as durably as its Records. The token check must be serialized with the write it guards, against the Store's own state. A write whose token is lower returns ErrFenced and writes nothing; this check comes before every other. A token that passes raises the highest even if the write then fails another check, so a new owner's refused first write still fences the old owner. A write with no token counts as token zero, so once an instance has been fenced an unfenced write is refused. An equal token passes, so a retry by the same owner still works. Tokens alone can't separate two writers on one token; ErrStepConflict does.
Atomicity: each Append and each Checkpoint is atomic. A concurrent Load never observes a partially written Record or a checkpoint torn against its tail; it observes either the state before the call or the state fully after it.
Consistency: Load returns the most recent checkpoint Snapshot together with every Record whose Step is strictly greater than the checkpoint's throughStep — the exact journal/effect tail needed to bring that checkpoint up to date. For an instance with no checkpoint, Snapshot is nil and the tail is the full Record history. For an unknown instance, Load reports ErrInstanceNotFound.
Fields: a Store keeps every Record field, including EventData and EventDataError. A Store that drops one of those loses that payload on recovery. Snapshot is the exception: recovery reads the checkpoint, so a Store may drop a tail Record's copy.
All methods are safe for concurrent use by multiple goroutines.
type TimeTravelView ¶
type TimeTravelView[S comparable, E comparable, C any] struct { // contains filtered or unexported fields }
TimeTravelView is the read-only result of a StateAt reconstruction: the kernel Instance restored and replayed to the requested step, and the step it was reconstructed at. The Instance is detached — it shares no state with any live Handle and is safe to read (Snapshot, Current, Configuration) but not to drive (firing it records nothing and is not durable). Obtain one from StateAt.
func StateAt ¶
func StateAt[S comparable, E comparable, C any]( ctx context.Context, m *state.Machine[S, E, C], st Store, id InstanceID, step int, opts ...Option[S, E, C], ) (*TimeTravelView[S, E, C], error)
StateAt reconstructs a durable instance's state AS OF the recorded step, read-only: 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 clock); a supplied effect handler is intentionally never invoked, since a historical read applies no side effect.
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. 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.
Example ¶
ExampleStateAt reconstructs an instance's state as of an earlier recorded step, read-only, without re-running any work or mutating the live instance. A history-retaining MemStore (WithHistory) keeps every Record so any step is reachable; Steps enumerates the recorded ordinals to read across.
package main
import (
"context"
"fmt"
"github.com/stablekernel/crucible/durable"
"github.com/stablekernel/crucible/state"
)
// ExampleStateAt reconstructs an instance's state as of an earlier recorded step,
// read-only, without re-running any work or mutating the live instance. A
// history-retaining MemStore (WithHistory) keeps every Record so any step is
// reachable; Steps enumerates the recorded ordinals to read across.
func main() {
ctx := context.Background()
m := state.ForgeFor[*auditCtx]("audit").
Action("bump", func(c state.ActionCtx[*auditCtx]) (state.Effect, error) {
c.Entity.Count++
return nil, nil
}).
State("open").
State("closed").Final().
Initial("open").
Transition("open").On("tick").GoTo("open").Do("bump").
Transition("open").On("close").GoTo("closed").Do("bump").
Quench()
store := durable.NewMemStore(durable.WithHistory())
id := durable.InstanceID("ledger-1")
runner := durable.NewRunner(m, store)
h, err := runner.Start(ctx, id, &auditCtx{}, state.WithInitialState("open"))
if err != nil {
panic(err)
}
for _, ev := range []string{"tick", "tick", "close"} {
if _, ferr := h.Fire(ctx, ev); ferr != nil {
panic(ferr)
}
}
// Enumerate the recorded steps, then reconstruct the count at each one.
steps, err := durable.Steps(ctx, store, id)
if err != nil {
panic(err)
}
for _, step := range steps {
view, verr := durable.StateAt(ctx, m, store, id, step)
if verr != nil {
panic(verr)
}
fmt.Printf("step %d: state=%s count=%d\n",
step, view.Snapshot().Current, view.Snapshot().Context.Count)
}
}
// auditCtx is a JSON-marshalable context counting the bumps a time-travel read
// reconstructs at each step.
type auditCtx struct {
Count int `json:"count"`
}
Output: step 0: state=open count=1 step 1: state=open count=2 step 2: state=closed count=3
func (*TimeTravelView[S, E, C]) Instance ¶
func (v *TimeTravelView[S, E, C]) Instance() *state.Instance[S, E, C]
Instance returns the reconstructed kernel Instance, for reads such as Snapshot, Current, or Configuration. It is a detached read-only view; drive a live instance through a Handle from Recover instead.
func (*TimeTravelView[S, E, C]) Snapshot ¶
func (v *TimeTravelView[S, E, C]) Snapshot() state.Snapshot[S, E, C]
Snapshot returns the reconstructed instance's kernel Snapshot at the target step, a convenience over Instance().Snapshot() for the common audit read.
func (*TimeTravelView[S, E, C]) Step ¶
func (v *TimeTravelView[S, E, C]) Step() int
Step returns the recorded step the view was reconstructed at (BaselineStep for the start baseline).