From e3388e7d0470d8cdfb20c14b60f506e1887713f1 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Tue, 17 Nov 2026 09:49:01 -0700 Subject: [PATCH 1/4] feat(durable): decode service results through WithEventDataDecoder and park undecodable ones Builds on #235's effect dispatch. A service result now decodes through the Runner's EventDataDecoder for the invocation's onDone event, live and on replay, as a WithEventData payload does, so a decoder hands Assign the service's own type; without one the result arrives in JSON's generic form. A service error stays message-only. - state: ServiceRunner.WithResultTransform's function takes the event that carries the outcome and returns an explicit abort: func(event E, result any, err error) (out any, outErr error, abort error). It runs on every settle, before any event fires, and an abort fires no event. Each activation carries a generation, so a settle can't settle a later activation of its service: Tick returns an empty slice, and SettleDone and SettleError return false, for a stale settle or abort. - durable: a result the decoder refuses, or decodes as another type than the service returned, is parked: RunService returns ErrEventDataEncoding with the Handle healthy, records the result with its Go type and import path, and settles nothing. The service stays in flight and its ServiceFn never runs again; a RunService after Recover with a fixed decoder settles the parked result. Checkpoints carry parked results in parkedServices, a timer or Fire that leaves the state discards them, and a checkpoint written without a registry keeps them. A ctx that ended during the ServiceFn parks nothing, and a result with no JSON form aborts the settle. - durable: every settle records the result's Go type and replay holds the decoder to it. The journal records the JSON the live settle decoded. A decoder may return json.Number for any service result. A typed nil result keeps its type through the decoder. - durable: a service result in a Record of format 3 or lower replays in JSON's generic form through no decoder, as the version that wrote it did. - durable: Recover, the stateless Runner.Fire, StateAt and Steps refuse a journal whose checkpoint or any Record records a format above this version's, including a checkpoint envelope of a shape this version can't unmarshal, and refuse a Record of a lower format than any before it as an older version appending to a newer journal. The CHANGELOG says not to run mixed versions on one instance (#253). Signed-off-by: Ray Karnes --- docs/src/content/docs/durable/overview.md | 21 +- durable/CHANGELOG.md | 163 ++++- durable/README.md | 21 +- durable/checkpoint.go | 47 +- durable/checkpoint_no_registry_test.go | 187 ++--- durable/doc.go | 19 + durable/effect_marshal_panic_test.go | 106 --- durable/errors.go | 6 +- .../internal/typefixture/alpha/model/model.go | 9 + .../internal/typefixture/beta/model/model.go | 10 + durable/journal_format_internal_test.go | 79 +++ durable/journal_format_midtail_test.go | 118 +++ durable/journal_format_mixed_test.go | 104 +++ durable/journal_format_newer_test.go | 235 ++++++ durable/journal_format_service_test.go | 96 +++ durable/journal_format_stateat_test.go | 96 +++ durable/parked_local_type_test.go | 60 ++ durable/parked_result_test.go | 484 +++++++++++++ durable/parked_tick_test.go | 311 ++++++++ durable/parked_type_test.go | 227 ++++++ durable/result_decoding_scenarios_test.go | 371 ++++++++++ durable/result_nil_and_error_test.go | 90 +++ durable/result_type_check_test.go | 98 +++ durable/runner.go | 262 +++++-- durable/runner_options.go | 17 + durable/service.go | 671 +++++++++++++++--- durable/service_activation_test.go | 52 ++ durable/service_encode_internal_test.go | 83 +++ durable/service_error_message_test.go | 58 -- durable/service_outcome_test.go | 35 +- durable/service_replay_bench_test.go | 79 +++ durable/service_result_edges_test.go | 331 +++++++++ durable/service_step_internal_test.go | 311 ++++++++ durable/service_undecodable_settle_test.go | 156 ++-- durable/settle_absorb_internal_test.go | 58 ++ durable/settled_type_test.go | 102 +++ durable/store.go | 7 +- durable/tick_service_checkpoint_test.go | 138 ---- durable/timetravel.go | 44 +- durable/typename_internal_test.go | 95 +++ state/CHANGELOG.md | 24 +- state/result_transform_test.go | 191 ++++- state/runner.go | 158 ++++- state/settle_stale_test.go | 194 +++++ 44 files changed, 5295 insertions(+), 729 deletions(-) delete mode 100644 durable/effect_marshal_panic_test.go create mode 100644 durable/internal/typefixture/alpha/model/model.go create mode 100644 durable/internal/typefixture/beta/model/model.go create mode 100644 durable/journal_format_internal_test.go create mode 100644 durable/journal_format_midtail_test.go create mode 100644 durable/journal_format_mixed_test.go create mode 100644 durable/journal_format_newer_test.go create mode 100644 durable/journal_format_service_test.go create mode 100644 durable/journal_format_stateat_test.go create mode 100644 durable/parked_local_type_test.go create mode 100644 durable/parked_result_test.go create mode 100644 durable/parked_tick_test.go create mode 100644 durable/parked_type_test.go create mode 100644 durable/result_decoding_scenarios_test.go create mode 100644 durable/result_nil_and_error_test.go create mode 100644 durable/result_type_check_test.go create mode 100644 durable/service_activation_test.go create mode 100644 durable/service_encode_internal_test.go delete mode 100644 durable/service_error_message_test.go create mode 100644 durable/service_replay_bench_test.go create mode 100644 durable/service_result_edges_test.go create mode 100644 durable/service_step_internal_test.go create mode 100644 durable/settled_type_test.go delete mode 100644 durable/tick_service_checkpoint_test.go create mode 100644 durable/typename_internal_test.go create mode 100644 state/settle_stale_test.go diff --git a/docs/src/content/docs/durable/overview.md b/docs/src/content/docs/durable/overview.md index fcc87119..e6069bfa 100644 --- a/docs/src/content/docs/durable/overview.md +++ b/docs/src/content/docs/durable/overview.md @@ -167,10 +167,23 @@ owner holds the instance, so stop. `Recover` retries an unapplied effect, and re Events, 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 of actor done-data on a replayed `onDone`. A service's -result is JSON-decoded live as well as on replay, so a reducer gets the same value both -ways: a struct is a map and an integer a `float64`, which loses precision above 2^53, and -an error an error with the same message, which `errors.Is` and `errors.As` no longer -match. A +result is decoded from its JSON form live as well as on replay, so a reducer gets the same +value both ways. When `WithEventDataDecoder` covers the invocation's `onDone` event, the +result arrives as the decoder's type, for example `durable.DecodeAs[User]`. Otherwise it +arrives in JSON's generic form: a struct as a map and an integer as a `float64`, which +loses precision above 2^53. A decoder that fails, or that returns a type other than the +one the service returned, parks the result: `RunService` returns `ErrEventDataEncoding` +and no `onDone` or `onError` reducer runs, but the journal records the result as the +service returned it, and the Handle stays healthy. The service stays in flight and never +runs again. The decoder is part of the Runner's options, so the Handle that parked the +result never sees a fix: `Recover` with the fixed decoder, then call `RunService`, and it +settles the parked result. Until then `RunService` keeps returning +`ErrEventDataEncoding`. A checkpoint keeps a parked result, and a `Fire` or timer that +leaves the state that declares the service stops the service and discards it. A service error stays message-only, an error with the same message, which `errors.Is` no +longer matches. Register the decoder before you record results: replay decodes the journal +with the recovering Runner's decoder, so a decoder added or changed after results were +recorded changes what replay hands the reducer, and one that can't decode a settled result +fails `Recover` and `StateAt` with `ErrEventDataEncoding`; a parked one doesn't fail them. 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, chosen per event, for example `durable.DecodeAs[Order]`. Without one, a payload decodes as JSON's own diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 5a597035..be9ed1b9 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -17,10 +17,12 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. onError was refused because a context ended, so `Recover` can tell them from the actors that were running. A Store must keep an empty set distinct from nil. - **`Record.Format`** records the journal format of the version that wrote the Record, - which is 3 from this version. Replay arms the timers and services an actor-driven + which is 4 from this version. Replay arms the timers and services an actor-driven parent Fire's state declares only for a Record of format 1 or later. `Recover` sends a tick's and a service settle's effects, and replay hands a tick's timer transitions' - effects to the service runner, only for a Record of format 2 or later. + effects to the service runner, only for a Record of format 2 or later. Replay decodes + a service result through `WithEventDataDecoder` only for a Record of format 4 or + later. **For Store authors:** a Store must keep `Format`, `EndedActors` and `UnstartedActors`, and keep an empty set distinct from nil. A Store that drops them, or maps an empty set to nil as an SQL array column or a protobuf repeated field can, @@ -90,6 +92,31 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. older `durable`'s `Recover` re-arms a baseline's or checkpoint's timers only after the tail, so it misses one a tail tick fired, with no error, and its `StateAt` ignores a baseline's timers. Don't downgrade a Store this version has written to. +- **Don't run mixed versions on one instance.** During a rolling deploy, let only + replicas of one version own a given instance: drain an instance's owner before a + replica of another version recovers it (#253). An older replica that appends to a + journal this version wrote stamps a lower journal format after this version's + checkpoint or Records. This version's `Recover` and stateless `Fire` then fail with an + error saying an older version appended to a newer journal, before replaying any of it, + so a refused journal sends no effect. `StateAt` and `Steps` fail with it too, on + whatever step `StateAt` targets, even one before the lower-format Record, so they + refuse the journals `Recover` refuses. This version + can't replay such a Record by the older format's rules, because the older version + reads the journal differently, settling a parked result through onDone, for one. A + version older than this one checks no journal format, so it reads the mixed journal + without refusing it, and that can't be fixed for binaries already built. When this version is the older one, it + refuses a later version's journal, with an error saying a newer version wrote it, + whenever the checkpoint or any Record it loads records a format above its own, and + doesn't then look for a lower-format Record among them. Each version checks only + what it loads, so none of this makes mixed versions safe. +- **A journal a newer version wrote is refused.** `Recover`, a stateless + `Runner.Fire`, `StateAt` and `Steps` fail, before they restore or replay anything, + on a journal whose checkpoint or any Record records a journal format above this + version's, with an error naming both formats, also when the checkpoint's envelope has + a shape this version can't unmarshal, such as a field whose type changed, rather than + restore it as a bare snapshot and fail later. A version from this one onward refuses + a newer journal, so a rollback across a later format bump fails cleanly instead of + replaying the journal as its own. Versions already built don't refuse one. - **A journal an older version wrote replays as it did.** Its actor entries carry no refusal, so `Recover` still fails on one whose parent Fire was refused, and an output recorded with a delivery's last Fire still replays into that transition. Only steps @@ -133,21 +160,69 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. relaxes `Fire`, and the stateless `Runner.Fire`, which failed with the marshal error before; `Tick` and `RunService` now record such an effect too. - **A service result reaches `Assign` decoded, live as well as on replay,** so a retried - effect can't differ from the first attempt: a struct arrives as a map, an integer as a - `float64`, which loses precision above 2^53, and an error as an error with the same - message, any invalid UTF-8 replaced, which `errors.Is` and `errors.As` no longer match. - So onError's `Assign` and the `ServiceRunner`'s `LastError` see a plain error even for - an unbound service's `*state.UnboundRefError`. An `Error` method that panics settles - with a message saying the service error panicked, its invalid UTF-8 replaced too. The journal records this decoded value. A result whose JSON - form won't decode, such as a number beyond `float64`, fails `RunService` with - `ErrHandleFailed` and records nothing, as a result that won't encode does, so - `Recover` doesn't fail on it. Either 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, before `RunService` fails; after `Recover` the service runs again, and its - `Assign` with it. So keep a service's result JSON round-trippable, and have an onDone - `Assign` check the payload's type rather than assume it. This may change, to refuse - such a result before any `Assign` runs. + effect can't differ from the first attempt. The result is decoded through the + `WithEventDataDecoder` decoder for the invocation's onDone event, as a `WithEventData` + payload is: a decoder for that event, such as `DecodeAs[Order]`, hands `Assign` that + type, and without one a struct arrives as a map and an integer as a `float64`, which + loses precision above 2^53. A decoder may always return JSON's generic form, including + a `json.Number` from one that decodes with `UseNumber`; a `WithEventData` payload + must still come back as the type its caller passed. A decoder that fails, or returns a type other than the + service returned, or a result whose JSON form won't decode, such as a number beyond + `float64`, parks the result (see below). `Recover` and `StateAt` fail with + `ErrEventDataEncoding`, running no `Assign`, on a settled result their decoder can't + decode. Every successful settle records the Go type the service returned, with its + import path, and replay holds the decoder to it as the live settle did: `Recover` and + `StateAt` fail with `ErrEventDataEncoding`, running no `Assign`, when the decoder + returns another type, such as a pointer to it. JSON's generic form, and nil, are always + accepted. Replay decodes the journal with the recovering Runner's decoder, so register + a decoder before results are recorded: changing the type a decoder returns for an event + whose results are recorded fails `Recover` on them, unless it returns the generic form, + and a decoder added later for the type the service returned changes what replay hands + `Assign` from the generic form to that type. A typed nil result, such as a nil + pointer, goes through the decoder as JSON's `null`, so `DecodeAs[*T]` hands `Assign` a + nil `*T` live and on replay alike; on main, `Assign` saw the typed nil live and an + untyped nil on replay. With no decoder it arrives as an untyped nil, and an untyped nil + result never reaches the decoder. An error stays message-only: + an error with the same message, any invalid UTF-8 replaced, 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`. An `Error` method that panics settles with a message saying the service error + panicked, its invalid UTF-8 replaced too. The journal records the JSON the live settle + decoded, so replay decodes the same bytes, even for a decoder whose type doesn't + survive a round trip through its own encoding. A result with no JSON form fails the + Handle, as before, but now before any `Assign` runs. A service result in a Record an + older version wrote, of format 3 or lower, replays as that version replayed it: in JSON's + generic form, through no decoder, so a decoder added for its onDone event can't fail + `Recover` on it. +- **A service result that won't decode is parked.** `RunService` returns + `ErrEventDataEncoding`, not `ErrHandleFailed`, before any onDone or onError `Assign` + runs. The decode aborts the settle through `ServiceRunner.WithResultTransform`'s abort + return, so no event fires. The journal records the result as the service returned it, + with its Go type and import path, in a Record of its own that settles nothing. The + Handle stays healthy and the service stays in flight, but its `ServiceFn` never runs + again. The Handle that parked it never sees a fixed decoder: `Recover` with the fixed + decoder, then call `RunService`, and it settles the parked result, which the decoder + must return as the type the service returned, or in JSON's generic form, as live. + The type is matched by import path and name, so after the type is moved or renamed + only a decoder that returns the generic form settles it: settle parked results before + such a move. A + ctx that ended during the service parks nothing: `RunService` fails the Handle and + records nothing, as for a result that decodes, and the service runs again after + `Recover`. Until then each `RunService` returns + `ErrEventDataEncoding` and records nothing more. `Recover` and `StateAt` replay a + parked result as parked, so they don't fail on it, and `StateAt` at that step shows + the instance as it was before. A checkpoint carries the parked results in a new + `parkedServices` field of its envelope, so compacting the Record that parked one + doesn't lose it. A Fire or timer that leaves the state that declares the service stops + it and discards the parked result; entering the state again runs the `ServiceFn` for + the new activation. The Record that settles a parked result records its Go type too, and replay holds the decoder to it, + as that settle did: `Recover` and `StateAt` fail with `ErrEventDataEncoding`, running no `Assign`, when the decoder returns another type. The + type is the full name, with every named type's import path, also inside a struct + literal, func or chan type, whose fields' tags are part of it. Moving or renaming the + type after a park leaves the result parked under a decoder for its new name, and, once + settled, fails replay under one; a decoder that returns JSON's generic form for that + event settles or replays it. A parked Record or checkpoint is new to this version: an + older `durable` replays a parked Record as a settled result. - **A step that may not have been recorded fails the Handle.** That call and every later one return `ErrHandleFailed`, wrapping the cause. A step that was recorded while another goroutine failed the Handle also returns `ErrHandleFailed`, saying the step was @@ -196,33 +271,45 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. its service in flight and its actor running, and one that entered a state started no service and spawned no actor. A service left in flight could then settle after a checkpoint that no longer held it, journaling a settle replay couldn't apply, so every - `Recover` failed with "no in-flight service to settle". Now `Tick` hands every fired + `Recover` failed with "no in-flight service to settle"; and a parked result the timer + discarded made `RunService` run the `ServiceFn` again. Now `Tick` hands every fired transition's effects to the service runner, in fire order, and then to the actor system, as a `Fire` that produced them all does, live and on replay, so a parent Fire an actor spawned for one timer drives sees the services every timer of the tick started, and stops one it leaves rather than leave it in flight: a timer that leaves a - state stops its service and its actor, and one that enters a state starts its service - and spawns its actor. The tick's Record journals the parent Fires an actor it spawned - drove, replayed after its timers, and a parent Fire a context's ending refused fails - the Handle and records nothing, as for `Fire`. Only such a parent Fire fails it once - its timers have fired: a message to an actor that the actor refused because the + state stops its service, + discarding a parked result, and its actor, and one that enters a state starts its + service and spawns its actor. The tick's Record journals the parent Fires an actor it + spawned drove, replayed after its timers, and a parent Fire a context's ending refused + fails the Handle and records nothing, as for `Fire`. Only such a parent Fire fails it + once its timers have fired: a message to an actor that the actor refused because the tick's `ctx` ended is lost, as actor deliveries are across `Recover`, and the tick - records. Replay does this for a tick of journal - format 2 or later; an older version's tick replays as it ran, with its services left - in flight. This is the Tick-driver fix #236 tracked. The services and actors a timer - starts run under the tick's step context, as a `Fire`'s do, so an actor's behavior or - a parent Fire's middleware that calls back into the same Handle gets - `ErrReentrantStep` at once rather than deadlock on the step lock the `Tick` holds. -- **A checkpoint without `WithServiceRegistry` keeps the settled services.** A Handle - recovered without a service registry restored them from its checkpoint but wrote its - next checkpoint without them, so a later `Recover` with the registry found the service - not settled, and `RunService` ran its `ServiceFn` again. A checkpoint now keeps them - with or without a registry. `Recover` without a registry still refuses a journal tail - that holds a service's settle. + records. Replay does this for a tick of + journal format 2 or later; an older version's tick replays as it ran, with its + services left in flight. This is the Tick-driver fix #236 tracked. The services and + actors a timer starts run under the tick's step context, as a `Fire`'s do, so an + actor's behavior or a parent Fire's middleware that calls back into the same Handle + gets `ErrReentrantStep` at once rather than deadlock on the step lock the `Tick` holds. +- **A parked settle holds the decoder to the result's own type on the Handle that + parked it.** The live settle compares the decoder's type with the `ServiceFn`'s, but + the parked settle compared only their names, so a decoder that returned another type of + the same name and package, such as another function-local type, was refused live, and + its result parked, then accepted by the next `RunService` on the same Handle. That + `RunService` now refuses it too. After a `Recover` only the recorded name is left, so a + result of a function-local type is told from another of the same name only until then. +- **A checkpoint without `WithServiceRegistry` keeps the services' parked and settled + results.** A Handle recovered without a service registry restored them from its + checkpoint but wrote its next checkpoint without them, so a later `Recover` with the + registry found the service in flight with no parked result, or not settled, and + `RunService` ran its `ServiceFn` again. A checkpoint now keeps them with or without a + registry. `Recover` without a registry still refuses a journal tail that holds a + service's settle or park. - **`Recover` and `StateAt` fail when a Store loses `Record.Format`.** The Start baseline - and every checkpoint record the journal format too, and a Record after one with a lower - format fails replay, where it used to replay as an older journal's and silently skip - the timers and services an actor-driven Fire armed. + and every checkpoint record the journal format too, and a Record with a lower format + than the checkpoint or any Record before it fails replay, before any Record replays, where it used to replay as an older journal's and silently skip + the timers and services an actor-driven Fire armed. The error says the Store didn't + keep `Record.Format` for a Record with no format, and that an older version appended + it, a mixed-version deploy, for one with a lower format. - **A step that touches no actor doesn't recompute the actor sets.** Each append rebuilt the declared actors from every active state; it now reuses the last sets while the configuration, the running actors and the step's spawns are unchanged. diff --git a/durable/README.md b/durable/README.md index 0099ade1..70935bbe 100644 --- a/durable/README.md +++ b/durable/README.md @@ -181,10 +181,23 @@ owner holds the instance, so stop. `Recover` retries an unapplied effect, and re Events, 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 of actor done-data on a replayed `onDone`. A service's -result is JSON-decoded live as well as on replay, so a reducer gets the same value both -ways: a struct is a map and an integer a `float64`, which loses precision above 2^53, and -an error an error with the same message, which `errors.Is` and `errors.As` no longer -match. A +result is decoded from its JSON form live as well as on replay, so a reducer gets the same +value both ways. When `WithEventDataDecoder` covers the invocation's `onDone` event, the +result arrives as the decoder's type, for example `durable.DecodeAs[User]`. Otherwise it +arrives in JSON's generic form: a struct as a map and an integer as a `float64`, which +loses precision above 2^53. A decoder that fails, or that returns a type other than the +one the service returned, parks the result: `RunService` returns `ErrEventDataEncoding` +and no `onDone` or `onError` reducer runs, but the journal records the result as the +service returned it, and the Handle stays healthy. The service stays in flight and never +runs again. The decoder is part of the Runner's options, so the Handle that parked the +result never sees a fix: `Recover` with the fixed decoder, then call `RunService`, and it +settles the parked result. Until then `RunService` keeps returning +`ErrEventDataEncoding`. A checkpoint keeps a parked result, and a `Fire` or timer that +leaves the state that declares the service stops the service and discards it. A service error stays message-only, an error with the same message, which `errors.Is` no +longer matches. Register the decoder before you record results: replay decodes the journal +with the recovering Runner's decoder, so a decoder added or changed after results were +recorded changes what replay hands the reducer, and one that can't decode a settled result +fails `Recover` and `StateAt` with `ErrEventDataEncoding`; a parked one doesn't fail them. 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, chosen per event, for example `durable.DecodeAs[Order]`. Without one, a payload decodes as JSON's own diff --git a/durable/checkpoint.go b/durable/checkpoint.go index b85fa138..26ef9399 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -3,6 +3,7 @@ package durable import ( "encoding/json" "fmt" + "math" "sort" "time" @@ -60,6 +61,15 @@ type pendingTimerWire struct { Event json.RawMessage `json:"event,omitempty"` } +// parkedServiceWire is a parked service result as a checkpoint envelope carries it: the +// service id, the result's JSON and its Go type, as the parked journal entry records +// them. +type parkedServiceWire struct { + ID string `json:"id"` + Result json.RawMessage `json:"result"` + Type string `json:"type,omitempty"` +} + // checkpointEnvelope is the durable layer's wrapper around the bytes a Store keeps // for a checkpoint: the opaque state.Snapshot bytes, the pending-timer table armed at // the checkpoint instant, and the next step ordinal. The durable layer fully owns the checkpoint @@ -98,9 +108,17 @@ type checkpointEnvelope struct { // settled isn't one. None, as in a Start baseline or an older checkpoint, means // Recover starts every declared service. EndedServices []string `json:"endedServices,omitempty"` + // ParkedServices are the results parked at the checkpoint, by service id, sorted: + // each didn't decode for its onDone event, so its service is in flight and not + // settled, and a later RunService settles the recorded result rather than run the + // ServiceFn again. A checkpoint compacts the Record that parked it, so it carries + // them. None, as in a Start baseline or an older checkpoint, means none is parked. + ParkedServices []parkedServiceWire `json:"parkedServices,omitempty"` // Format is the journal format of the version that wrote the checkpoint, as // Record.Format is. Zero means a checkpoint from before this field. A Record after - // it with a lower Format means the Store lost the field, and replay fails. + // it with a lower Format means the Store lost the field, and replay fails. A Format + // above this version's journalFormat means a newer version wrote it, and every reader + // refuses the journal. Format int `json:"format,omitempty"` } @@ -141,17 +159,38 @@ func marshalCheckpoint(env checkpointEnvelope, timers map[string]pendingTimer) ( // tolerates a bare (pre-envelope) snapshot: bytes that are not a checkpoint envelope // are returned as the snapshot with no timers and a zero ordinal, so an older // checkpoint still restores. A checkpoint envelope is distinguished by carrying a -// non-empty "snapshot" member. +// non-empty "snapshot" member. Bytes this version's envelope can't unmarshal but whose +// "format" member is a number above journalFormat are a newer version's envelope, one +// that may have changed a field's type: they keep that Format, so checkNotNewer +// refuses them rather than restore them as a bare snapshot. A bare kernel snapshot has +// no "format" member. func unmarshalCheckpoint(b []byte) checkpointEnvelope { var env checkpointEnvelope if err := json.Unmarshal(b, &env); err != nil || len(env.Snapshot) == 0 { // Not an envelope (or an envelope without the wrapped snapshot member): treat - // the bytes as a bare kernel snapshot, the pre-timer-survival checkpoint form. - return checkpointEnvelope{Snapshot: b} + // the bytes as a bare kernel snapshot, the pre-timer-survival checkpoint form, + // unless they record a newer format. + return checkpointEnvelope{Snapshot: b, Format: newerFormatOf(b)} } return env } +// newerFormatOf returns the "format" member of b, a JSON object, when it is an integer +// above journalFormat, capped to fit an int on any platform, and zero otherwise. +func newerFormatOf(b []byte) int { + var probe struct { + Format json.Number `json:"format"` + } + if json.Unmarshal(b, &probe) != nil { + return 0 + } + f, err := probe.Format.Int64() + if err != nil || f <= journalFormat { + return 0 + } + return int(min(f, math.MaxInt32)) +} + // decodeTimerEvent decodes a persisted timer event wire back into the machine's // event type E through the same codec the Runner replays driving events with, so // the re-armed ScheduleAfter carries a correctly-typed event the scheduler accepts. diff --git a/durable/checkpoint_no_registry_test.go b/durable/checkpoint_no_registry_test.go index 3af0d8f1..a6881912 100644 --- a/durable/checkpoint_no_registry_test.go +++ b/durable/checkpoint_no_registry_test.go @@ -2,6 +2,8 @@ package durable_test import ( "context" + "errors" + "slices" "strings" "sync/atomic" "testing" @@ -11,14 +13,14 @@ import ( ) // noRegistryMachine invokes fn in "loading", which "begin" enters from "idle". Its -// onDone "done" stays in loading, through an Assign that counts it in done, so a -// settled service's state stays active; "poke" stays in loading too, leaving the -// service's activation alone. -func noRegistryMachine(fn state.ServiceFn[svcCtx], done *int) *state.Machine[string, string, svcCtx] { +// onDone "done" stays in loading, through an Assign that counts it, so a settled +// service's state stays active; "poke" stays in loading too, leaving the service's +// activation alone. +func noRegistryMachine(fn state.ServiceFn[svcCtx], a *scnAssigns) *state.Machine[string, string, svcCtx] { return state.ForgeFor[svcCtx]("noReg"). Service("fetch", fn). Reducer("noteDone", func(in state.AssignCtx[svcCtx]) svcCtx { - *done++ + a.done++ return in.Entity }). State("idle"). @@ -32,90 +34,111 @@ func noRegistryMachine(fn state.ServiceFn[svcCtx], done *int) *state.Machine[str var noRegistrySvc = state.InvokeID("noReg", "loading", 0) -// countingRuns returns a ServiceFn that counts its runs. -func countingRuns(runs *int64) state.ServiceFn[svcCtx] { - return func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { - return atomic.AddInt64(runs, 1), nil - } -} +// TestCheckpoint_WithoutARegistry_KeepsTheServices pins that a checkpoint a Handle +// recovered without WithServiceRegistry writes keeps the services the one before it +// held, parked or settled: a Handle with the registry parks loading's result, or +// settles it while loading stays active, and checkpoints; one recovered without the +// registry Fires a step that leaves the service alone, and checkpoints again; then one +// recovered with the registry calls RunService. It settles the parked result, or finds +// the service settled, and the ServiceFn doesn't run again. +func TestCheckpoint_WithoutARegistry_KeepsTheServices(t *testing.T) { + for _, tc := range []struct { + name string + park bool + }{{"parked", true}, {"settled", false}} { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + var runs int64 + a := &scnAssigns{} + fn := countingUsers(&runs) + m := noRegistryMachine(fn, a) + var refuse atomic.Bool + refuse.Store(tc.park) + bare := []durable.Option[string, string, svcCtx]{ + durable.WithCheckpointEvery[string, string, svcCtx](1), + decoderFor("done", func(data []byte) (any, error) { + if refuse.Load() { + return nil, errors.New("decoder refused") + } + return durable.DecodeAs[scnUser](data) + }), + } + withRegistry := append(slices.Clone(bare), durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))) + store, id := durable.NewMemStore(), durable.InstanceID("no-reg") -// TestCheckpoint_WithoutARegistry_KeepsTheSettledServices pins that a checkpoint a -// Handle recovered without WithServiceRegistry writes keeps the settled services the one -// before it held: a Handle with the registry settles loading's service while loading -// stays active, and checkpoints; one recovered without the registry Fires a step that -// leaves the service alone, and checkpoints again; then one recovered with the registry -// finds the service settled, and the ServiceFn doesn't run again. -func TestCheckpoint_WithoutARegistry_KeepsTheSettledServices(t *testing.T) { - ctx := context.Background() - var runs int64 - done := 0 - fn := countingRuns(&runs) - m := noRegistryMachine(fn, &done) - bare := []durable.Option[string, string, svcCtx]{durable.WithCheckpointEvery[string, string, svcCtx](1)} - withRegistry := append(append([]durable.Option[string, string, svcCtx]{}, bare...), durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))) - store, id := durable.NewMemStore(), durable.InstanceID("no-reg") - - h, err := durable.NewRunner(m, store, withRegistry...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatalf("Start: %v", err) - } - if _, err = h.Fire(ctx, "begin"); err != nil { - t.Fatalf("Fire(begin): %v", err) - } - if _, ran, rerr := h.RunService(ctx, noRegistrySvc); !ran || rerr != nil { - t.Fatalf("RunService = %v, %v; want it settled", ran, rerr) - } + h, err := durable.NewRunner(m, store, withRegistry...).Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "begin"); err != nil { + t.Fatalf("Fire(begin): %v", err) + } + _, ran, err := h.RunService(ctx, noRegistrySvc) + if tc.park { + mustPark(t, "RunService", ran, err) + } else if !ran || err != nil { + t.Fatalf("RunService = %v, %v; want it settled", ran, err) + } - nh, err := durable.Recover(ctx, m, store, id, bare...) - if err != nil { - t.Fatalf("Recover without the registry: %v", err) - } - if _, err = nh.Fire(ctx, "poke"); err != nil { - t.Fatalf("Fire(poke) without the registry: %v", err) - } + nh, err := durable.Recover(ctx, m, store, id, bare...) + if err != nil { + t.Fatalf("Recover without the registry: %v", err) + } + if _, err = nh.Fire(ctx, "poke"); err != nil { + t.Fatalf("Fire(poke) without the registry: %v", err) + } - rh, err := durable.Recover(ctx, m, store, id, withRegistry...) - if err != nil { - t.Fatalf("Recover with the registry: %v", err) - } - _, ran, err := rh.RunService(ctx, noRegistrySvc) - if err != nil { - t.Fatalf("RunService after the registry-less checkpoint: %v", err) - } - if got := atomic.LoadInt64(&runs); got != 1 { - t.Fatalf("the ServiceFn ran %d times, want once: the registry-less checkpoint dropped the settled service", got) - } - if ran { - t.Fatal("RunService ran = true, want nothing in flight for a settled service") - } - if done != 1 { - t.Fatalf("onDone ran %d times, want once", done) + refuse.Store(false) + rh, err := durable.Recover(ctx, m, store, id, withRegistry...) + if err != nil { + t.Fatalf("Recover with the registry: %v", err) + } + _, ran, err = rh.RunService(ctx, noRegistrySvc) + if err != nil { + t.Fatalf("RunService after the registry-less checkpoint: %v", err) + } + if got := atomic.LoadInt64(&runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want once: the registry-less checkpoint dropped the %s service", got, tc.name) + } + // A parked result settles now; a settled service has nothing in flight. + if ran != tc.park { + t.Fatalf("RunService ran = %v, want %v", ran, tc.park) + } + if a.done != 1 { + t.Fatalf("onDone ran %d times, want once", a.done) + } + }) } } // TestRecover_WithoutARegistry_RefusesAJournaledServiceRecord pins that Recover without -// WithServiceRegistry refuses a tail holding a service's settle, rather than replay it -// with no service runner: only a checkpoint that compacted that Record recovers without -// the registry. +// WithServiceRegistry refuses a tail holding a service's settle or park, rather than +// replay it with no service runner: only a checkpoint that compacted those Records +// recovers without the registry. func TestRecover_WithoutARegistry_RefusesAJournaledServiceRecord(t *testing.T) { - ctx := context.Background() - var runs int64 - done := 0 - fn := countingRuns(&runs) - m := noRegistryMachine(fn, &done) - store, id := durable.NewMemStore(), durable.InstanceID("no-reg-tail") - h, err := durable.NewRunner(m, store, durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))). - Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatalf("Start: %v", err) - } - if _, err = h.Fire(ctx, "begin"); err != nil { - t.Fatalf("Fire(begin): %v", err) - } - if _, ran, rerr := h.RunService(ctx, noRegistrySvc); !ran || rerr != nil { - t.Fatalf("RunService = %v, %v; want it settled", ran, rerr) - } - if _, err = durable.Recover(ctx, m, store, id); err == nil || !strings.Contains(err.Error(), "requires a service registry") { - t.Fatalf("Recover without the registry = %v, want it refused for want of a registry", err) + for _, park := range []bool{true, false} { + ctx := context.Background() + var runs int64 + fn := countingUsers(&runs) + m := noRegistryMachine(fn, &scnAssigns{}) + dec := decoderFor("done", func(data []byte) (any, error) { + if park { + return nil, errors.New("decoder refused") + } + return durable.DecodeAs[scnUser](data) + }) + store, id := durable.NewMemStore(), durable.InstanceID("no-reg-tail") + h, err := durable.NewRunner(m, store, dec, durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))). + Start(ctx, id, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "begin"); err != nil { + t.Fatalf("Fire(begin): %v", err) + } + _, _, _ = h.RunService(ctx, noRegistrySvc) + if _, err = durable.Recover(ctx, m, store, id, dec); err == nil || !strings.Contains(err.Error(), "requires a service registry") { + t.Fatalf("Recover without the registry (park %v) = %v, want it refused for want of a registry", park, err) + } } } diff --git a/durable/doc.go b/durable/doc.go index ea322b0a..ad935121 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -41,6 +41,25 @@ // well as on replay, so a reducer gets the same value both ways; WithEventDataDecoder // decodes it as the type the caller passed. // +// A service result is decoded the same way, live and on replay. When +// WithEventDataDecoder covers the invocation's onDone event, the result arrives as the +// decoder's type; otherwise it arrives in JSON's generic form, a struct as a +// map[string]any and a number as a float64. A decoder that fails, or returns a type +// other than the service's result, parks the result: RunService returns +// ErrEventDataEncoding and no onDone or onError reducer runs, but the result is +// recorded and the Handle stays healthy, so the service never runs again. The decoder +// is part of the Runner's options, so the Handle that parked the result never sees a +// fix: Recover with the fixed decoder, then call RunService, and it settles the parked +// result. The decoder must return the type the service returned, by import path and +// name, or JSON's generic form, so settle parked results before moving or renaming that +// type; after a move, only a decoder that returns the generic form settles them. +// A Fire or timer that leaves the state that declares the service stops it and +// discards the parked result. A service error stays message-only. Register the decoder before recording results: replay decodes the +// journal with the recovering Runner's decoder, held to the Go type the service +// returned, which every settle records, so a decoder changed after results were +// recorded to return another type fails Recover, unless it returns JSON's generic form, +// and one added later for the service's type changes what replay produces. +// // 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 diff --git a/durable/effect_marshal_panic_test.go b/durable/effect_marshal_panic_test.go deleted file mode 100644 index 4e16175b..00000000 --- a/durable/effect_marshal_panic_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package durable_test - -import ( - "context" - "errors" - "fmt" - "strings" - "testing" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// These tests pin a KindedEffect whose MarshalJSON panics: it is recorded by id and -// kind, as one whose marshal fails, rather than panicking out of a step the kernel -// applied. A Kind that panics still fails the Handle. - -// panicky is a KindedEffect whose MarshalJSON panics. -type panicky struct{} - -func (panicky) Kind() string { return "demo.panicky" } -func (panicky) MarshalJSON() ([]byte, error) { panic("marshal blew up") } - -// panickyKind is a KindedEffect whose Kind panics. -type panickyKind struct{} - -func (panickyKind) Kind() string { panic("kind blew up") } - -func emitting(eff state.Effect) func(state.ActionCtx[svcCtx]) (state.Effect, error) { - return func(state.ActionCtx[svcCtx]) (state.Effect, error) { return eff, nil } -} - -func panickyMachine(eff state.Effect) *state.Machine[string, string, svcCtx] { - return state.ForgeFor[svcCtx]("pnk"). - Action("emit", emitting(eff)). - State("idle"). - State("done").Final(). - Initial("idle"). - Transition("idle").On("go").GoTo("done").Do("emit"). - Quench() -} - -// fireCatching fires event on h and returns the panic that escaped, or the error. -func fireCatching(h *durable.Handle[string, string, svcCtx], event string) (panicked any, err error) { - defer func() { panicked = recover() }() - _, err = h.Fire(context.Background(), event) - return nil, err -} - -// A KindedEffect whose MarshalJSON panics is recorded as one whose marshal fails: by id -// and kind, with the panic's message in Meta under crucible.marshalError. The step -// doesn't panic or fail, and Recover replays it. -func TestUnmarshalableEffect_PanickingMarshal_RecordsByIDAndKind(t *testing.T) { - ctx := context.Background() - m := panickyMachine(panicky{}) - store := durable.NewMemStore() - h, err := durable.NewRunner(m, store).Start(ctx, "pnk-1", svcCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatalf("Start: %v", err) - } - p, ferr := fireCatching(h, "go") - if p != nil || ferr != nil { - t.Fatalf("Fire = %v, panic %v; want neither", ferr, p) - } - _, recs, err := store.Load(ctx, "pnk-1") - if err != nil || len(recs) != 1 || len(recs[0].Effects) != 1 { - t.Fatalf("Load = %d Records (err %v), want one with one effect", len(recs), err) - } - env := recs[0].Effects[0] - if env.Kind != "demo.panicky" || env.EffectID != "0#0#demo.panicky" || len(env.Payload) != 0 { - t.Fatalf("recorded %+v, want kind demo.panicky, id 0#0#demo.panicky and no payload", env) - } - if msg, _ := env.Meta[metaMarshalError].(string); !strings.Contains(msg, "marshal blew up") { - t.Fatalf("Meta = %v, want the panic's message under %q", env.Meta, metaMarshalError) - } - rh, err := durable.Recover(ctx, m, store, "pnk-1") - if err != nil { - t.Fatalf("Recover: %v", err) - } - if got := rh.Instance().Current(); got != "done" { - t.Fatalf("recovered in %q, want done", got) - } -} - -// Pins current behavior: a KindedEffect whose Kind panics has no kind to record it by, -// so it can't take the id-and-kind fallback. The panic leaves the Fire, and the Handle -// is failed first, as for any panic in host code during a step, so the caller can -// Recover. The kernel applied the transition, but nothing was journaled. -func TestUnmarshalableEffect_PanickingKind_FailsTheHandle(t *testing.T) { - ctx := context.Background() - m := panickyMachine(panickyKind{}) - store := durable.NewMemStore() - h, err := durable.NewRunner(m, store).Start(ctx, "pnk-1", svcCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatalf("Start: %v", err) - } - if p, _ := fireCatching(h, "go"); p == nil || !strings.Contains(fmt.Sprint(p), "kind blew up") { - t.Fatalf("Fire panicked with %v, want the Kind panic", p) - } - if _, err := h.Fire(ctx, "go"); !errors.Is(err, durable.ErrHandleFailed) { - t.Fatalf("Fire after the panic = %v, want ErrHandleFailed", err) - } - if got := tailLen(t, store, "pnk-1"); got != 0 { - t.Fatalf("the journal holds %d Records, want none", got) - } -} diff --git a/durable/errors.go b/durable/errors.go index 3d28140b..3b12e93c 100644 --- a/durable/errors.go +++ b/durable/errors.go @@ -47,7 +47,11 @@ var ( // 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. + // Nothing applied, so the Handle stays usable. RunService returns it, with the Handle + // healthy, for a service result that won't decode for its onDone event, or decodes as + // another type than the service returned: the result is parked, and a RunService + // once the decoder decodes it settles it. Recover and StateAt return it for a settled + // result that won't decode. No onDone or onError Assign runs for that result. ErrEventDataEncoding = errors.New(errorPrefix + errorEventDataEncoding) // ErrRecordTooLarge is reported by FileStore.Append for a Record whose journal line diff --git a/durable/internal/typefixture/alpha/model/model.go b/durable/internal/typefixture/alpha/model/model.go new file mode 100644 index 00000000..b33c3fd4 --- /dev/null +++ b/durable/internal/typefixture/alpha/model/model.go @@ -0,0 +1,9 @@ +// Package model is a test fixture: it and the model package under beta each define a +// Result, so a test can tell two types apart that share the short name model.Result. +package model + +// Result is alpha's model.Result. +type Result struct { + ID int64 + Name string +} diff --git a/durable/internal/typefixture/beta/model/model.go b/durable/internal/typefixture/beta/model/model.go new file mode 100644 index 00000000..835600ec --- /dev/null +++ b/durable/internal/typefixture/beta/model/model.go @@ -0,0 +1,10 @@ +// Package model is a test fixture: it and the model package under alpha each define a +// Result, so a test can tell two types apart that share the short name model.Result. +package model + +// Result is beta's model.Result. Its JSON is alpha's, so a decoder for it decodes an +// alpha Result's JSON without error. +type Result struct { + ID int64 + Name string +} diff --git a/durable/journal_format_internal_test.go b/durable/journal_format_internal_test.go new file mode 100644 index 00000000..f94f2069 --- /dev/null +++ b/durable/journal_format_internal_test.go @@ -0,0 +1,79 @@ +package durable + +import ( + "encoding/json" + "testing" +) + +// TestCheckFormat_RefusesAHigherFormat pins what a downgrade meets. checkFormat fails +// on a Record of a lower format than its checkpoint's, a Store that lost the field, and +// accepts a higher one, as every version since Record.Format has. checkFormats holds +// each Record to the highest format before it, the checkpoint's or a Record's, so an +// older version's Record is refused anywhere in the tail. checkNotNewer, which +// every reader calls first, refuses a checkpoint or a Record of a format above +// journalFormat, one a newer version wrote, so each later bump of journalFormat makes +// this version refuse that version's journal. A binary built before checkNotNewer +// replays a newer journal as its own format. +func TestCheckFormat_RefusesAHigherFormat(t *testing.T) { + if err := checkFormat(1, &Record{Format: 2}); err != nil { + t.Errorf("checkFormat(1, a Record of format 2) = %v, want nil", err) + } + if err := checkFormat(2, &Record{Format: 1}); err == nil { + t.Errorf("checkFormat(2, a Record of format 1) = nil, want the older-version error") + } + for _, tc := range []struct { + checkpoint int + recs []Record + refused bool + }{ + {0, []Record{{Format: 0}, {Format: 1}, {Format: 1}, {Format: 2}}, false}, + {1, []Record{{Format: 1}, {Format: 2}, {Format: 2}}, false}, + {1, []Record{{Format: 2}, {Format: 1}}, true}, + {0, []Record{{Format: 1}, {Format: 0}}, true}, + {2, []Record{{Format: 1}}, true}, + } { + err := checkFormats(tc.checkpoint, tc.recs) + if (err != nil) != tc.refused { + t.Errorf("checkFormats(%d, %+v) = %v, want refused %v", tc.checkpoint, tc.recs, err, tc.refused) + } + } + for _, tc := range []struct { + checkpoint int + recs []Record + refused bool + }{ + {0, nil, false}, + {journalFormat, nil, false}, + {0, []Record{{Format: 0}, {Format: 1}, {Format: journalFormat}}, false}, + {journalFormat + 1, nil, true}, + {journalFormat, []Record{{Format: journalFormat}, {Format: journalFormat + 1}}, true}, + {0, []Record{{Format: journalFormat + 5}}, true}, + } { + err := checkNotNewer("x", tc.checkpoint, tc.recs) + if (err != nil) != tc.refused { + t.Errorf("checkNotNewer(%d, %+v) = %v, want refused %v", tc.checkpoint, tc.recs, err, tc.refused) + } + } +} + +// TestParkedEntry_AnOlderReaderSettlesIt pins what a version from before parking reads +// in a parked entry: its serviceResultPayload has only Result and Error, so the entry +// decodes as a result that settled, and its replay would settle the parked result +// through onDone, running the Assign the park held back. The CHANGELOG says not to +// downgrade a Store this version has written to; this is one reason. +func TestParkedEntry_AnOlderReaderSettlesIt(t *testing.T) { + payload, err := json.Marshal(serviceResultPayload{Result: json.RawMessage(`{"ID":7}`), Parked: true, Type: "x.T"}) + if err != nil { + t.Fatal(err) + } + var older struct { + Result json.RawMessage `json:"result,omitempty"` + Error *string `json:"error,omitempty"` + } + if err := json.Unmarshal(payload, &older); err != nil { + t.Fatalf("an older reader fails on a parked entry: %v", err) + } + if older.Error != nil || string(older.Result) != `{"ID":7}` { + t.Fatalf("an older reader reads %+v, want a settled result", older) + } +} diff --git a/durable/journal_format_midtail_test.go b/durable/journal_format_midtail_test.go new file mode 100644 index 00000000..eaaa3652 --- /dev/null +++ b/durable/journal_format_midtail_test.go @@ -0,0 +1,118 @@ +package durable_test + +import ( + "context" + "strings" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests answer a review finding on the journal format check: it compared each +// Record's format only with the checkpoint's, so an older version's Record appended +// after this version's Records, past an older checkpoint, replayed by its own format's +// rules. A journal's format never goes down, so a Record below any format before it, +// the checkpoint's or an earlier Record's, means mixed versions wrote it, and Recover +// and StateAt refuse it before replaying anything. + +// TestRecover_OlderRecordMidTailIsRefused: a format-1 checkpoint, then this version's +// format-4 Record that parks a result, then an older replica's format-1 Fire. The older +// replica reads the park as a settle (see TestRecover_OlderVersionAfterAParkIsRefused), +// so the two versions disagree about the journal, and Recover must refuse it, naming +// the older version, as it does when the checkpoint itself is newer. +func TestRecover_OlderRecordMidTailIsRefused(t *testing.T) { + ctx := context.Background() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return scnUser{ID: 7, Name: "ann"}, nil } + m := forkMachine(fn) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + st := durable.NewMemStore() + // An older version, of format 1, started the instance and wrote its checkpoint. + older := &olderWriter{MemStore: st, format: 1} + if _, err := durable.NewRunner(m, older, reg, failingDecoder()).Start(ctx, "o1", svcCtx{}, state.WithInitialState("loading")); err != nil { + t.Fatalf("Start: %v", err) + } + // This version recovers it and parks the result, in a format-4 Record. + h, err := durable.Recover(ctx, m, st, "o1", reg, failingDecoder()) + if err != nil { + t.Fatalf("Recover the older checkpoint: %v", err) + } + _, ran, err := h.RunService(ctx, state.InvokeID("fork", "loading", 0)) + mustPark(t, "RunService", ran, err) + _, recs, err := st.Load(ctx, "o1") + if err != nil || len(recs) != 1 || recs[0].Format != 4 { + t.Fatalf("the journal holds %+v (err %v), want the park's one format-4 Record", recs, err) + } + // The older replica fires "next" after it, in its format. + if _, err = st.Append(ctx, "o1", durable.Record{Step: recs[0].Step + 1, Event: []byte(`"next"`), Format: 1}); err != nil { + t.Fatalf("Append: %v", err) + } + + rh, err := durable.Recover(ctx, m, st, "o1", reg, failingDecoder()) + if err == nil { + t.Fatalf("Recover replayed a format-1 Record after a format-4 one, into %q", rh.Instance().Current()) + } + if msg := err.Error(); !strings.Contains(msg, "older version") || !strings.Contains(msg, "don't run mixed versions") { + t.Fatalf("Recover: %v, want the mixed-version error", err) + } + if _, err = durable.StateAt(ctx, m, st, "o1", recs[0].Step+1, reg, failingDecoder()); err == nil || !strings.Contains(err.Error(), "older version") { + t.Fatalf("StateAt: %v, want the mixed-version error", err) + } +} + +// TestRecover_RefusesAMixedJournalBeforeReplaying: Recover checks every Record's format +// before it replays any, so a journal it refuses sends no effect. This version's Fire +// records an effect no handler sent, and an older replica appends after it; the effect +// would be sent if Recover only refused on reaching the older Record. +func TestRecover_RefusesAMixedJournalBeforeReplaying(t *testing.T) { + ctx := context.Background() + st := durable.NewMemStore() + h, err := durable.NewRunner(effectMachine(), st).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + // No handler: step 0's effect is recorded and not sent. + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire go: %v", err) + } + if _, err = durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: 1}).Fire(ctx, "i1", "bill"); err != nil { + t.Fatalf("the older replica's Fire: %v", err) + } + rec := newEffectRecorder() + _, err = durable.Recover(ctx, effectMachine(), st, "i1", durable.WithEffectHandler[string, string, *runCtx](rec.handler())) + if err == nil || !strings.Contains(err.Error(), "older version") { + t.Fatalf("Recover: %v, want the mixed-version error", err) + } + if n := rec.totalApplies(); n != 0 { + t.Fatalf("Recover sent %v before refusing the journal, want nothing sent", rec.ids()) + } +} + +// TestRecover_NonDecreasingFormatsLoad: a journal whose formats never go down loads, +// whatever they are: an older version's checkpoint and Records, then this version's. +func TestRecover_NonDecreasingFormatsLoad(t *testing.T) { + ctx := context.Background() + for _, formats := range [][]int{{0, 0, 2}, {0, 1, 2}, {1, 1, 1}, {1, 2, 2}, {0, 2, 2}} { + st := durable.NewMemStore() + r := durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: formats[0]}) + if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("%v: Start: %v", formats, err) + } + if _, err := durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: formats[1]}).Fire(ctx, "i1", "go"); err != nil { + t.Fatalf("%v: Fire go: %v", formats, err) + } + if _, err := durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: formats[2]}).Fire(ctx, "i1", "bill"); err != nil { + t.Fatalf("%v: Fire bill: %v", formats, err) + } + rh, err := durable.Recover(ctx, effectMachine(), st, "i1") + if err != nil { + t.Fatalf("%v: Recover: %v", formats, err) + } + if got := rh.Instance().Current(); got != "billed" { + t.Fatalf("%v: recovered in %q, want billed", formats, got) + } + if _, err = durable.StateAt(ctx, effectMachine(), st, "i1", 1); err != nil { + t.Fatalf("%v: StateAt: %v", formats, err) + } + } +} diff --git a/durable/journal_format_mixed_test.go b/durable/journal_format_mixed_test.go new file mode 100644 index 00000000..1abc32e9 --- /dev/null +++ b/durable/journal_format_mixed_test.go @@ -0,0 +1,104 @@ +package durable_test + +import ( + "context" + "strings" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests answer a review finding on a rolling deploy that runs two versions on one +// instance: an older replica appends a Record of its own, lower journal format after +// this version's checkpoint. Recover must refuse the journal, and say that mixed +// versions wrote it rather than blame the Store. + +// TestRecover_OlderVersionAppendedAfterThisVersionsCheckpoint: this version's Start +// writes a baseline in its own format, and an older replica, which stamps format 1, appends the +// next step. Recover refuses, naming the older version, not a Store that lost +// Record.Format. +func TestRecover_OlderVersionAppendedAfterThisVersionsCheckpoint(t *testing.T) { + ctx := context.Background() + st := durable.NewMemStore() + if _, err := durable.NewRunner(effectMachine(), st).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + // The older replica: a Runner of this version, whose Store stamps format 1 on every + // Record it appends, as that version's Runner did. + if _, err := durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: 1}).Fire(ctx, "i1", "go"); err != nil { + t.Fatalf("the older replica's Fire: %v", err) + } + _, err := durable.Recover(ctx, effectMachine(), st, "i1") + if err == nil { + t.Fatal("Recover replayed a format-1 Record after a checkpoint of this version's format") + } + if msg := err.Error(); !strings.Contains(msg, "older version") || strings.Contains(msg, "didn't keep Record.Format") { + t.Fatalf("Recover: %v, want it to say an older version appended to this version's journal, not blame the Store", err) + } +} + +// TestRecover_FormatlessRecordAfterThisVersionsCheckpoint keeps the diagnosis for a +// Record with no format at all, which a Store that drops the field gives, as does a +// version from before the field: Recover refuses and names both. +func TestRecover_FormatlessRecordAfterThisVersionsCheckpoint(t *testing.T) { + ctx := context.Background() + st := durable.NewMemStore() + if _, err := durable.NewRunner(effectMachine(), st).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { + t.Fatalf("Start: %v", err) + } + if _, err := durable.NewRunner(effectMachine(), formatDroppingStore{st}).Fire(ctx, "i1", "go"); err != nil { + t.Fatalf("Fire: %v", err) + } + _, err := durable.Recover(ctx, effectMachine(), st, "i1") + if err == nil || !strings.Contains(err.Error(), "didn't keep Record.Format") { + t.Fatalf("Recover: %v, want it to say the Store may not have kept Record.Format", err) + } +} + +// forkMachine invokes fetch in loading. "next" is declared in loading and in ready, +// with different targets, so a journal replayed from the wrong state still replays, +// to the wrong place. +func forkMachine(fn state.ServiceFn[svcCtx]) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("fork"). + Service("fetch", fn). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready"). + State("canceled").Final(). + State("shipped").Final(). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready"). + Transition("loading").On("fail").GoTo("failed"). + Transition("loading").On("next").GoTo("canceled"). + Transition("ready").On("next").GoTo("shipped"). + Quench() +} + +// TestRecover_OlderVersionAfterAParkIsRefused shows why Recover can't replay an older +// replica's Record by its own format's rules. This version parks a result; the older +// replica, which has no parking, reads the parked entry as a settle, so it moves to +// ready, and its "next" ships the order. Replayed here, the park leaves the instance in +// loading, where "next" cancels it: the two versions disagree about what the journal +// means, so Recover must refuse rather than recover canceled. +func TestRecover_OlderVersionAfterAParkIsRefused(t *testing.T) { + ctx := context.Background() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return scnUser{ID: 7, Name: "ann"}, nil } + m := forkMachine(fn) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + st := durable.NewMemStore() + h, err := durable.NewRunner(m, st, reg, failingDecoder()).Start(ctx, "o1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + _, ran, err := h.RunService(ctx, state.InvokeID("fork", "loading", 0)) + mustPark(t, "RunService", ran, err) + // The older replica's step: the "next" it fired from ready, in its format. + if _, err = st.Append(ctx, "o1", durable.Record{Step: 1, Event: []byte(`"next"`), Format: 1}); err != nil { + t.Fatalf("Append: %v", err) + } + rh, err := durable.Recover(ctx, m, st, "o1", reg, failingDecoder()) + if err == nil { + t.Fatalf("Recover replayed the older replica's step into %q; the older replica left the order shipped", rh.Instance().Current()) + } +} diff --git a/durable/journal_format_newer_test.go b/durable/journal_format_newer_test.go new file mode 100644 index 00000000..d5e5b354 --- /dev/null +++ b/durable/journal_format_newer_test.go @@ -0,0 +1,235 @@ +package durable_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strconv" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// newerFormat is a journal format above this version's, as a later version would write. +const newerFormat = 9 + +// newerWriter stamps every Record it keeps with older's format, and the checkpoint too +// when checkpoint is set, as the version that wrote that format would. +type newerWriter struct { + older *olderWriter + checkpoint bool + *durable.MemStore +} + +func (s *newerWriter) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { + return s.older.Append(ctx, id, rec, opts...) +} + +func (s *newerWriter) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { + if s.checkpoint { + return s.older.Checkpoint(ctx, id, snapshot, throughStep, opts...) + } + return s.MemStore.Checkpoint(ctx, id, snapshot, throughStep, opts...) +} + +func newWriter(format int, checkpoint bool) *newerWriter { + mem := durable.NewMemStore(durable.WithHistory()) + return &newerWriter{older: &olderWriter{MemStore: mem, format: format}, checkpoint: checkpoint, MemStore: mem} +} + +// journalCase is a journal some version wrote: a Start baseline, and, when step is set, +// one service settlement after it. +type journalCase struct { + name string + checkpoint bool // the baseline records format, not this version's + step bool // the journal holds a Record, of format +} + +// newerCases are the journals a newer version could leave: a newer Record after this +// version's baseline, a newer baseline with an empty tail, and both. +var newerCases = []journalCase{ + {"newer Record", false, true}, + {"newer checkpoint, empty tail", true, false}, + {"newer checkpoint and Record", true, true}, +} + +// writeJournal starts scn-1 on a store that writes format as c says, and settles its +// service once when c.step is set. +func writeJournal(t *testing.T, c journalCase, format int, a *scnAssigns) (*state.Machine[string, string, svcCtx], *newerWriter, durable.Option[string, string, svcCtx]) { + t.Helper() + fn := returning(scnUser{ID: 7, Name: "ann"}, nil) + m := scnMachine(fn, a) + store := newWriter(format, c.checkpoint) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + h := scnStart(t, m, store, reg) + if c.step { + mustRunService(t, h, state.InvokeID(scnInvoke, "loading", 0)) + } + return m, store, reg +} + +// mustBeNewer fails unless err is the refusal of a journal of newerFormat, which names +// the instance and both formats and wraps none of the package's sentinels. +func mustBeNewer(t *testing.T, what string, err error) { + t.Helper() + want := fmt.Sprintf("durable: %q was written by a newer version (journal format %d; this version reads up to 4)", "scn-1", newerFormat) + if err == nil || err.Error() != want { + t.Fatalf("%s = %v, want %q", what, err, want) + } + for _, sentinel := range []error{ + durable.ErrInstanceNotFound, durable.ErrStepOutOfOrder, durable.ErrStepConflict, + durable.ErrFenced, durable.ErrCheckpointNotAdvancing, durable.ErrInstanceExists, + durable.ErrEffectDispatch, durable.ErrStepOutOfRange, durable.ErrEventDataEncoding, + durable.ErrRecordTooLarge, durable.ErrHandleFailed, durable.ErrReentrantStep, + durable.ErrNoDispatchStore, + } { + if errors.Is(err, sentinel) { + t.Fatalf("%s's refusal matches %v, want no sentinel", what, sentinel) + } + } +} + +// A version refuses a journal a newer version wrote, a checkpoint or a Record of a +// format above its own, rather than replay it as its own format. Recover refuses it +// before it restores or replays anything, so no Assign runs again. +func TestJournalFormat_NewerJournal_RecoverRefuses(t *testing.T) { + for _, c := range newerCases { + t.Run(c.name, func(t *testing.T) { + a := &scnAssigns{} + m, store, reg := writeJournal(t, c, newerFormat, a) + live := a.done + _, err := durable.Recover(context.Background(), m, store, "scn-1", reg) + mustBeNewer(t, "Recover", err) + if a.done != live { + t.Fatalf("onDone's Assign ran %d times, want only live's %d", a.done, live) + } + }) + } +} + +// The stateless Runner.Fire loads the instance as Recover does, so it refuses a newer +// journal too, and appends nothing to it. +func TestJournalFormat_NewerJournal_StatelessFireRefuses(t *testing.T) { + for _, c := range newerCases { + t.Run(c.name, func(t *testing.T) { + m, store, reg := writeJournal(t, c, newerFormat, &scnAssigns{}) + ctx := context.Background() + _, before, err := store.Load(ctx, "scn-1") + if err != nil { + t.Fatal(err) + } + _, err = durable.NewRunner(m, store, reg).Fire(ctx, "scn-1", "done") + mustBeNewer(t, "Runner.Fire", err) + _, after, err := store.Load(ctx, "scn-1") + if err != nil || len(after) != len(before) { + t.Fatalf("the journal holds %d Records (err %v) after the refused Fire, want %d", len(after), err, len(before)) + } + }) + } +} + +// StateAt refuses a newer journal whatever the step, even the baseline, which a newer +// Record after it doesn't reach. +func TestJournalFormat_NewerJournal_StateAtRefuses(t *testing.T) { + for _, c := range newerCases { + t.Run(c.name, func(t *testing.T) { + m, store, reg := writeJournal(t, c, newerFormat, &scnAssigns{}) + steps := []int{durable.BaselineStep} + if c.step { + steps = append(steps, 0) + } + for _, step := range steps { + _, err := durable.StateAt(context.Background(), m, store, "scn-1", step, reg) + mustBeNewer(t, fmt.Sprintf("StateAt(%d)", step), err) + } + }) + } +} + +// Steps refuses a newer journal, as StateAt does. +func TestJournalFormat_NewerJournal_StepsRefuses(t *testing.T) { + for _, c := range newerCases { + t.Run(c.name, func(t *testing.T) { + _, store, _ := writeJournal(t, c, newerFormat, &scnAssigns{}) + _, err := durable.Steps(context.Background(), store, "scn-1") + mustBeNewer(t, "Steps", err) + }) + } +} + +// The ceiling refuses only a newer format: a journal of format 0 (the 0.1.0 release), 1 +// or 2, this version's, still loads on every read path, with a checkpoint and an empty +// tail or a Record after it. +func TestJournalFormat_OlderAndCurrentJournal_Loads(t *testing.T) { + for _, format := range []int{0, 1, 2} { + for _, c := range []journalCase{ + {"checkpoint, empty tail", true, false}, + {"checkpoint and Record", true, true}, + } { + t.Run(fmt.Sprintf("format %d, %s", format, c.name), func(t *testing.T) { + ctx := context.Background() + m, store, reg := writeJournal(t, c, format, &scnAssigns{}) + if _, err := durable.Recover(ctx, m, store, "scn-1", reg); err != nil { + t.Fatalf("Recover: %v", err) + } + if _, err := durable.StateAt(ctx, m, store, "scn-1", durable.BaselineStep, reg); err != nil { + t.Fatalf("StateAt: %v", err) + } + if _, err := durable.Steps(ctx, store, "scn-1"); err != nil { + t.Fatalf("Steps: %v", err) + } + if !c.step { // the instance is still loading, so its onDone event fires + if _, err := durable.NewRunner(m, store, reg).Fire(ctx, "scn-1", "done"); err != nil { + t.Fatalf("Runner.Fire: %v", err) + } + } + }) + } + } +} + +// reshapedWriter writes every checkpoint as a later version might: format newerFormat, +// with nextStep changed from a number to a string, so this version's envelope type +// can't unmarshal it. +type reshapedWriter struct { + *durable.MemStore +} + +func (s *reshapedWriter) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { + var env map[string]json.RawMessage + if err := json.Unmarshal(snapshot, &env); err != nil { + return err + } + env["format"] = json.RawMessage(strconv.Itoa(newerFormat)) + env["nextStep"] = json.RawMessage(`"x"`) + b, err := json.Marshal(env) + if err != nil { + return err + } + return s.MemStore.Checkpoint(ctx, id, b, throughStep, opts...) +} + +// TestJournalFormat_NewerEnvelopeOfAnotherShape_IsRefused: a later version may change +// the type of an envelope field, so this version's envelope type can't unmarshal its +// checkpoint. Every reader must still read the checkpoint's format and refuse it as a +// newer version's, rather than take the bytes for a bare pre-envelope snapshot of +// format 0 and fail later with an obscure error. +func TestJournalFormat_NewerEnvelopeOfAnotherShape_IsRefused(t *testing.T) { + ctx := context.Background() + fn := returning(scnUser{ID: 7, Name: "ann"}, nil) + m := scnMachine(fn, &scnAssigns{}) + store := &reshapedWriter{MemStore: durable.NewMemStore(durable.WithHistory())} + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + scnStart(t, m, store, reg) + + _, err := durable.Recover(ctx, m, store, "scn-1", reg) + mustBeNewer(t, "Recover", err) + _, err = durable.NewRunner(m, store, reg).Fire(ctx, "scn-1", "done") + mustBeNewer(t, "Runner.Fire", err) + _, err = durable.StateAt(ctx, m, store, "scn-1", durable.BaselineStep, reg) + mustBeNewer(t, "StateAt", err) + _, err = durable.Steps(ctx, store, "scn-1") + mustBeNewer(t, "Steps", err) +} diff --git a/durable/journal_format_service_test.go b/durable/journal_format_service_test.go new file mode 100644 index 00000000..81313f6a --- /dev/null +++ b/durable/journal_format_service_test.go @@ -0,0 +1,96 @@ +package durable_test + +import ( + "context" + "encoding/json" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// olderWriter is a MemStore that stamps every Record and checkpoint it keeps with +// format, as a version that wrote that journal format did. The scnUser result these +// tests record needs no rewrite: an older version journaled json.Marshal of the value +// the ServiceFn returned, and for a scnUser those are the bytes this version records. +type olderWriter struct { + *durable.MemStore + format int +} + +func (s *olderWriter) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { + rec.Format = s.format + return s.MemStore.Append(ctx, id, rec, opts...) +} + +func (s *olderWriter) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { + var env map[string]json.RawMessage + if err := json.Unmarshal(snapshot, &env); err != nil { + return err + } + delete(env, "format") + if s.format > 0 { + env["format"] = json.RawMessage([]byte{byte('0' + s.format)}) + } + b, err := json.Marshal(env) + if err != nil { + return err + } + return s.MemStore.Checkpoint(ctx, id, b, throughStep, opts...) +} + +// TestJournalFormat_OlderServiceResult_ReplaysAsItDid: a service result an older +// version journaled, at format 0 (the 0.1.0 release), 1, 2 or 3 (each before results +// were decoded through WithEventDataDecoder), replays as that version replayed it: in +// JSON's generic form, through no decoder and no type check. Formats 2 and 3 are the +// ones the versions just before this one write, so this version can't take either for +// its own. A Runner whose decoder covers onDone, and fails, returns another type or +// returns the service's own type, still recovers it, and the replayed Assign sees the +// map the older version's replay gave it. Records this version writes, at format 4, +// decode through the decoder (see +// TestServiceResult_RecordedResultThatWontDecode_RunsNoAssignOnReplay). +func TestJournalFormat_OlderServiceResult_ReplaysAsItDid(t *testing.T) { + decoders := []struct { + name string + opt durable.Option[string, string, svcCtx] + }{ + {"decoder fails", failingDecoder()}, + {"decoder returns another type", decoderFor("done", durable.DecodeAs[scnAdmin])}, + {"decoder returns the service's type", decoderFor("done", durable.DecodeAs[scnUser])}, + } + for _, format := range []int{0, 1, 2, 3} { + for _, dc := range decoders { + t.Run(dc.name+", format "+string(rune('0'+format)), func(t *testing.T) { + ctx := context.Background() + fn := returning(scnUser{ID: 7, Name: "ann"}, nil) + a := &scnAssigns{} + m := scnMachine(fn, a) + store := &olderWriter{MemStore: durable.NewMemStore(durable.WithHistory()), format: format} + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + h := scnStart(t, m, store, reg) + mustRunService(t, h, state.InvokeID(scnInvoke, "loading", 0)) + _, recs, err := store.Load(ctx, "scn-1") + if err != nil || len(recs) != 1 || recs[0].Format != format { + t.Fatalf("the journal holds %+v (err %v), want one Record of format %d", recs, err, format) + } + + rh, err := durable.Recover(ctx, m, store, "scn-1", reg, dc.opt) + if err != nil { + t.Fatalf("Recover: %v; the older version recovered this journal", err) + } + if got := rh.Instance().Current(); got != "ready" { + t.Fatalf("recovered in %q, want ready", got) + } + if a.done != 2 { + t.Fatalf("onDone's Assign ran %d times, want 2 (live, replay)", a.done) + } + if _, ok := a.seen[1].(map[string]any); !ok { + t.Fatalf("replay saw %s, want the map[string]any the older version's replay gave", describe(a.seen[1])) + } + if _, err := durable.StateAt(ctx, m, store, "scn-1", 0, reg, dc.opt); err != nil { + t.Fatalf("StateAt: %v", err) + } + }) + } + } +} diff --git a/durable/journal_format_stateat_test.go b/durable/journal_format_stateat_test.go new file mode 100644 index 00000000..ebfb8319 --- /dev/null +++ b/durable/journal_format_stateat_test.go @@ -0,0 +1,96 @@ +package durable_test + +import ( + "context" + "errors" + "strconv" + "strings" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests answer two review findings. StateAt checked the journal formats only of +// the Records up to its target step, while Recover checks its whole tail, so a journal +// Recover refuses as mixed-version still reconstructed through StateAt before the older +// Record. And undecodableResult's doc said its error always wraps ErrEventDataEncoding, +// though a result with no JSON form fails the Handle with an error that doesn't. + +// loopMachine stays in spin on every "go". +func loopMachine() *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("loop"). + State("spin"). + Initial("spin"). + Transition("spin").On("go").GoTo("spin"). + Quench() +} + +// TestStateAt_RefusesAMixedJournalAtEveryStep: this version records steps 0 to 6 in +// format 2, and an older replica appends step 7 in format 1. Recover refuses the +// journal, so StateAt must refuse it at every step, before step 7 too, and Steps +// must refuse it, as each refuses a journal a newer version wrote. +func TestStateAt_RefusesAMixedJournalAtEveryStep(t *testing.T) { + for _, history := range []bool{false, true} { + name := "Load" + if history { + name = "History" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + m := loopMachine() + var st *durable.MemStore + if history { + st = durable.NewMemStore(durable.WithHistory()) + } else { + st = durable.NewMemStore() + } + h, err := durable.NewRunner(m, st).Start(ctx, "l1", svcCtx{}, state.WithInitialState("spin")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for i := range 7 { + if _, err = h.Fire(ctx, "go"); err != nil { + t.Fatalf("Fire %d: %v", i, err) + } + } + if _, err = st.Append(ctx, "l1", durable.Record{Step: 7, Event: []byte(`"go"`), Format: 1}); err != nil { + t.Fatalf("Append: %v", err) + } + mixed := func(what string, err error) { + t.Helper() + if err == nil || !strings.Contains(err.Error(), "older version") { + t.Errorf("%s = %v, want the mixed-version error", what, err) + } + } + _, err = durable.Recover(ctx, m, st, "l1") + mixed("Recover", err) + for _, step := range []int{durable.BaselineStep, 0, 5, 6, 7} { + _, err = durable.StateAt(ctx, m, st, "l1", step) + mixed("StateAt("+strconv.Itoa(step)+")", err) + } + _, err = durable.Steps(ctx, st, "l1") + mixed("Steps", err) + }) + } +} + +// TestRunService_ResultEncodingErrorsMatchTheirSentinels pins which sentinel each +// failed settle wraps. A result that won't decode is parked: RunService returns +// ErrEventDataEncoding with the Handle healthy. A result with no JSON form fails the +// Handle: RunService returns ErrHandleFailed, not ErrEventDataEncoding, whose Handle +// stays usable. +func TestRunService_ResultEncodingErrorsMatchTheirSentinels(t *testing.T) { + t.Run("won't decode", func(t *testing.T) { + _, runErr, _ := scnRun(t, returning(scnUser{ID: 7, Name: "ann"}, nil), failingDecoder()) + if !errors.Is(runErr, durable.ErrEventDataEncoding) || errors.Is(runErr, durable.ErrHandleFailed) { + t.Errorf("RunService = %v, want ErrEventDataEncoding without ErrHandleFailed", runErr) + } + }) + t.Run("won't encode", func(t *testing.T) { + _, runErr, _ := scnRun(t, returning(make(chan int), nil)) + if !errors.Is(runErr, durable.ErrHandleFailed) || errors.Is(runErr, durable.ErrEventDataEncoding) { + t.Errorf("RunService = %v, want ErrHandleFailed without ErrEventDataEncoding", runErr) + } + }) +} diff --git a/durable/parked_local_type_test.go b/durable/parked_local_type_test.go new file mode 100644 index 00000000..2b8418a6 --- /dev/null +++ b/durable/parked_local_type_test.go @@ -0,0 +1,60 @@ +package durable_test + +import ( + "context" + "encoding/json" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// otherLocalResult decodes data as a type declared in this function, named result as +// the one TestParkedResult_SameNamedLocalType's ServiceFn returns is: reflect spells the +// two alike, by package path and name, but they are distinct types. +func otherLocalResult(_ string, data []byte) (any, error) { + type result struct { + ID int `json:"id"` + } + var r result + err := json.Unmarshal(data, &r) + return r, err +} + +// TestParkedResult_SameNamedLocalType pins that a parked settle holds the decoder to the +// result's own type, as the live settle that parked it did, even when another type has +// the same name and package, such as two function-local types named result: the live +// check compares the types, and a parked settle on the same Handle compares them too, so +// the result stays parked and no Assign runs. After a Recover only the recorded name is +// left, which can't tell the two apart, so the parked settle accepts the other type: a +// result of a function-local type is identified by its name alone once it is recorded. +func TestParkedResult_SameNamedLocalType(t *testing.T) { + type result struct { + ID int `json:"id"` + } + ctx := context.Background() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return result{ID: 7}, nil } + a := &scnAssigns{} + m := scnMachine(fn, a) + opts := []durable.Option[string, string, svcCtx]{ + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + durable.WithEventDataDecoder[string, string, svcCtx](otherLocalResult), + } + store := durable.NewMemStore() + h := scnStart(t, m, store, opts...) + id := state.InvokeID(scnInvoke, "loading", 0) + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + _, ran, err = h.RunService(ctx, id) + mustPark(t, "RunService of the parked result", ran, err) + if a.done != 0 || a.fails != 0 { + t.Fatalf("Assigns ran: done %d, fail %d; want none: the decoder's result is another type than the ServiceFn's", a.done, a.fails) + } + recovered, err := durable.Recover(ctx, m, store, "scn-1", opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, err = recovered.RunService(ctx, id); !ran || err != nil || a.done != 1 { + t.Fatalf("RunService after Recover = ran %v, %v, done %d; want it settled: only the recorded name is left", ran, err, a.done) + } +} diff --git a/durable/parked_result_test.go b/durable/parked_result_test.go new file mode 100644 index 00000000..594a8660 --- /dev/null +++ b/durable/parked_result_test.go @@ -0,0 +1,484 @@ +package durable_test + +import ( + "context" + "errors" + "strings" + "sync/atomic" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests pin what a host sees for a service result the decoder for its onDone +// event refuses: RunService returns ErrEventDataEncoding, runs no Assign, and parks the +// result in the journal, with the Handle healthy and the service in flight; the +// ServiceFn never runs again, and a RunService after the decoder is fixed settles the +// parked result. + +// countingFetch returns a scnUser and counts its runs, standing in for a ServiceFn +// with a side effect. +func countingFetch(runs *int64) state.ServiceFn[svcCtx] { + return func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + atomic.AddInt64(runs, 1) + return scnUser{ID: 7, Name: "ann"}, nil + } +} + +// mustPark fails unless err says a RunService parked its result: ErrEventDataEncoding, +// not ErrHandleFailed, with the service found in flight. +func mustPark(t *testing.T, what string, ran bool, err error) { + t.Helper() + if !ran || !errors.Is(err, durable.ErrEventDataEncoding) || errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("%s = %v, %v; want ran and ErrEventDataEncoding without ErrHandleFailed", what, ran, err) + } +} + +// TestServiceResult_UndecodableResult_RunsTheServiceOnce: a result the decoder refuses, +// by failing or by returning another type, is parked. RunService returns +// ErrEventDataEncoding and the Handle stays healthy. Every later RunService, on the +// same Handle or after any number of Recovers, returns ErrEventDataEncoding again +// without running the ServiceFn, and records nothing more. No Assign runs. +func TestServiceResult_UndecodableResult_RunsTheServiceOnce(t *testing.T) { + for _, tc := range []struct { + name string + opt durable.Option[string, string, svcCtx] + }{ + {"decoder fails", failingDecoder()}, + {"type mismatch", decoderFor("done", durable.DecodeAs[scnAdmin])}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + var runs int64 + fn := countingFetch(&runs) + a := &scnAssigns{} + m := scnMachine(fn, a) + store := durable.NewMemStore() + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), tc.opt} + id := state.InvokeID(scnInvoke, "loading", 0) + h := scnStart(t, m, store, opts...) + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + _, ran, err = h.RunService(ctx, id) + mustPark(t, "RunService again on the same Handle", ran, err) + if verr := h.View(ctx, func(*state.Instance[string, string, svcCtx]) {}); verr != nil { + t.Fatalf("View after the park: %v, want the Handle healthy", verr) + } + for i := 1; i <= 3; i++ { + rh, rerr := durable.Recover(ctx, m, store, "scn-1", opts...) + if rerr != nil { + t.Fatalf("Recover %d: %v", i, rerr) + } + _, ran, err = rh.RunService(ctx, id) + mustPark(t, "RunService after Recover", ran, err) + if got := rh.Instance().Current(); got != "loading" { + t.Fatalf("Recover %d: in %q, want loading", i, got) + } + } + if got := atomic.LoadInt64(&runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } + if a.done != 0 || a.fails != 0 { + t.Fatalf("onDone's Assign ran %d times and onError's %d, want neither", a.done, a.fails) + } + if _, recs, lerr := store.Load(ctx, "scn-1"); lerr != nil || len(recs) != 1 { + t.Fatalf("the journal holds %d Records (err %v), want the one that parked the result", len(recs), lerr) + } + }) + } +} + +// parkRun starts scn-1 in loading, with the ServiceFn counting its runs, and runs the +// service once under a decoder that refuses the result. +type parkRun struct { + m *state.Machine[string, string, svcCtx] + a *scnAssigns + store *durable.MemStore + runs *int64 + reg durable.Option[string, string, svcCtx] + err error // the first RunService's error +} + +func newParkRun(t *testing.T, extra ...durable.Option[string, string, svcCtx]) *parkRun { + t.Helper() + runs := new(int64) + fn := countingFetch(runs) + r := &parkRun{ + a: &scnAssigns{}, + store: durable.NewMemStore(durable.WithHistory()), + runs: runs, + reg: durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + } + r.m = scnMachine(fn, r.a) + h := scnStart(t, r.m, r.store, append([]durable.Option[string, string, svcCtx]{r.reg, failingDecoder()}, extra...)...) + _, _, r.err = h.RunService(context.Background(), state.InvokeID(scnInvoke, "loading", 0)) + return r +} + +// recoverAndRun Recovers with opts and, if that works, runs the service. It returns +// the Handle, the RunService error and the Recover error. +func (r *parkRun) recoverAndRun(opts ...durable.Option[string, string, svcCtx]) (*durable.Handle[string, string, svcCtx], error, error) { + ctx := context.Background() + h, err := durable.Recover(ctx, r.m, r.store, "scn-1", append([]durable.Option[string, string, svcCtx]{r.reg}, opts...)...) + if err != nil { + return nil, nil, err + } + _, _, runErr := h.RunService(ctx, state.InvokeID(scnInvoke, "loading", 0)) + return h, runErr, nil +} + +// The ServiceFn, and its side effect, runs once however often the instance is +// recovered and the service run while the decoder still refuses the result. +func TestParkedResult_ServiceRunsOnce(t *testing.T) { + r := newParkRun(t) + for i := 0; i < 3; i++ { + _, _, _ = r.recoverAndRun(failingDecoder()) + } + if got := atomic.LoadInt64(r.runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } +} + +// A decode failure runs no Assign, onDone's or onError's, live, on replay, or while +// the result is parked. +func TestParkedResult_NoAssignOnDecodeFailure(t *testing.T) { + r := newParkRun(t) + _, _, _ = r.recoverAndRun(failingDecoder()) + _, _, _ = r.recoverAndRun(decoderFor("done", durable.DecodeAs[scnAdmin])) + if r.a.done != 0 || r.a.fails != 0 { + t.Fatalf("onDone's Assign ran %d times and onError's %d, want neither", r.a.done, r.a.fails) + } +} + +// Once the decoder is fixed, a RunService settles the result the service returned the +// first time, through onDone, without running the ServiceFn again; and a later +// Recover replays that settle. +func TestParkedResult_FixedDecoderSettlesTheOriginalResult(t *testing.T) { + r := newParkRun(t) + fixed := decoderFor("done", durable.DecodeAs[scnUser]) + h, runErr, err := r.recoverAndRun(fixed) + if err != nil || runErr != nil { + t.Fatalf("Recover: %v, RunService: %v, with the fixed decoder", err, runErr) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("the instance is in %q, want ready", got) + } + if got := atomic.LoadInt64(r.runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1: the fix should settle the recorded result", got) + } + if r.a.done != 1 || describe(r.a.seen[0]) != describe(scnUser{ID: 7, Name: "ann"}) { + t.Fatalf("onDone's Assign ran %d times and saw %v, want once with the scnUser", r.a.done, r.a.seen) + } + rh, err := durable.Recover(context.Background(), r.m, r.store, "scn-1", r.reg, fixed) + if err != nil { + t.Fatalf("Recover after the settle: %v", err) + } + if got := rh.Instance().Current(); got != "ready" { + t.Fatalf("recovered in %q, want ready", got) + } + if r.a.done != 2 || describe(r.a.seen[1]) != describe(r.a.seen[0]) { + t.Fatalf("replay: onDone's Assign ran %d times in all, saw %v; want twice with the same value", r.a.done, r.a.seen) + } + if got := atomic.LoadInt64(r.runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } +} + +// A parked result settles only as the type the ServiceFn returned, as live: a decoder +// fixed to another type is refused with ErrEventDataEncoding, and no Assign runs. +// JSON's generic form is accepted, as live. +func TestParkedResult_SettlesOnlyAsTheReturnedType(t *testing.T) { + r := newParkRun(t) + _, runErr, err := r.recoverAndRun(decoderFor("done", durable.DecodeAs[scnAdmin])) + if err != nil || !errors.Is(runErr, durable.ErrEventDataEncoding) { + t.Fatalf("Recover: %v, RunService: %v; want ErrEventDataEncoding for the wrong type", err, runErr) + } + if r.a.done != 0 || r.a.fails != 0 { + t.Fatalf("an Assign ran: onDone %d, onError %d", r.a.done, r.a.fails) + } + h, runErr, err := r.recoverAndRun() // the default decoder: JSON's generic form + if err != nil || runErr != nil { + t.Fatalf("Recover: %v, RunService: %v, with the default decoder", err, runErr) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("in %q, want ready", got) + } + if _, ok := r.a.seen[0].(map[string]any); !ok { + t.Fatalf("onDone's Assign saw %s, want JSON's generic form", describe(r.a.seen[0])) + } +} + +// The instance can still be recovered while the decoder refuses the result. +func TestParkedResult_RecoverableWhileBroken(t *testing.T) { + r := newParkRun(t) + h, err := durable.Recover(context.Background(), r.m, r.store, "scn-1", r.reg, failingDecoder()) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := h.Instance().Current(); got != "loading" { + t.Fatalf("recovered in %q, want loading", got) + } +} + +// The host is told: the RunService that met the failure returns ErrEventDataEncoding, +// and says the result is parked, not ErrHandleFailed. +func TestParkedResult_HostIsTold(t *testing.T) { + r := newParkRun(t) + mustPark(t, "RunService", true, r.err) + if !strings.Contains(r.err.Error(), "parked") { + t.Fatalf("RunService: %v, want it to say the result is parked", r.err) + } +} + +// The machine routing the failure itself, reaching its onError state with no host +// action, isn't what parking does: the owner chose to have the host fix the decoder. +func TestParkedResult_MachineRoutesTheFailure(t *testing.T) { + t.Skip("not this design: a parked result waits for the host to fix the decoder and call RunService; the machine doesn't route the failure through onError") +} + +// A checkpoint that compacts the Record that parked the result carries the parked +// result: the step that parks offers its checkpoint as any step does, and a Recover +// from it knows the service is parked, not in flight to run. The ServiceFn doesn't run +// again, and the fixed decoder gets the parked result. +func TestParkedResult_CheckpointKeepsIt(t *testing.T) { + ctx := context.Background() + r := newParkRun(t, durable.WithCheckpointEvery[string, string, svcCtx](1)) + mustPark(t, "RunService", true, r.err) + snap, recs, err := r.store.Load(ctx, "scn-1") + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(recs) != 0 { + t.Fatalf("the tail holds %d Records, want none: the park step should checkpoint", len(recs)) + } + if !strings.Contains(string(snap), `"parkedServices"`) { + t.Fatalf("the checkpoint carries no parked result: %s", snap) + } + // Still broken: the service is parked, not run. + if _, runErr, rerr := r.recoverAndRun(failingDecoder()); rerr != nil || !errors.Is(runErr, durable.ErrEventDataEncoding) { + t.Fatalf("Recover: %v, RunService: %v; want ErrEventDataEncoding", rerr, runErr) + } + if got := atomic.LoadInt64(r.runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times after the checkpoint, want 1", got) + } + h, runErr, err := r.recoverAndRun(decoderFor("done", durable.DecodeAs[scnUser])) + if err != nil || runErr != nil { + t.Fatalf("Recover: %v, RunService: %v, with the fixed decoder", err, runErr) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("in %q, want ready", got) + } + if got := atomic.LoadInt64(r.runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } + if r.a.done != 1 || describe(r.a.seen[0]) != describe(scnUser{ID: 7, Name: "ann"}) { + t.Fatalf("onDone's Assign ran %d times and saw %v, want the parked scnUser", r.a.done, r.a.seen) + } +} + +// StateAt replays a parked Record as the live run left it: nothing settled, so the +// view at the park step is the instance before it, whatever the decoder, and runs no +// Assign. A later settle replays as any recorded result. +func TestParkedResult_StateAt(t *testing.T) { + ctx := context.Background() + r := newParkRun(t) + fixed := decoderFor("done", durable.DecodeAs[scnUser]) + if _, runErr, err := r.recoverAndRun(fixed); err != nil || runErr != nil { + t.Fatalf("Recover: %v, RunService: %v", err, runErr) + } + steps, err := durable.Steps(ctx, r.store, "scn-1") + if err != nil || len(steps) != 2 { + t.Fatalf("Steps = %v, %v; want the park and the settle", steps, err) + } + doneBefore := r.a.done + for _, dec := range []durable.Option[string, string, svcCtx]{failingDecoder(), fixed} { + v, serr := durable.StateAt(ctx, r.m, r.store, "scn-1", steps[0], r.reg, dec) + if serr != nil { + t.Fatalf("StateAt the park: %v", serr) + } + if got := v.Instance().Current(); got != "loading" { + t.Fatalf("StateAt the park: in %q, want loading", got) + } + } + if r.a.done != doneBefore || r.a.fails != 0 { + t.Fatalf("StateAt the park ran an Assign: onDone %d (was %d), onError %d", r.a.done, doneBefore, r.a.fails) + } + v, err := durable.StateAt(ctx, r.m, r.store, "scn-1", steps[1], r.reg, fixed) + if err != nil { + t.Fatalf("StateAt the settle: %v", err) + } + if got := v.Instance().Current(); got != "ready" { + t.Fatalf("StateAt the settle: in %q, want ready", got) + } +} + +// cancelMachine invokes fn in "loading", which "cancel" leaves for idle and "retry" +// re-enters, so a parked service can be stopped and started again under the same +// invoke id. +func cancelMachine(fn state.ServiceFn[svcCtx], a *scnAssigns) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("park"). + Service("fetch", fn). + Reducer("noteDone", func(in state.AssignCtx[svcCtx]) svcCtx { + a.done++ + a.seen = append(a.seen, in.Event) + return in.Entity + }). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done")). + State("ready").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready").Assign("noteDone"). + Transition("loading").On("cancel").GoTo("idle"). + Transition("idle").On("retry").GoTo("loading"). + Quench() +} + +// countingUsers returns a scnUser whose ID counts the runs. +func countingUsers(runs *int64) state.ServiceFn[svcCtx] { + return func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + return scnUser{ID: atomic.AddInt64(runs, 1), Name: "ann"}, nil + } +} + +// Leaving the state that declares a parked service stops the service and discards the +// parked result, live and on replay, with or without a checkpoint: RunService finds +// nothing in flight, and re-entering the state starts a new activation whose ServiceFn +// runs, rather than settling the discarded result. +func TestParkedResult_LeavingTheStateDiscardsIt(t *testing.T) { + for _, every := range []int{0, 1} { + name := "no checkpoint" + if every > 0 { + name = "checkpoint every step" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + runs := new(int64) + fn := countingUsers(runs) + a := &scnAssigns{} + m := cancelMachine(fn, a) + store := durable.NewMemStore() + base := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))} + if every > 0 { + base = append(base, durable.WithCheckpointEvery[string, string, svcCtx](every)) + } + broken := append(append([]durable.Option[string, string, svcCtx]{}, base...), failingDecoder()) + fixed := append(append([]durable.Option[string, string, svcCtx]{}, base...), decoderFor("done", durable.DecodeAs[scnUser])) + id := state.InvokeID("park", "loading", 0) + + h, err := durable.NewRunner(m, store, broken...).Start(ctx, "p-1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + if _, err = h.Fire(ctx, "cancel"); err != nil { + t.Fatalf("Fire cancel: %v", err) + } + if _, ran, err = h.RunService(ctx, id); ran || err != nil { + t.Fatalf("RunService after cancel = %v, %v; want nothing in flight", ran, err) + } + rh, err := durable.Recover(ctx, m, store, "p-1", fixed...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, err = rh.RunService(ctx, id); ran || err != nil { + t.Fatalf("RunService after Recover = %v, %v; want nothing in flight", ran, err) + } + if got := rh.Instance().Current(); got != "idle" || a.done != 0 { + t.Fatalf("recovered in %q with onDone run %d times, want idle and none", got, a.done) + } + + // Re-entering starts a new activation: its ServiceFn runs, and the discarded + // result never settles. + if _, err = rh.Fire(ctx, "retry"); err != nil { + t.Fatalf("Fire retry: %v", err) + } + mustRunService(t, rh, id) + if got := atomic.LoadInt64(runs); got != 2 { + t.Fatalf("the ServiceFn ran %d times, want 2: once per activation", got) + } + if a.done != 1 || describe(a.seen[0]) != describe(scnUser{ID: 2, Name: "ann"}) { + t.Fatalf("onDone saw %v, want the second activation's scnUser", a.seen) + } + }) + } +} + +// A service parked, stopped and started again on the same Handle runs its ServiceFn +// for the new activation, rather than settle the first one's parked result, even +// before any Recover. +func TestParkedResult_ReenteredStateRunsTheServiceAgain(t *testing.T) { + ctx := context.Background() + runs := new(int64) + fn := countingUsers(runs) + a := &scnAssigns{} + m := cancelMachine(fn, a) + store := durable.NewMemStore() + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + id := state.InvokeID("park", "loading", 0) + h, err := durable.NewRunner(m, store, reg, failingDecoder()).Start(ctx, "p-1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + for _, ev := range []string{"cancel", "retry"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire %s: %v", ev, err) + } + } + _, ran, err = h.RunService(ctx, id) + mustPark(t, "RunService of the new activation", ran, err) + if got := atomic.LoadInt64(runs); got != 2 { + t.Fatalf("the ServiceFn ran %d times, want 2: the new activation runs it", got) + } + // The fixed decoder settles the new activation's parked result, not the first's. + rh, err := durable.Recover(ctx, m, store, "p-1", reg, decoderFor("done", durable.DecodeAs[scnUser])) + if err != nil { + t.Fatalf("Recover: %v", err) + } + mustRunService(t, rh, id) + if a.done != 1 || describe(a.seen[0]) != describe(scnUser{ID: 2, Name: "ann"}) { + t.Fatalf("onDone saw %v, want the second activation's scnUser", a.seen) + } + if got := atomic.LoadInt64(runs); got != 2 { + t.Fatalf("the ServiceFn ran %d times, want 2", got) + } +} + +// A Recover whose journal parks a result, then stops and starts its service again, +// replays the new activation as unparked: RunService runs the ServiceFn for it rather +// than settle the discarded result. +func TestParkedResult_ReplayedReentryRunsTheServiceAgain(t *testing.T) { + ctx := context.Background() + runs := new(int64) + fn := countingUsers(runs) + a := &scnAssigns{} + m := cancelMachine(fn, a) + store := durable.NewMemStore() + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + id := state.InvokeID("park", "loading", 0) + h, err := durable.NewRunner(m, store, reg, failingDecoder()).Start(ctx, "p-1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + for _, ev := range []string{"cancel", "retry"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire %s: %v", ev, err) + } + } + rh, err := durable.Recover(ctx, m, store, "p-1", reg, decoderFor("done", durable.DecodeAs[scnUser])) + if err != nil { + t.Fatalf("Recover: %v", err) + } + mustRunService(t, rh, id) + if got := atomic.LoadInt64(runs); got != 2 { + t.Fatalf("the ServiceFn ran %d times, want 2: the new activation runs it", got) + } + if a.done != 1 || describe(a.seen[0]) != describe(scnUser{ID: 2, Name: "ann"}) { + t.Fatalf("onDone saw %v, want the second activation's scnUser", a.seen) + } +} diff --git a/durable/parked_tick_test.go b/durable/parked_tick_test.go new file mode 100644 index 00000000..a0993548 --- /dev/null +++ b/durable/parked_tick_test.go @@ -0,0 +1,311 @@ +package durable_test + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests pin what a Tick does to a parked result: a timer transition hands its +// effects to the service runner, as a Fire does, so a timer that leaves the state that +// declares a parked service stops the service and discards the parked result, and one +// that re-enters the state starts a fresh activation, whose ServiceFn runs. The live +// Handle, one recovered from the journal and one recovered from a checkpoint agree, and +// the ServiceFn runs once per activation. + +// timerParkMachine invokes fn in "loading", which "begin" enters from "idle" (Start +// arms no timer). Its after timer leaves for "timedOut", or with reenter re-enters +// "loading". +func timerParkMachine(fn state.ServiceFn[svcCtx], a *scnAssigns, reenter bool) *state.Machine[string, string, svcCtx] { + f := state.ForgeFor[svcCtx]("park"). + Service("fetch", fn). + Reducer("noteDone", func(in state.AssignCtx[svcCtx]) svcCtx { + a.done++ + a.seen = append(a.seen, in.Event) + return in.Entity + }). + State("idle"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done")). + State("ready").Final(). + State("timedOut"). + Initial("idle"). + Transition("idle").On("begin").GoTo("loading"). + Transition("loading").On("done").GoTo("ready").Assign("noteDone") + if reenter { + f = f.Transition("loading").After(5 * time.Second).On("redo").GoTo("loading").Reenter() + } else { + f = f.Transition("loading").After(5 * time.Second).On("timeout").GoTo("timedOut") + } + return f.Quench() +} + +// parkProbe is what a RunService of a parked service reports: whether it found the +// service in flight, and whether it found the result parked (ErrEventDataEncoding, +// with the Handle healthy). +type parkProbe struct { + inFlight, parked bool +} + +func probePark(t *testing.T, h *durable.Handle[string, string, svcCtx], id string) parkProbe { + t.Helper() + _, ran, err := h.RunService(context.Background(), id) + if err != nil && !errors.Is(err, durable.ErrEventDataEncoding) || errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService = %v, %v; want nil or ErrEventDataEncoding", ran, err) + } + return parkProbe{inFlight: ran, parked: ran && errors.Is(err, durable.ErrEventDataEncoding)} +} + +// timerPark is a run that parks the result of loading's service, then Ticks its after +// timer. Its decoder refuses onDone while refuse is set, and decodes it as scnUser +// otherwise, so the live Handle can settle a result once the test clears refuse. +type timerPark struct { + m *state.Machine[string, string, svcCtx] + a *scnAssigns + store *durable.MemStore + runs *int64 + refuse *atomic.Bool + opts []durable.Option[string, string, svcCtx] + live *durable.Handle[string, string, svcCtx] +} + +const timerParkID = "p-1" + +var timerParkSvc = state.InvokeID("park", "loading", 0) + +// newTimerPark parks the result, Ticks the timer, and fails unless the timer fired. +// With every above zero, every step checkpoints, so the Tick's Record carries one. +func newTimerPark(t *testing.T, reenter bool, every int) *timerPark { + t.Helper() + ctx := context.Background() + r := &timerPark{a: &scnAssigns{}, store: durable.NewMemStore(), runs: new(int64), refuse: new(atomic.Bool)} + r.refuse.Store(true) + fn := countingUsers(r.runs) + r.m = timerParkMachine(fn, r.a, reenter) + clk := state.NewFakeClock(epoch) + r.opts = []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + decoderFor("done", func(data []byte) (any, error) { + if r.refuse.Load() { + return nil, errors.New("decoder refused") + } + return durable.DecodeAs[scnUser](data) + }), + } + if every > 0 { + r.opts = append(r.opts, durable.WithCheckpointEvery[string, string, svcCtx](every)) + } + + h, err := durable.NewRunner(r.m, r.store, r.opts...).Start(ctx, timerParkID, svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, err = h.Fire(ctx, "begin"); err != nil { + t.Fatalf("Fire begin: %v", err) + } + _, ran, err := h.RunService(ctx, timerParkSvc) + mustPark(t, "RunService", ran, err) + clk.Advance(6 * time.Second) + if results, terr := h.Tick(ctx); terr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v; want the timer to fire", len(results), terr) + } + want := "timedOut" + if reenter { + want = "loading" + } + if got := h.Instance().Current(); got != want { + t.Fatalf("after the Tick in %q, want %q", got, want) + } + r.live = h + return r +} + +func (r *timerPark) recover(t *testing.T, what string) *durable.Handle[string, string, svcCtx] { + t.Helper() + h, err := durable.Recover(context.Background(), r.m, r.store, timerParkID, r.opts...) + if err != nil { + t.Fatalf("Recover %s: %v; want the instance recoverable", what, err) + } + return h +} + +// mustRun fails unless the ServiceFn ran n times. +func (r *timerPark) mustRun(t *testing.T, n int64, why string) { + t.Helper() + if got := atomic.LoadInt64(r.runs); got != n { + t.Fatalf("the ServiceFn ran %d times, want %d: %s", got, n, why) + } +} + +func everyName(every int) string { + if every > 0 { + return "checkpoint every step" + } + return "journal" +} + +// TestParkedResult_TimerLeavingTheStateStopsTheService pins that an after timer leaving +// the state that declares a parked service stops the service and discards the parked +// result, as a Fire does: RunService finds nothing in flight on the live Handle and on +// one recovered from the journal or from the Tick's checkpoint, which all agree, and +// the ServiceFn ran once. A fixed decoder settles nothing either. +func TestParkedResult_TimerLeavingTheStateStopsTheService(t *testing.T) { + for _, every := range []int{0, 1} { + t.Run(everyName(every), func(t *testing.T) { + r := newTimerPark(t, false, every) + if got := probePark(t, r.live, timerParkSvc); got != (parkProbe{}) { + t.Errorf("live after the Tick: %+v, want nothing in flight", got) + } + if got := probePark(t, r.recover(t, "after the Tick"), timerParkSvc); got != (parkProbe{}) { + t.Errorf("recovered after the Tick: %+v, want nothing in flight, as live", got) + } + r.refuse.Store(false) + fh := r.recover(t, "with the fixed decoder") + if got := probePark(t, fh, timerParkSvc); got != (parkProbe{}) { + t.Errorf("recovered with the fixed decoder: %+v, want nothing in flight", got) + } + if got := fh.Instance().Current(); got != "timedOut" || r.a.done != 0 { + t.Errorf("recovered in %q with onDone run %d times, want timedOut and none", got, r.a.done) + } + if _, recs, _ := r.store.Load(context.Background(), timerParkID); every == 0 && len(recs) != 3 { + t.Errorf("the journal holds %d Records, want 3 (begin, the park, the Tick): no RunService recorded anything", len(recs)) + } + r.mustRun(t, 1, "the service stopped with its parked result") + }) + } +} + +// TestParkedResult_TimerThenCheckpointThenSettleStaysRecoverable is the sequence that +// failed every Recover while a Tick left the service in flight: park a result, let a +// timer leave the service's state, take a checkpoint that no longer holds the service, +// then call RunService on the live Handle. The Handle settled the service there, kept +// or run again, and journaled a settle replay can't apply ("no in-flight service to +// settle"). Now the timer stopped the service, so RunService finds nothing, records +// nothing, and every Recover succeeds. +func TestParkedResult_TimerThenCheckpointThenSettleStaysRecoverable(t *testing.T) { + ctx := context.Background() + // Every third step checkpoints: begin, the park, then the Tick, so the checkpoint + // lands on the Tick's Record and anything RunService records follows it. + r := newTimerPark(t, false, 3) + ckpt, recs, err := r.store.Load(ctx, timerParkID) + if err != nil || len(ckpt) == 0 || len(recs) != 0 { + t.Fatalf("after the Tick the store holds a %d-byte checkpoint and %d Records (%v); want the Tick's checkpoint and nothing after it", len(ckpt), len(recs), err) + } + r.refuse.Store(false) + _, ran, rerr := r.live.RunService(ctx, timerParkSvc) + for i := range 2 { + h := r.recover(t, "after the live RunService") + if got := h.Instance().Current(); got != "timedOut" { + t.Fatalf("Recover %d in %q, want timedOut", i, got) + } + if _, hran, herr := h.RunService(ctx, timerParkSvc); hran || herr != nil { + t.Fatalf("RunService after Recover %d = %v, %v; want nothing in flight", i, hran, herr) + } + } + if ran || rerr != nil { + t.Fatalf("live RunService after the Tick = %v, %v; want nothing in flight: the timer stopped the service", ran, rerr) + } + r.mustRun(t, 1, "the timer stopped the service") +} + +// TestParkedResult_TimerReenteringTheStateRunsAFreshActivation pins that an after timer +// that re-enters the state that declares a parked service stops the old activation, +// discarding its parked result, and starts a fresh one, whose ServiceFn runs: on the +// live Handle and on one recovered from the journal or the Tick's checkpoint. The fixed +// decoder settles the fresh run's result, which reaches ready with the second +// scnUser, and the ServiceFn runs once per activation. +func TestParkedResult_TimerReenteringTheStateRunsAFreshActivation(t *testing.T) { + for _, every := range []int{0, 1} { + for _, where := range []string{"live", "recovered"} { + t.Run(everyName(every)+"/"+where, func(t *testing.T) { + r := newTimerPark(t, true, every) + h := r.live + if where == "recovered" { + h = r.recover(t, "after the Tick") + } + r.refuse.Store(false) + if got := probePark(t, h, timerParkSvc); got != (parkProbe{inFlight: true}) { + t.Fatalf("%s after the Tick: %+v, want the fresh activation run and settled", where, got) + } + r.mustRun(t, 2, "once for each activation") + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("in %q, want ready", got) + } + if describe(r.a.seen[0]) != describe(scnUser{ID: 2, Name: "ann"}) { + t.Fatalf("onDone saw %v, want the fresh activation's scnUser", r.a.seen) + } + if got := probePark(t, h, timerParkSvc); got != (parkProbe{}) { + t.Fatalf("after the settle: %+v, want nothing in flight", got) + } + if got := r.recover(t, "after the settle").Instance().Current(); got != "ready" { + t.Fatalf("recovered after the settle in %q, want ready", got) + } + r.mustRun(t, 2, "once for each activation") + }) + } + } +} + +// TestTimerLeavingTheState_SettleAfterCheckpointStaysRecoverable is the same sequence +// with nothing parked: loading's service is in flight, its after timer leaves for +// timedOut, the Tick's Record carries a checkpoint, which holds only the services of the +// states the instance is in, and the live Handle then calls RunService. While Tick left +// the service in flight, that ran it and journaled its settle after the checkpoint, +// which replay couldn't apply, so every Recover failed. Now the timer stopped the +// service: RunService finds nothing in flight and Recover succeeds. +func TestTimerLeavingTheState_SettleAfterCheckpointStaysRecoverable(t *testing.T) { + ctx := context.Background() + runs := new(int64) + fn := countingUsers(runs) + // prep adds a step before loading, so the Tick lands on the checkpoint and anything + // RunService records follows it. + m := state.ForgeFor[svcCtx]("park"). + Service("fetch", fn). + State("idle"). + State("prep"). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done")). + State("ready").Final(). + State("timedOut"). + Initial("idle"). + Transition("idle").On("prep").GoTo("prep"). + Transition("prep").On("begin").GoTo("loading"). + Transition("loading").On("done").GoTo("ready"). + Transition("loading").After(5 * time.Second).On("timeout").GoTo("timedOut"). + Quench() + clk := state.NewFakeClock(epoch) + store := durable.NewMemStore() + opts := []durable.Option[string, string, svcCtx]{ + durable.WithRunnerClock[string, string, svcCtx](clk), + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + decoderFor("done", durable.DecodeAs[scnUser]), + durable.WithCheckpointEvery[string, string, svcCtx](3), + } + h, err := durable.NewRunner(m, store, opts...).Start(ctx, "t-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + for _, ev := range []string{"prep", "begin"} { + if _, err = h.Fire(ctx, ev); err != nil { + t.Fatalf("Fire %s: %v", ev, err) + } + } + clk.Advance(6 * time.Second) + if results, terr := h.Tick(ctx); terr != nil || len(results) != 1 { + t.Fatalf("Tick = %d results, %v; want the timer to fire", len(results), terr) + } + if ckpt, recs, lerr := store.Load(ctx, "t-1"); lerr != nil || len(ckpt) == 0 || len(recs) != 0 { + t.Fatalf("after the Tick the store holds a %d-byte checkpoint and %d Records (%v); want the Tick's checkpoint and nothing after it", len(ckpt), len(recs), lerr) + } + _, ran, rerr := h.RunService(ctx, timerParkSvc) + if _, err = durable.Recover(ctx, m, store, "t-1", opts...); err != nil { + t.Fatalf("Recover: %v; want the instance recoverable", err) + } + if ran || rerr != nil || atomic.LoadInt64(runs) != 0 { + t.Fatalf("live RunService after the Tick = %v, %v with the ServiceFn run %d times; want nothing in flight: the timer stopped the service", ran, rerr, atomic.LoadInt64(runs)) + } +} diff --git a/durable/parked_type_test.go b/durable/parked_type_test.go new file mode 100644 index 00000000..b175f996 --- /dev/null +++ b/durable/parked_type_test.go @@ -0,0 +1,227 @@ +package durable_test + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync/atomic" + "testing" + + "github.com/stablekernel/crucible/durable" + alpha "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model" + beta "github.com/stablekernel/crucible/durable/internal/typefixture/beta/model" + "github.com/stablekernel/crucible/state" +) + +// These tests answer two review findings on the Go type a parked result records: what +// a type moved or renamed after the park does to the result, and whether the Record +// that finally settles a parked result keeps the type, so replay holds the decoder to +// it as the live settle did. + +// alphaResultType is the type name a parked alpha.Result records. +const alphaResultType = "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model.Result" + +// movedFromType is where alpha.Result lived before the move these tests stand in for. +const movedFromType = "github.com/stablekernel/crucible/durable/internal/typefixture/old/model.Result" + +// parkedAlpha parks an alpha.Result for scn-1 under a decoder that refuses it, and +// returns the machine, its Assigns, the registry option and the store. +func parkedAlpha(t *testing.T) (*state.Machine[string, string, svcCtx], *scnAssigns, durable.Option[string, string, svcCtx], *durable.MemStore, *int64) { + t.Helper() + runs := new(int64) + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + atomic.AddInt64(runs, 1) + return alpha.Result{ID: 7, Name: "ann"}, nil + } + a := &scnAssigns{} + m := scnMachine(fn, a) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + store := durable.NewMemStore() + h := scnStart(t, m, store, reg, failingDecoder()) + _, ran, err := h.RunService(context.Background(), state.InvokeID(scnInvoke, "loading", 0)) + mustPark(t, "RunService", ran, err) + return m, a, reg, store, runs +} + +// rewriteServiceTypes copies scn-1's journal into a fresh MemStore with every recorded +// service entry's Type from replaced by to, as if the type had been moved after the +// version that recorded it. +func rewriteServiceTypes(t *testing.T, src *durable.MemStore, from, to string) *durable.MemStore { + t.Helper() + ctx := context.Background() + snap, recs, err := src.Load(ctx, "scn-1") + if err != nil { + t.Fatalf("Load: %v", err) + } + dst := durable.NewMemStore() + if err = dst.Checkpoint(ctx, "scn-1", snap, -1); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + rewrote := 0 + for _, rec := range recs { + for i, e := range rec.Entries { + if e.Kind != state.JournalServiceResult { + continue + } + var p map[string]any + if err = json.Unmarshal(e.Payload, &p); err != nil { + t.Fatalf("decoding a service entry: %v", err) + } + if p["type"] == from { + p["type"] = to + rewrote++ + } + if rec.Entries[i].Payload, err = json.Marshal(p); err != nil { + t.Fatalf("encoding a service entry: %v", err) + } + } + if _, err = dst.Append(ctx, "scn-1", rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + if rewrote == 0 { + t.Fatalf("no service entry recorded the type %s", from) + } + return dst +} + +// serviceTypes returns the Type of each recorded service entry for scn-1, in order. +func serviceTypes(t *testing.T, st durable.Store) []string { + t.Helper() + _, recs, err := st.Load(context.Background(), "scn-1") + if err != nil { + t.Fatalf("Load: %v", err) + } + var out []string + for _, rec := range recs { + for _, e := range rec.Entries { + if e.Kind != state.JournalServiceResult { + continue + } + var p struct { + Type string `json:"type"` + Parked bool `json:"parked"` + } + if err = json.Unmarshal(e.Payload, &p); err != nil { + t.Fatalf("decoding a service entry: %v", err) + } + out = append(out, p.Type) + } + } + return out +} + +// TestParkedResult_MovedType pins what a type moved, or renamed, after a park does to +// its result. The park recorded the old full name, and settling holds the decoder to +// it, so a decoder for the type in its new home is refused on every RunService: the +// result stays parked, and no Assign runs. The way out is a decoder that gives JSON's +// generic form for the event, which a parked settle always accepts, as live does; the +// ServiceFn never runs again either way. After a park the result's original value is +// gone, so nothing tells a moved type from a wrong decoder's same-shaped one (see +// TestParkedResult_TypeCheckKeepsTheImportPath). +func TestParkedResult_MovedType(t *testing.T) { + ctx := context.Background() + m, a, reg, src, runs := parkedAlpha(t) + store := rewriteServiceTypes(t, src, alphaResultType, movedFromType) + id := state.InvokeID(scnInvoke, "loading", 0) + asAlpha := decoderFor("done", durable.DecodeAs[alpha.Result]) + for i := 0; i < 2; i++ { + h, err := durable.Recover(ctx, m, store, "scn-1", reg, asAlpha) + if err != nil { + t.Fatalf("Recover: %v", err) + } + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService with the moved type's decoder", ran, err) + if !strings.Contains(err.Error(), movedFromType) { + t.Fatalf("RunService: %v, want it to name the recorded type %s", err, movedFromType) + } + } + if a.done != 0 || a.fails != 0 { + t.Fatalf("an Assign ran: onDone %d, onError %d", a.done, a.fails) + } + h, err := durable.Recover(ctx, m, store, "scn-1", reg) // the default decoder + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, _, err = h.RunService(ctx, id); err != nil { + t.Fatalf("RunService with the default decoder: %v, want the generic form to settle it", err) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("in %q, want ready", got) + } + if _, ok := a.seen[0].(map[string]any); a.done != 1 || !ok { + t.Fatalf("onDone's Assign ran %d times and saw %v, want once with JSON's generic form", a.done, a.seen) + } + if got := atomic.LoadInt64(runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } +} + +// TestParkedResult_SettledRecordKeepsTheType: the Record that settles a parked result +// records the type the park did, and replay holds the decoder to it, as the live settle +// did. A Recover whose decoder gives another type fails with ErrEventDataEncoding and +// runs no Assign, rather than hand onDone's Assign a value of a type the live run never +// let through. +func TestParkedResult_SettledRecordKeepsTheType(t *testing.T) { + ctx := context.Background() + r := newParkRun(t) + fixed := decoderFor("done", durable.DecodeAs[scnUser]) + if _, runErr, err := r.recoverAndRun(fixed); err != nil || runErr != nil { + t.Fatalf("Recover: %v, RunService: %v, with the fixed decoder", err, runErr) + } + userType := "github.com/stablekernel/crucible/durable_test.scnUser" + if got := serviceTypes(t, r.store); len(got) != 2 || got[0] != userType || got[1] != userType { + t.Fatalf("the service entries record the types %q, want the park's and the settle's both %s", got, userType) + } + done := r.a.done + _, err := durable.Recover(ctx, r.m, r.store, "scn-1", r.reg, decoderFor("done", durable.DecodeAs[scnAdmin])) + if !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Recover with a decoder for another type: %v, want ErrEventDataEncoding", err) + } + if r.a.done != done { + t.Fatalf("replay ran onDone's Assign with %s, a type the live settle refuses", describe(r.a.seen[len(r.a.seen)-1])) + } + // The fixed decoder, and JSON's generic form, still replay it. + if _, err = durable.Recover(ctx, r.m, r.store, "scn-1", r.reg, fixed); err != nil { + t.Fatalf("Recover with the fixed decoder: %v", err) + } + if _, err = durable.Recover(ctx, r.m, r.store, "scn-1", r.reg); err != nil { + t.Fatalf("Recover with the default decoder: %v", err) + } +} + +// TestParkedResult_StructLiteralKeepsTheImportPath: a result whose type is a struct +// literal with a field of alpha's model.Result is parked under that full name, so a +// decoder for the literal with beta's model.Result in its place can't settle it, as for +// the named types (see TestParkedResult_TypeCheckKeepsTheImportPath). +func TestParkedResult_StructLiteralKeepsTheImportPath(t *testing.T) { + ctx := context.Background() + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + return struct{ R alpha.Result }{alpha.Result{ID: 7, Name: "ann"}}, nil + } + a := &scnAssigns{} + m := scnMachine(fn, a) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + store := durable.NewMemStore() + id := state.InvokeID(scnInvoke, "loading", 0) + h := scnStart(t, m, store, reg, failingDecoder()) + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + rh, err := durable.Recover(ctx, m, store, "scn-1", reg, decoderFor("done", durable.DecodeAs[struct{ R beta.Result }])) + if err != nil { + t.Fatalf("Recover: %v", err) + } + _, ran, err = rh.RunService(ctx, id) + mustPark(t, "RunService with a decoder for beta's literal", ran, err) + if a.done != 0 { + t.Fatalf("onDone's Assign ran with %v", a.seen) + } + rh, err = durable.Recover(ctx, m, store, "scn-1", reg, decoderFor("done", durable.DecodeAs[struct{ R alpha.Result }])) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, _, err = rh.RunService(ctx, id); err != nil { + t.Fatalf("RunService with a decoder for alpha's literal: %v", err) + } +} diff --git a/durable/result_decoding_scenarios_test.go b/durable/result_decoding_scenarios_test.go new file mode 100644 index 00000000..1e1f9d68 --- /dev/null +++ b/durable/result_decoding_scenarios_test.go @@ -0,0 +1,371 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These scenario tests pin what a host's Assign sees for a service result, live and +// after Recover: a result whose onDone event WithEventDataDecoder covers arrives as the +// decoder's type, any other arrives in JSON's generic form, an error is message-only, +// and a decoder that fails or returns the wrong type parks the result before any +// Assign runs. + +type scnUser struct { + ID int64 + Name string +} + +type scnAdmin struct { + ID int64 + Name string + Level int +} + +var errScnNotFound = errors.New("user not found") + +// scnAssigns records what the onDone and onError Assigns saw, in order, and how many +// times each ran. +type scnAssigns struct { + seen []any + done, fails int +} + +// scnMachine invokes fn on entering "loading": onDone "done" goes to ready, onError +// "fail" to failed, each through an Assign that notes what it saw in a. +func scnMachine(fn state.ServiceFn[svcCtx], a *scnAssigns) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("scn"). + Service("fetch", fn). + Reducer("noteDone", func(in state.AssignCtx[svcCtx]) svcCtx { + a.done++ + a.seen = append(a.seen, in.Event) + return in.Entity + }). + Reducer("noteFail", func(in state.AssignCtx[svcCtx]) svcCtx { + a.fails++ + a.seen = append(a.seen, in.Event) + return in.Entity + }). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready").Final(). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready").Assign("noteDone"). + Transition("loading").On("fail").GoTo("failed").Assign("noteFail"). + Quench() +} + +const scnInvoke = "scn" // the machine id InvokeID takes + +// scnStart starts an instance of m in "loading" and returns its Handle. +func scnStart(t *testing.T, m *state.Machine[string, string, svcCtx], store durable.Store, opts ...durable.Option[string, string, svcCtx]) *durable.Handle[string, string, svcCtx] { + t.Helper() + h, err := durable.NewRunner(m, store, opts...).Start(context.Background(), "scn-1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + return h +} + +// scnRun starts an instance in a state that invokes fn, runs the service live, then +// Recovers it, and returns what onDone's or onError's Assign saw each time (live +// first), with the RunService and Recover errors. +func scnRun(t *testing.T, fn state.ServiceFn[svcCtx], opts ...durable.Option[string, string, svcCtx]) (a *scnAssigns, runErr, recoverErr error) { + t.Helper() + ctx := context.Background() + a = &scnAssigns{} + m := scnMachine(fn, a) + store := durable.NewMemStore() + opts = append([]durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))}, opts...) + h := scnStart(t, m, store, opts...) + _, _, runErr = h.RunService(ctx, state.InvokeID(scnInvoke, "loading", 0)) + _, recoverErr = durable.Recover(ctx, m, store, "scn-1", opts...) + return a, runErr, recoverErr +} + +func describe(v any) string { return fmt.Sprintf("%T %+v", v, v) } + +// decoderFor decodes event's payload with d and every other event's as JSON's own form. +func decoderFor(event string, d func([]byte) (any, error)) durable.Option[string, string, svcCtx] { + return durable.WithEventDataDecoder[string, string, svcCtx](func(e string, data []byte) (any, error) { + if e == event { + return d(data) + } + return durable.DecodeAs[any](data) + }) +} + +func returning(v any, err error) state.ServiceFn[svcCtx] { + return func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return v, err } +} + +// mustTwo fails unless the Assign ran exactly live and once on replay, and saw the +// same value both times. +func mustTwo(t *testing.T, a *scnAssigns, runErr, recErr error) { + t.Helper() + if runErr != nil || recErr != nil { + t.Fatalf("RunService: %v, Recover: %v", runErr, recErr) + } + if len(a.seen) != 2 { + t.Fatalf("Assign ran %d times, want 2 (live, replay): %v", len(a.seen), a.seen) + } + if describe(a.seen[0]) != describe(a.seen[1]) { + t.Fatalf("live saw %s, replay %s; want the same", describe(a.seen[0]), describe(a.seen[1])) + } +} + +// TestServiceResult_DecoderForOnDone_ArrivesAsTheDecodersType: a struct result whose +// onDone event has a decoder reaches the Assign as that struct, live and on replay. +func TestServiceResult_DecoderForOnDone_ArrivesAsTheDecodersType(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(scnUser{ID: 7, Name: "ann"}, nil), + decoderFor("done", durable.DecodeAs[scnUser])) + mustTwo(t, a, runErr, recErr) + for i, v := range a.seen { + if u, ok := v.(scnUser); !ok || u != (scnUser{ID: 7, Name: "ann"}) { + t.Errorf("seen[%d] = %s, want the scnUser", i, describe(v)) + } + } +} + +// TestServiceResult_Int64Above2to53_ExactWithADecoder: an int64 beyond float64's exact +// range survives when the decoder decodes it as an int64. +func TestServiceResult_Int64Above2to53_ExactWithADecoder(t *testing.T) { + const want = int64(1<<53 + 1) + a, runErr, recErr := scnRun(t, returning(want, nil), decoderFor("done", durable.DecodeAs[int64])) + mustTwo(t, a, runErr, recErr) + for i, v := range a.seen { + if n, ok := v.(int64); !ok || n != want { + t.Errorf("seen[%d] = %s, want int64 %d", i, describe(v), want) + } + } +} + +// TestServiceResult_StructWithInt64Above2to53_ExactWithADecoder: the same id inside a +// struct survives too. +func TestServiceResult_StructWithInt64Above2to53_ExactWithADecoder(t *testing.T) { + const want = int64(1<<53 + 1) + a, runErr, recErr := scnRun(t, returning(scnUser{ID: want, Name: "big"}, nil), + decoderFor("done", durable.DecodeAs[scnUser])) + mustTwo(t, a, runErr, recErr) + for i, v := range a.seen { + if u, ok := v.(scnUser); !ok || u.ID != want { + t.Errorf("seen[%d] = %s, want ID %d", i, describe(v), want) + } + } +} + +// TestServiceResult_SentinelError_ErrorsIs would have errors.Is match a wrapped +// sentinel in onError. Errors are message-only by design, so it can't. +func TestServiceResult_SentinelError_ErrorsIs(t *testing.T) { + t.Skip("service errors are message-only by design: onError gets an error with the same message, which errors.Is doesn't match") + a, runErr, recErr := scnRun(t, returning(nil, fmt.Errorf("lookup 7: %w", errScnNotFound))) + mustTwo(t, a, runErr, recErr) + for i, v := range a.seen { + if e, ok := v.(error); !ok || !errors.Is(e, errScnNotFound) { + t.Errorf("seen[%d] = %s, want an error matching errScnNotFound", i, describe(v)) + } + } +} + +// TestServiceResult_ErrorIsMessageOnly: a service error reaches onError as an error +// with the same message, live and on replay, and doesn't match the sentinel it wraps. +func TestServiceResult_ErrorIsMessageOnly(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(nil, fmt.Errorf("lookup 7: %w", errScnNotFound)), + decoderFor("fail", func([]byte) (any, error) { return nil, errors.New("an error must not reach the decoder") })) + mustTwo(t, a, runErr, recErr) + for i, v := range a.seen { + e, ok := v.(error) + if !ok || e.Error() != "lookup 7: user not found" || errors.Is(e, errScnNotFound) { + t.Errorf("seen[%d] = %s, want an error with the message only", i, describe(v)) + } + } +} + +// TestServiceResult_NoDecoder_StructIsAMap: with no decoder for onDone a struct +// arrives in JSON's generic form. +func TestServiceResult_NoDecoder_StructIsAMap(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(scnUser{ID: 7, Name: "ann"}, nil)) + mustTwo(t, a, runErr, recErr) + for i, v := range a.seen { + if _, ok := v.(map[string]any); !ok { + t.Errorf("seen[%d] = %T, want map[string]any", i, v) + } + } +} + +// TestServiceResult_NoDecoder_Int64IsFloat64: with no decoder for onDone an int64 +// arrives as a float64. +func TestServiceResult_NoDecoder_Int64IsFloat64(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(int64(42), nil)) + mustTwo(t, a, runErr, recErr) + for i, v := range a.seen { + if f, ok := v.(float64); !ok || f != 42 { + t.Errorf("seen[%d] = %s, want float64 42", i, describe(v)) + } + } +} + +// TestServiceResult_NoJSONForm_FailsTheHandle: a result with no JSON form fails the +// Handle and records nothing, so the recovered instance has the service in flight +// again. No Assign runs: the settle aborts before it fires anything, as for a result +// that won't decode (see TestServiceResult_NoJSONForm_RunsNoAssign). +func TestServiceResult_NoJSONForm_FailsTheHandle(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(make(chan int), nil), decoderFor("done", durable.DecodeAs[scnUser])) + if !errors.Is(runErr, durable.ErrHandleFailed) { + t.Errorf("RunService err = %v, want ErrHandleFailed", runErr) + } + if recErr != nil { + t.Errorf("Recover: %v", recErr) + } + if len(a.seen) != 0 { + t.Errorf("Assign ran %d times, want 0", len(a.seen)) + } +} + +// mustFailLoudly fails unless RunService returned ErrEventDataEncoding, parking the +// result with the Handle healthy, no Assign ran, and Recover found the service parked. +func mustFailLoudly(t *testing.T, a *scnAssigns, runErr, recErr error) { + t.Helper() + if errors.Is(runErr, durable.ErrHandleFailed) || !errors.Is(runErr, durable.ErrEventDataEncoding) { + t.Errorf("RunService err = %v, want ErrEventDataEncoding without ErrHandleFailed", runErr) + } + if recErr != nil { + t.Errorf("Recover: %v, want the instance recoverable", recErr) + } + if a.done != 0 || a.fails != 0 { + t.Errorf("onDone's Assign ran %d times and onError's %d, want neither", a.done, a.fails) + } +} + +// TestServiceResult_WrongDecoderType_Compatible_FailsLoudly: a decoder for the wrong +// type (scnAdmin for a scnUser result), whose JSON still decodes, is refused live. +func TestServiceResult_WrongDecoderType_Compatible_FailsLoudly(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(scnUser{ID: 7, Name: "ann"}, nil), + decoderFor("done", durable.DecodeAs[scnAdmin])) + mustFailLoudly(t, a, runErr, recErr) +} + +// TestServiceResult_WrongDecoderType_Incompatible_FailsLoudly: a decoder for a type +// the JSON won't decode as (int64 for an object) fails the step too. +func TestServiceResult_WrongDecoderType_Incompatible_FailsLoudly(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(scnUser{ID: 7, Name: "ann"}, nil), + decoderFor("done", durable.DecodeAs[int64])) + mustFailLoudly(t, a, runErr, recErr) +} + +// TestServiceResult_NilResult_ArrivesNil: a nil result arrives as nil both ways, +// whatever the decoder. +func TestServiceResult_NilResult_ArrivesNil(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(nil, nil), decoderFor("done", durable.DecodeAs[scnUser])) + mustTwo(t, a, runErr, recErr) + if a.seen[0] != nil { + t.Errorf("live saw %T, want nil", a.seen[0]) + } +} + +// TestServiceResult_DecoderAddedAfterRecording_ChangesReplay pins the documented hazard +// that makes the docs say to register the decoder before recording: a result recorded +// with no decoder, then recovered by a Runner that has one for onDone, reaches the +// replayed Assign as the decoder's type, though live saw JSON's generic form. The +// journal is the same JSON either way; replay decodes it with the decoder it has. +func TestServiceResult_DecoderAddedAfterRecording_ChangesReplay(t *testing.T) { + ctx := context.Background() + fn := returning(scnUser{ID: 7, Name: "ann"}, nil) + a := &scnAssigns{} + m := scnMachine(fn, a) + store := durable.NewMemStore() + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + h := scnStart(t, m, store, reg) + mustRunService(t, h, state.InvokeID(scnInvoke, "loading", 0)) + if _, err := durable.Recover(ctx, m, store, "scn-1", reg, decoderFor("done", durable.DecodeAs[scnUser])); err != nil { + t.Fatalf("Recover: %v", err) + } + if len(a.seen) != 2 { + t.Fatalf("Assign ran %d times, want 2 (live, replay)", len(a.seen)) + } + if _, ok := a.seen[0].(map[string]any); !ok { + t.Errorf("live saw %s, want map[string]any: no decoder was registered", describe(a.seen[0])) + } + // The hazard: replay hands the Assign a different type than live did. + if _, ok := a.seen[1].(scnUser); !ok { + t.Errorf("replay saw %s, want the scnUser the added decoder gives", describe(a.seen[1])) + } +} + +// failingDecoder fails for onDone and decodes every other event as JSON's own form. +func failingDecoder() durable.Option[string, string, svcCtx] { + return decoderFor("done", func([]byte) (any, error) { return nil, errors.New("decoder refused") }) +} + +// TestServiceResult_DecodeFailure_RunsNoOnErrorAssign proves a result that fails to +// decode, or decodes live as another type than the service returned, runs no Assign +// at all: neither onDone's nor onError's, not even once in memory. RunService returns +// ErrEventDataEncoding, the Handle stays healthy, the journal holds one Record that +// parks the result, and the instance stays where it was. +func TestServiceResult_DecodeFailure_RunsNoOnErrorAssign(t *testing.T) { + cases := []struct { + name string + opt durable.Option[string, string, svcCtx] + }{ + {"decoder fails", failingDecoder()}, + {"type mismatch", decoderFor("done", durable.DecodeAs[scnAdmin])}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + fn := returning(scnUser{ID: 7, Name: "ann"}, nil) + a := &scnAssigns{} + m := scnMachine(fn, a) + store := durable.NewMemStore() + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), tc.opt} + h := scnStart(t, m, store, opts...) + _, ran, err := h.RunService(ctx, state.InvokeID(scnInvoke, "loading", 0)) + mustPark(t, "RunService", ran, err) + if a.done != 0 || a.fails != 0 { + t.Fatalf("onDone's Assign ran %d times and onError's %d, want neither", a.done, a.fails) + } + if got := h.Instance().Current(); got != "loading" { + t.Fatalf("the live instance is in %q, want loading", got) + } + if _, recs, lerr := store.Load(ctx, "scn-1"); lerr != nil || len(recs) != 1 { + t.Fatalf("journal holds %d Records (err %v), want the one that parks the result", len(recs), lerr) + } + }) + } +} + +// TestServiceResult_RecordedResultThatWontDecode_RunsNoAssignOnReplay proves Recover and +// StateAt, replaying a recorded result their decoder can't decode, fail with +// ErrEventDataEncoding before any Assign runs. +func TestServiceResult_RecordedResultThatWontDecode_RunsNoAssignOnReplay(t *testing.T) { + ctx := context.Background() + fn := returning(scnUser{ID: 7, Name: "ann"}, nil) + a := &scnAssigns{} + m := scnMachine(fn, a) + store := durable.NewMemStore() + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + h := scnStart(t, m, store, reg) + mustRunService(t, h, state.InvokeID(scnInvoke, "loading", 0)) + if a.done != 1 || a.fails != 0 { + t.Fatalf("live: onDone ran %d times and onError %d, want 1 and 0", a.done, a.fails) + } + + if _, err := durable.Recover(ctx, m, store, "scn-1", reg, failingDecoder()); !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Recover: %v, want ErrEventDataEncoding", err) + } + if a.done != 1 || a.fails != 0 { + t.Fatalf("after Recover: onDone ran %d times and onError %d, want no more than live's 1 and 0", a.done, a.fails) + } + + if _, err := durable.StateAt(ctx, m, store, "scn-1", 0, reg, failingDecoder()); !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("StateAt: %v, want ErrEventDataEncoding", err) + } + if a.done != 1 || a.fails != 0 { + t.Fatalf("after StateAt: onDone ran %d times and onError %d, want no more than live's 1 and 0", a.done, a.fails) + } +} diff --git a/durable/result_nil_and_error_test.go b/durable/result_nil_and_error_test.go new file mode 100644 index 00000000..17167256 --- /dev/null +++ b/durable/result_nil_and_error_test.go @@ -0,0 +1,90 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +type tnQuote struct{ Price int } + +// TestRunService_ATypedNilResultKeepsItsType answers a review finding: a ServiceFn +// that returned a typed nil pointer reached onDone's Assign as an untyped nil, though a +// decoder for its onDone event decodes the pointer type, because a null result never +// reached the decoder. On main, durable passed the ServiceFn's own value live, so the +// Assign saw a (*tnQuote)(nil), and an untyped nil on replay. Now a typed nil result's +// null goes through the decoder, live and on replay alike, so DecodeAs[*tnQuote] hands +// the Assign a (*tnQuote)(nil) both times. +func TestRunService_ATypedNilResultKeepsItsType(t *testing.T) { + a, runErr, recErr := scnRun(t, returning((*tnQuote)(nil), nil), decoderFor("done", durable.DecodeAs[*tnQuote])) + mustTwo(t, a, runErr, recErr) + for i, when := range []string{"live", "on replay"} { + q, ok := a.seen[i].(*tnQuote) + if !ok || q != nil { + t.Fatalf("%s, onDone's Assign saw %s, want a nil *tnQuote", when, describe(a.seen[i])) + } + } +} + +// TestRunService_ATypedNilResultWithNoDecoderIsNil pins the default: with no decoder +// for its onDone event, a typed nil result arrives in JSON's generic form for null, an +// untyped nil, live and on replay. +func TestRunService_ATypedNilResultWithNoDecoderIsNil(t *testing.T) { + a, runErr, recErr := scnRun(t, returning((*tnQuote)(nil), nil)) + mustTwo(t, a, runErr, recErr) + if a.seen[0] != nil { + t.Fatalf("onDone's Assign saw %s, want an untyped nil", describe(a.seen[0])) + } +} + +// TestRunService_AnUntypedNilResultStaysNil pins that an untyped nil result arrives as +// an untyped nil, live and on replay, even with a decoder for its onDone event, which +// it doesn't reach. +func TestRunService_AnUntypedNilResultStaysNil(t *testing.T) { + called := 0 + dec := func(data []byte) (any, error) { + called++ + return durable.DecodeAs[*tnQuote](data) + } + a, runErr, recErr := scnRun(t, returning(nil, nil), decoderFor("done", dec)) + mustTwo(t, a, runErr, recErr) + if a.seen[0] != nil || called != 0 { + t.Fatalf("onDone's Assign saw %s, and the decoder ran %d times; want an untyped nil and no decode", describe(a.seen[0]), called) + } +} + +// TestRunService_AnUnboundServiceErrorIsMessageOnly pins a documented limit: errors are +// message-only, so onError's Assign sees a plain error with the message of an unbound +// service's *state.UnboundRefError, which errors.As doesn't match, live or on replay. +func TestRunService_AnUnboundServiceErrorIsMessageOnly(t *testing.T) { + ctx := context.Background() + a := &scnAssigns{} + m := scnMachine(returning(nil, nil), a) + store := durable.NewMemStore() + // The registry binds no "fetch", so the service settles as unbound. + opt := durable.WithServiceRegistry[string, string, svcCtx](state.NewRegistry[svcCtx]()) + h := scnStart(t, m, store, opt) + if _, _, err := h.RunService(ctx, state.InvokeID(scnInvoke, "loading", 0)); err != nil { + t.Fatalf("RunService: %v", err) + } + if _, err := durable.Recover(ctx, m, store, "scn-1", opt); err != nil { + t.Fatalf("Recover: %v", err) + } + if a.fails != 2 || len(a.seen) != 2 { + t.Fatalf("onError's Assign ran %d times (%v), want 2: live and on replay", a.fails, a.seen) + } + want := (&state.UnboundRefError{Kind: "service", Name: "fetch"}).Error() + for i, when := range []string{"live", "on replay"} { + err, ok := a.seen[i].(error) + if !ok || err.Error() != want { + t.Fatalf("%s, onError's Assign saw %s, want an error saying %q", when, describe(a.seen[i]), want) + } + var unbound *state.UnboundRefError + if errors.As(err, &unbound) { + t.Fatalf("%s, errors.As matched an *UnboundRefError, though errors are message-only", when) + } + } +} diff --git a/durable/result_type_check_test.go b/durable/result_type_check_test.go new file mode 100644 index 00000000..563dded7 --- /dev/null +++ b/durable/result_type_check_test.go @@ -0,0 +1,98 @@ +package durable_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests compare the type check a live service result passes with the one a +// Fire's WithEventData payload passes. Both decode through the Runner's +// EventDataDecoder; they differ in what they accept back. + +type tcOrder struct { + ID int64 + Items []string +} + +// useNumber decodes a payload as JSON's generic form, keeping numbers as json.Number +// so an integer keeps its precision. +func useNumber(data []byte) (any, error) { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + var v any + if err := dec.Decode(&v); err != nil { + return nil, err + } + return v, nil +} + +// fireDone fires "done" on a fresh scn instance with payload, and returns the error. +func fireDone(t *testing.T, payload any, opts ...durable.Option[string, string, svcCtx]) error { + t.Helper() + fn := returning(nil, nil) + m := scnMachine(fn, &scnAssigns{}) + opts = append([]durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))}, opts...) + h := scnStart(t, m, durable.NewMemStore(), opts...) + _, err := h.Fire(context.Background(), "done", state.WithEventData(payload)) + return err +} + +// TestTypeCheck_NoDecoder_ServiceResultIsAMap_FirePayloadIsRefused pins the documented +// asymmetry: with no decoder, a struct service result reaches Assign as JSON's generic +// form, a map, while a Fire carrying the same struct is refused. A Fire is refused +// before the kernel runs, so its caller can add a decoder and fire again; a service has +// already run, so refusing its result would only fail the step and run it again. +func TestTypeCheck_NoDecoder_ServiceResultIsAMap_FirePayloadIsRefused(t *testing.T) { + order := tcOrder{ID: 7, Items: []string{"tea"}} + a, runErr, recErr := scnRun(t, returning(order, nil)) + mustTwo(t, a, runErr, recErr) + if _, ok := a.seen[0].(map[string]any); !ok { + t.Fatalf("the service result reached Assign as %s, want map[string]any", describe(a.seen[0])) + } + if err := fireDone(t, order); !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Fire with the same struct: %v, want ErrEventDataEncoding", err) + } +} + +// TestTypeCheck_UseNumberDecoder_ServiceResult proves a decoder that keeps numbers as +// json.Number, a generic form, is accepted for a service result whatever its shape: an +// int arrives as a json.Number, as the same decoder's struct result arrives as a map +// holding json.Numbers. Before the fix the int was refused and the struct accepted. +func TestTypeCheck_UseNumberDecoder_ServiceResult(t *testing.T) { + t.Run("int", func(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(42, nil), decoderFor("done", useNumber)) + mustTwo(t, a, runErr, recErr) + if n, ok := a.seen[0].(json.Number); !ok || n.String() != "42" { + t.Fatalf("Assign saw %s, want json.Number 42", describe(a.seen[0])) + } + }) + t.Run("struct", func(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(tcOrder{ID: 7}, nil), decoderFor("done", useNumber)) + mustTwo(t, a, runErr, recErr) + m, ok := a.seen[0].(map[string]any) + if !ok { + t.Fatalf("Assign saw %s, want map[string]any", describe(a.seen[0])) + } + if _, ok := m["ID"].(json.Number); !ok { + t.Fatalf("the map's ID is %s, want json.Number", describe(m["ID"])) + } + }) +} + +// TestTypeCheck_UseNumberDecoder_FirePayloadIsRefused pins that a Fire stays strict: an +// int payload decoded as a json.Number isn't the type its caller passed, so the Fire is +// refused, as one decoded as a map is. +func TestTypeCheck_UseNumberDecoder_FirePayloadIsRefused(t *testing.T) { + if err := fireDone(t, 42, decoderFor("done", useNumber)); !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Fire with an int and a json.Number decoder: %v, want ErrEventDataEncoding", err) + } + if err := fireDone(t, tcOrder{ID: 7}, decoderFor("done", useNumber)); !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Fire with a struct and a json.Number decoder: %v, want ErrEventDataEncoding", err) + } +} diff --git a/durable/runner.go b/durable/runner.go index ffacf6da..d6471ad0 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "reflect" "slices" "sync" "time" @@ -141,9 +140,16 @@ type Handle[S comparable, E comparable, C any] struct { svc *state.ServiceRunner[S, E, C] // host driver for invoked services, nil when none wired svcBuf *[]state.JournalEntry // recording service-result accumulator, flushed per step + // svcJSON holds the JSON a successful settle decoded, which the step takes and + // journals; it holds nothing between steps. + svcJSON *settledJSON // settled holds the services that settled in the current activation of the state // that declares them, so a checkpoint records them and Recover doesn't start them. settled map[string]bool + // parked holds the results recorded parked, by service id: each didn't decode for + // its onDone event, so the service is still in flight, and RunService settles the + // result rather than run the ServiceFn again. A checkpoint records them. + parked map[string]recordedResult actors *state.ActorSystem[S, E, C] // host driver for child-machine actors, nil when none wired ended recordedSet // the ended actors the journal last recorded @@ -368,13 +374,14 @@ func (h *Handle[S, E, C]) absorbDrivers(ctx context.Context, event any, effects // state the settle enters arms whatever it declares, such as a service whose onDone // spawns an actor. The ServiceRunner absorbed those effects itself as it settled, so // absorbSettle doesn't hand them to it again, which would arm each service it starts a -// second time, where replay arms it once: it forgets the settled services the effects -// start or stop, and arms the timers, then the actors, in absorbDrivers' order. +// second time, where replay arms it once: it forgets the settled services and parked +// results the effects start or stop, and arms the timers, then the actors, in +// absorbDrivers' order. func (h *Handle[S, E, C]) absorbSettle(ctx context.Context, effects []state.Effect) { if hasTimerEffect(effects) { h.absorbTimers(ctx, effects) } - forgetSettled(h.settled, effects) + h.forgetServices(effects) h.absorbActors(ctx, nil, effects, nil) } @@ -387,12 +394,12 @@ func (h *Handle[S, E, C]) absorbRunners(ctx context.Context, event any, effects } // absorbServices feeds a transition's effects into the service runner, forgetting the -// settled services each service the effects start or stop. Tick calls it for each -// timer transition it fired, whose timers the scheduler already armed, before -// absorbActors for any of them: a timer that leaves a state stops its services, and one -// that enters a state starts them, as a Fire does. +// settled services and parked results of each service the effects start or stop. Tick +// calls it for each timer transition it fired, whose timers the scheduler already +// armed, before absorbActors for any of them: a timer that leaves a state stops its +// services, and one that enters a state starts them, as a Fire does. func (h *Handle[S, E, C]) absorbServices(ctx context.Context, effects []state.Effect) { - forgetSettled(h.settled, effects) + h.forgetServices(effects) if h.svc != nil { h.svc.Absorb(ctx, effects) } @@ -444,7 +451,7 @@ func (h *Handle[S, E, C]) absorbActors(ctx context.Context, event any, effects, // does. Replay arms them the same way, in the same order, so the clock reads match. ctx // is the context of the step that drove the system. func (h *Handle[S, E, C]) absorbParentFire(ctx context.Context, effects []state.Effect) { - forgetSettled(h.settled, effects) + h.forgetServices(effects) if hasTimerEffect(effects) { h.absorbTimers(ctx, effects) } @@ -511,9 +518,19 @@ func dropUnscheduled[S comparable, E comparable, C any](timers map[string]pendin } } +// forgetServices drops from the settled services and the parked results each service +// effects start or stop (see forgetSettled). +func (h *Handle[S, E, C]) forgetServices(effects []state.Effect) { + forgetSettled(h.settled, effects) + forgetSettled(h.parked, effects) +} + // forgetSettled removes from settled each service effects start or stop: a state that -// declares it was entered or exited, so the service is new or gone. -func forgetSettled(settled map[string]bool, effects []state.Effect) { +// declares it was entered or exited, so the service is new or gone. It forgets parked +// results the same way: a stopped service's parked result is discarded, and a service +// started again runs its ServiceFn. The Handle and the replay mirror call it for both +// maps at once, through forgetServices and armMirror.forget. +func forgetSettled[V any](settled map[string]V, effects []state.Effect) { if len(settled) == 0 { return } @@ -653,7 +670,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // no service entries. starts := inst.StartEffects() svcBuf := make([]state.JournalEntry, 0) - svc := r.newServiceRunner(inst) + svc, svcJSON := r.newServiceRunner(inst) if svc != nil { svc.Absorb(ctx, starts) } @@ -675,6 +692,7 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt timers: timers, svc: svc, svcBuf: &svcBuf, + svcJSON: svcJSON, actors: actors, actorFires: actorFires, lock: make(chan struct{}, 1), @@ -709,12 +727,13 @@ func (r *Runner[S, E, C]) Start(ctx context.Context, id InstanceID, input C, opt // newServiceRunner builds the kernel host driver for invoked services bound to // inst, or nil when no service registry was wired (a purely event/timer-driven -// machine invokes none). -func (r *Runner[S, E, C]) newServiceRunner(inst *state.Instance[S, E, C]) *state.ServiceRunner[S, E, C] { +// machine invokes none), and the holder of the JSON each settle decodes. +func (r *Runner[S, E, C]) newServiceRunner(inst *state.Instance[S, E, C]) (*state.ServiceRunner[S, E, C], *settledJSON) { if r.cfg.serviceReg == nil { - return nil + return nil, nil } - return state.NewServiceRunner(inst, r.cfg.serviceReg).WithResultTransform(replayableOutcome) + settled := &settledJSON{} + return state.NewServiceRunner(inst, r.cfg.serviceReg).WithResultTransform(replayableOutcome(r.cfg.eventDataDecoder, settled)), settled } // newActorSystem builds the kernel host driver for child-machine actors bound to @@ -1144,14 +1163,15 @@ func (h *Handle[S, E, C]) finishStep(ctx context.Context, rec *Record, des []dis // 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. +// actor system too, as a Fire's do: a timer that leaves a state stops its services, +// discarding a parked result, 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 @@ -1382,6 +1402,7 @@ func (h *Handle[S, E, C]) appendStep(ctx context.Context, step int, rec *Record) EndedActors: ended, UnstartedActors: unstarted, EndedServices: h.endedServices(), + ParkedServices: h.parkedServices(), Format: journalFormat, }, h.timers) if err != nil { @@ -1522,6 +1543,35 @@ func (h *Handle[S, E, C]) endedServices() []string { return slices.Compact(ids) } +// parkedServices returns the parked results of the services the active states declare, +// sorted by service id, for a checkpoint. It is nil with none parked. A Handle with no +// service registry keeps the ones it recovered, so a later Recover with the registry +// settles them rather than run their ServiceFns again. +func (h *Handle[S, E, C]) parkedServices() []parkedServiceWire { + if len(h.parked) == 0 { + return nil + } + var ids []string + for _, eff := range h.inst.StartEffects() { + if sv, ok := eff.(state.StartService); ok { + if _, parked := h.parked[sv.ID]; parked { + ids = append(ids, sv.ID) + } + } + } + if len(ids) == 0 { + return nil + } + slices.Sort(ids) + ids = slices.Compact(ids) + out := make([]parkedServiceWire, len(ids)) + for i, id := range ids { + p := h.parked[id] + out[i] = parkedServiceWire{ID: id, Result: p.raw, Type: p.typ} + } + return out +} + // declaredActors returns the ids of the actors effects spawn. func declaredActors(effects []state.Effect) []string { var ids []string @@ -1612,9 +1662,12 @@ func (h *Handle[S, E, C]) respawn(ctx context.Context, effects []state.Effect, u // effect not yet marked dispatched, so it returns ErrEffectDispatch and no Handle while // the effect handler keeps failing. With an effect handler wired, it refuses a Store // that isn't a DispatchStore with ErrNoDispatchStore before it loads anything, whether -// or not an effect is waiting. 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. +// or not an effect is waiting. It refuses a journal a newer version of this module +// wrote, whose checkpoint or any Record records a journal format above this version's, +// before it restores or replays anything; that error wraps none of the package's +// sentinel errors. It re-arms the checkpoint's timers before replaying the tail, and +// fails when a tick of journal format 3 or later fires a different number of timers on +// replay than it recorded. func Recover[S comparable, E comparable, C any](ctx context.Context, m *state.Machine[S, E, C], st Store, id InstanceID, opts ...Option[S, E, C]) (*Handle[S, E, C], error) { r := NewRunner(m, st, opts...) return r.recover(ctx, id) @@ -1640,6 +1693,14 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // deadlines of the timers armed at the checkpoint, and the next step ordinal. A bare // (pre-envelope) checkpoint yields the snapshot with no persisted timers. env := unmarshalCheckpoint(snapBytes) + if err = checkNotNewer(id, env.Format, tail); err != nil { + return nil, err + } + // Refuse a journal mixed versions wrote before replaying any of it, so a refused one + // sends no effect. + if err = checkFormats(env.Format, tail); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } kernelSnap, persistedTimers, checkpointNext := env.Snapshot, env.Timers, env.NextStep snap, err := state.UnmarshalSnapshot[S, E, C](kernelSnap) @@ -1669,7 +1730,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S restoredStarts := inst.StartEffects() endedServices := env.EndedServices svcBuf := make([]state.JournalEntry, 0) - svc := r.newServiceRunner(inst) + svc, svcJSON := r.newServiceRunner(inst) if svc != nil { svc.Absorb(ctx, startsExcept(restoredStarts, endedServices, func(sv state.StartService) string { return sv.ID })) } @@ -1695,6 +1756,11 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S for _, sv := range endedServices { mirror.settle(sv) } + // A result parked at the checkpoint is still parked: its service is armed above, in + // flight, and RunService settles the result rather than run the ServiceFn again. + for _, p := range env.ParkedServices { + mirror.park(p.ID, recordedResult{raw: p.Result, typ: p.Type}) + } // Re-arm the timers pending at the checkpoint before the tail replays, because the // tail can fire them. Their deadlines are absolute, so any fixed instant works as the @@ -1733,9 +1799,6 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // The mirror tracks the still-pending timers in armed as replay arms, cancels and // fires them, with deadlines drawn from the recorded clock reads, not the live // wall clock. - if err := checkFormat(env.Format, rec); err != nil { - return nil, fmt.Errorf("durable: recovering %q: %w", id, err) - } reads += clockReadCount(rec) stepEffects, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, mirror, armsActorFires(rec)) if err != nil { @@ -1776,6 +1839,8 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // clock: an older journal can leave one, such as a settle's read it put in the next // Record. repClock.skipTo(reads) + // The replayed settles left the JSON the last one decoded, which no step journals. + svcJSON.take() // Drain any clock readings the replay re-recorded after the cursor exhausted // (none in the common case where replay consumes exactly the recorded @@ -1821,7 +1886,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S timers: armed, svc: svc, svcBuf: &svcBuf, + svcJSON: svcJSON, settled: mirror.settled, + parked: mirror.parked, actors: actors, actorFires: actorFires, lock: make(chan struct{}, 1), @@ -1926,9 +1993,8 @@ func encodeEventData[E comparable](event E, opts []state.FireOption, maxBytes in return payload, nil, fmt.Errorf("%w: %w", ErrEventDataEncoding, err) } if !isErr { - if got, want := reflect.TypeOf(value), reflect.TypeOf(data); got != want { - return payload, nil, fmt.Errorf("%w: a %v payload decodes as %v; decode it as %v with WithEventDataDecoder", - ErrEventDataEncoding, want, got, want) + if err := decodedAsPassed(value, data, "payload", false); err != nil { + return payload, nil, err } } live := make([]state.FireOption, 0, len(opts)+1) @@ -1984,19 +2050,24 @@ func eventDataTooLarge(size, maxBytes int) error { // decode returns the payload as a Fire sees it, live and when a replay re-Fires the // step: an error payload as an error with its message, and data through decode. -func decodePayload[E comparable](p eventPayload, event E, decode EventDataDecoder[E]) (v any, err error) { +func decodePayload[E comparable](p eventPayload, event E, decode EventDataDecoder[E]) (any, error) { if p.errMsg != nil { return errors.New(*p.errMsg), nil } if string(p.data) == "null" { // a nil payload stays nil, whatever the decoder return nil, nil } + return decodeData(event, p.data, decode) +} + +// decodeData returns data through decode, or an error if decode panics. +func decodeData[E comparable](event E, data []byte, decode EventDataDecoder[E]) (v any, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("event data decoder panicked: %v", r) } }() - return decode(event, p.data) + return decode(event, data) } // EventDataDecoder rebuilds a state.WithEventData payload from its recorded JSON form, @@ -2176,7 +2247,8 @@ func resultErrs[S comparable](results []state.FireResult[S]) []error { // - A service settlement re-settles each recorded outcome through the same settle // seam, in settle order; the settle absorbs its own follow-on StartService // effects, so a chained invoke arms its successor for the next entry, and its -// timers are re-armed as RunService armed them. +// timers are re-armed as RunService armed them. A parked result settles nothing: +// its service stays in flight, and mirror keeps the result for RunService. // - A tick barrier ticks the replay clock, which returns the recorded readings, so // the same deadlines come due and the same timers fire at their recorded instants. // Each fired transition starts or stops its services, as the live Tick did, for a @@ -2226,7 +2298,20 @@ func replayRecord[S comparable, E comparable, C any]( stepEffects = res.Effects case hasServiceEntry(rec): for _, entry := range serviceEntries(rec) { - effects, err := replayService(ctx, svc, entry) + sp, err := decodeServiceEntry(entry) + if err != nil { + return stepEffects, fmt.Errorf("at step %d: %w", rec.Step, err) + } + if sp.Parked { + // Live, the result didn't decode, so nothing settled: park it again, for + // RunService to settle. Its service stays in flight. + if err = replayPark(svc, entry); err != nil { + return stepEffects, fmt.Errorf("at step %d: %w", rec.Step, err) + } + mirror.park(entry.CorrelationID, recordedResult{raw: sp.Result, typ: sp.Type}) + continue + } + effects, err := replayService(ctx, svc, entry, sp, rec.Format >= decodedResultsFormat) if err != nil { return stepEffects, fmt.Errorf("at step %d: %w", rec.Step, err) } @@ -2299,20 +2384,54 @@ func replayActors[S comparable, E comparable, C any]( return nil } -// checkFormat fails when rec's journal Format is lower than the checkpoint's that replay -// started from: a version doesn't write an older format than it did, so the Store lost -// the field, and replaying the Record as an older format's would recover wrong. -func checkFormat(checkpoint int, rec *Record) error { - if rec.Format < checkpoint { - return fmt.Errorf("durable: step %d records journal format %d after a checkpoint of format %d: the Store didn't keep Record.Format", rec.Step, rec.Format, checkpoint) +// checkFormats fails when a Record in records has a lower journal Format than the +// checkpoint's that replay starts from, or than any Record before it (see checkFormat). +// A journal's format never goes down, so this catches an older version's Record +// appended after a newer one's anywhere in the tail, not only after a newer checkpoint. +// Recover calls it on its tail, and StateAt and Steps on every Record they load, past +// the step StateAt targets too, before any of them replays one. +func checkFormats(checkpoint int, records []Record) error { + highest := checkpoint + for i := range records { + if err := checkFormat(highest, &records[i]); err != nil { + return err + } + highest = max(highest, records[i].Format) } return nil } -// armsActorFires reports whether rec was written by a version that arms the timers and -// services an actor-driven parent Fire declares, from the journal Format it records. -func armsActorFires(rec *Record) bool { - return rec.Format >= actorArmsFormat +// checkFormat fails when rec's journal Format is lower than highest, the highest format +// the journal records before it: the checkpoint's, or an earlier Record's. A version +// doesn't write an older format than it did, so either an older version appended rec to +// a journal a newer one wrote, which a rolling deploy that runs mixed versions on one +// instance does, or, for a Record with no format, the Store lost the field. Either way +// the two versions may read the journal differently (an older one settles a parked +// result, for one), so replaying rec by its own format's rules would recover wrong. +func checkFormat(highest int, rec *Record) error { + switch { + case rec.Format >= highest: + return nil + case rec.Format == 0: + return fmt.Errorf("durable: step %d records no journal format after one of format %d: the Store didn't keep Record.Format, or a version from before that field appended the Record (mixed versions on one instance)", rec.Step, highest) + } + return fmt.Errorf("durable: step %d was appended by an older version, of journal format %d, after one of format %d: don't run mixed versions on one instance", rec.Step, rec.Format, highest) +} + +// checkNotNewer fails when id's checkpoint, of journal format checkpoint, or any of its +// records was written in a journal format above journalFormat: by a newer version, whose +// journal this version can't tell from its own, so replaying it could recover wrong. +// Every reader calls it on what it loaded before it restores or replays anything. The +// error wraps no sentinel. +func checkNotNewer(id InstanceID, checkpoint int, records []Record) error { + format := checkpoint + for i := range records { + format = max(format, records[i].Format) + } + if format > journalFormat { + return fmt.Errorf("durable: %q was written by a newer version (journal format %d; this version reads up to %d)", id, format, journalFormat) + } + return nil } // sendsReplayedEffects reports whether Recover sends the domain effects replaying rec @@ -2323,8 +2442,16 @@ func sendsReplayedEffects(rec *Record) bool { return len(rec.Event) > 0 || rec.Format >= dispatchedStepsFormat } -// journalFormat is the format this version writes in every Record and checkpoint. It is -// timersFirstFormat. actorArmsFormat is the first format that arms the timers and +// armsActorFires reports whether rec was written by a version that arms the timers and +// services an actor-driven parent Fire declares, from the journal Format it records. +func armsActorFires(rec *Record) bool { + return rec.Format >= actorArmsFormat +} + +// journalFormat is the format this version writes in every Record and checkpoint, and +// the highest it reads: Recover, the stateless Fire, StateAt and Steps refuse a journal +// whose checkpoint or any Record records a higher one (see checkNotNewer). It is +// decodedResultsFormat. actorArmsFormat is the first format that arms the timers and // services an actor-driven parent Fire's state declares. dispatchedStepsFormat is the // first that dispatches a tick's and a service settle's domain effects, so Recover sends // them. tickDriversFormat is the first whose Tick hands its timer transitions' effects @@ -2333,12 +2460,17 @@ func sendsReplayedEffects(rec *Record) bool { // before the tail, so its replayed ticks fire exactly the timers they record. An older // version's recovery re-armed them after the tail, so a journal it continued can record // a tick replay can't reproduce: a timer the tail had fired or canceled, fired again. +// decodedResultsFormat is the first whose service results the live run decoded through +// WithEventDataDecoder, so replay decodes them the same way; it is also the first that +// can park a result. A result in a Record of an older format replays as that version +// replayed it, in JSON's generic form. const ( actorArmsFormat = 1 dispatchedStepsFormat = 2 tickDriversFormat = 2 timersFirstFormat = 3 - journalFormat = timersFirstFormat + decodedResultsFormat = 4 + journalFormat = decodedResultsFormat ) // replayArm arms the timers and services a replayed Fire's effects declare, as the live @@ -2353,8 +2485,9 @@ func replayArm[S comparable, E comparable, C any](ctx context.Context, sched *st } // replayRunners starts or stops the services a replayed transition's effects declare, -// and forgets the settles of each, as the live absorbRunners did. Replay runs no actor: -// Recover spawns the actors of the states it ends in. svc may be nil. +// and forgets the settles and parked results of each, as the live absorbRunners did. +// Replay runs no actor: Recover spawns the actors of the states it ends in. svc may be +// nil. func replayRunners[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], effects []state.Effect, mirror *armMirror) { mirror.forget(effects) if svc != nil { @@ -2371,9 +2504,22 @@ type armMirror struct { armed map[string]pendingTimer clock *replayClock settled map[string]bool + parked map[string]recordedResult // the results parked and not yet settled, by service id +} + +// park notes that the replayed journal parked the result of service id. +func (m *armMirror) park(id string, r recordedResult) { + if m == nil { + return + } + if m.parked == nil { + m.parked = map[string]recordedResult{} + } + m.parked[id] = r } -// settle notes that a replayed settle settled the service id. +// settle notes that a replayed settle settled the service id, so no result of it is +// parked, as Handle.markSettled does live. func (m *armMirror) settle(id string) { if m == nil { return @@ -2382,15 +2528,17 @@ func (m *armMirror) settle(id string) { m.settled = map[string]bool{} } m.settled[id] = true + delete(m.parked, id) } -// forget drops from the settled services each one a replayed Fire's effects start or -// stop, as the live step did. +// forget drops from the settled services and the parked results each one a replayed +// Fire's effects start or stop, as the live step did. func (m *armMirror) forget(effects []state.Effect) { if m == nil { return } forgetSettled(m.settled, effects) + forgetSettled(m.parked, effects) } // arm folds a replayed absorb's timer effects into the table, at the reading the diff --git a/durable/runner_options.go b/durable/runner_options.go index 1c3cb3d5..8ca3e835 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -186,6 +186,23 @@ func WithMaxEventDataBytes[S comparable, E comparable, C any](n int) Option[S, E // 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. +// +// The decoder also decodes a service's result, for the invocation's onDone event, live +// in RunService and on every replay. A result whose onDone event the decoder covers +// arrives as the decoder's type; otherwise it arrives in JSON's generic form, a struct +// as a map[string]any and a number as a float64. A decoder that fails on a result, or +// returns a type other than the service returned, parks the result: RunService returns +// ErrEventDataEncoding before any onDone or onError Assign runs, records the result +// without settling it, and keeps the Handle healthy. Recover with the fixed decoder, +// then call RunService, to settle the parked result without running the service again; +// the Handle that parked it never sees the fix (see Handle.RunService). The settling +// decoder must return the type the service returned, by import path and name, or JSON's +// generic form, so a type moved or renamed after the park settles only through a decoder +// that returns the generic form. A service error stays message-only and +// doesn't reach the decoder. Register the decoder before results are recorded: replay +// decodes the journal with the recovering Runner's decoder, so one added or changed +// after results were recorded changes what replay produces, and one that can't decode +// a settled result fails Recover and StateAt with ErrEventDataEncoding. func WithEventDataDecoder[S comparable, E comparable, C any](d EventDataDecoder[E]) Option[S, E, C] { return func(c *runnerConfig[S, E, C]) { if d != nil { diff --git a/durable/service.go b/durable/service.go index 8a19ecb5..bd0d83ae 100644 --- a/durable/service.go +++ b/durable/service.go @@ -5,6 +5,9 @@ import ( "encoding/json" "errors" "fmt" + "reflect" + "strconv" + "strings" "github.com/stablekernel/crucible/state" ) @@ -24,18 +27,21 @@ import ( // replay against the kernel rather than a re-execution of the host's services. A result // that wasn't recorded, after a context canceled during the service, a crash, or a failed // Append whose write didn't land, has nothing to replay, so it stays in flight, runs again -// when the host calls RunService, and must tolerate a second run. +// when the host calls RunService, and must tolerate a second run. A result that won't +// decode for its onDone event is recorded parked: nothing settles, replay parks it +// again, and a later RunService settles it, once the decoder decodes it, without +// running the service again. // // The Runner wraps the kernel's reusable host driver, state.ServiceRunner, which // turns StartService / StopService effects into real ServiceFn executions and // re-fires each result through the invocation's onDone / onError event. On the live -// path RunService delegates to ServiceRunner.Tick (resolve + run + settle), reads -// the outcome in its JSON-decoded form, and journals it as a JournalServiceResult -// correlated by the invocation id. On recovery the recorded outcomes are replayed -// in order through ServiceRunner.SettleDone / SettleError — the same settle methods -// the live run drove — so the kernel re-fires the identical onDone / onError event -// with the identical data and re-derives byte-identical context, having run no -// service. +// path RunService delegates to ServiceRunner.Tick (resolve + run + settle), keeps the +// JSON the settle decoded the outcome from (see replayableOutcome), and journals it as +// a JournalServiceResult correlated by the invocation id. On recovery the recorded +// outcomes are replayed in order through ServiceRunner.SettleDone / SettleError — the +// same settle methods the live run drove — so the kernel re-fires the identical onDone +// / onError event with the identical data and re-derives byte-identical context, +// having run no service. // // # Correlation and ordering // @@ -53,14 +59,39 @@ import ( // whichever is present and settles the invocation through the matching seam. type serviceResultPayload struct { // Result is the JSON-encoded successful return of the ServiceFn, present for a - // SettleDone outcome. It is decoded to a Go value and re-fired through onDone so - // the transition's Assign reads it from AssignCtx.Event exactly as on the live - // run, which settles with the same decoded form (see replayableOutcome). + // SettleDone outcome: the bytes the live settle decoded. Replay decodes them through + // the Runner's EventDataDecoder for the onDone event and re-fires them through + // onDone, so the transition's Assign reads from AssignCtx.Event the value the live + // run's decode gave (see replayableOutcome). A Record of a format before + // decodedResultsFormat replays them in JSON's generic form, as the version that + // wrote it did. Result json.RawMessage `json:"result,omitempty"` // Error is the failure message for a SettleError outcome. It is reconstructed // into an error and re-fired through onError so the transition's Assign reads it // from AssignCtx.Event. Error *string `json:"error,omitempty"` + // Parked marks a result that didn't decode for its onDone event: it is recorded so + // the ServiceFn never runs again, but it didn't settle. Replay parks it again rather + // than settling it, and a later RunService settles it once the decoder decodes it. + // An older Record never sets it. + Parked bool `json:"parked,omitempty"` + // Type is a result's Go type, with its import path (see typeName): the type the + // ServiceFn returned. A parked result records it so the RunService that settles it + // holds the decoder to that type, as the live settle did, and every successful + // settle records it, the one that settles a parked result too, so replay holds the + // decoder to it as the settle did. It is empty for an error, and for a result + // recorded before this field, which replays with no type check. + Type string `json:"type,omitempty"` +} + +// decodeServiceEntry decodes a recorded service outcome's payload, once for replay to +// park or settle it. +func decodeServiceEntry(e state.JournalEntry) (serviceResultPayload, error) { + var sp serviceResultPayload + if err := json.Unmarshal(e.Payload, &sp); err != nil { + return sp, fmt.Errorf("durable: decoding recorded service %q outcome: %w", e.CorrelationID, err) + } + return sp, nil } // drainServices returns and clears the service outcomes recorded since the last @@ -82,54 +113,93 @@ func (h *Handle[S, E, C]) drainServices() []state.JournalEntry { // 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, +// re-invoking the service. The outcome reaches the machine decoded from its JSON form, +// live as on replay, and the journal holds the JSON the live settle decoded, so replay +// decodes the same bytes. A result whose onDone event +// WithEventDataDecoder covers arrives as the decoder's type; otherwise it arrives in +// JSON's generic form: a struct is a map, an integer a float64 that loses precision +// above 2^53. A typed nil result, such as a nil pointer, goes through the decoder as +// JSON's null, so DecodeAs[*T] hands Assign a nil *T, live and on replay; with no +// decoder it arrives as an untyped nil, and an untyped nil result arrives as one +// without reaching the decoder. (A WithEventData payload that is a typed nil is refused +// instead, as EventDataDecoder says: a Fire can be retried with an untyped nil, but a +// service has already run.) 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. +// *state.UnboundRefError. The journal records the Go type the service returned, +// and replay holds the decoder to it, as the live settle did: a decoder that returns +// another type fails Recover and StateAt with ErrEventDataEncoding, though JSON's +// generic form and nil are always accepted. Register the decoder before results are +// recorded: changing the type a decoder returns for an event whose results are +// recorded fails Recover on them, unless it returns the generic form, and a decoder +// added later for the service's type changes what replay produces. // // 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. +// names no in-flight service (already settled, stopped, or never started). The bool +// says whether the service was in flight and ran, not whether it settled: a parked +// result returns true, and so does a settle that finds the activation the ServiceFn +// ran for stopped, or stopped and armed again, while it ran, which returns the zero +// result and no error and records nothing, since nothing fired. The step lock keeps +// durable's own steps from doing that, so only code that drives the ServiceRunner past +// the Handle can. 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 +// Once the service has run, it returns true with any error. A result the decoder for +// its onDone event can't decode, such as a number beyond float64, or decodes as a type +// other than the service returned, is parked: RunService records the result as the +// ServiceFn returned it, with its Go type, settles nothing, and returns +// ErrEventDataEncoding, not ErrHandleFailed, before any onDone or onError Assign runs. +// The Handle stays healthy and the service stays in flight, on this Handle and on a +// recovered one, but its ServiceFn never runs again. The decoder is part of the +// Runner's options, so this Handle never sees a fix: Recover with the fixed decoder, +// then call RunService, and it settles the parked result. The decoder must return the +// recorded type, by import path and name, or JSON's generic form: after the type is +// moved or renamed, only a decoder that returns the generic form settles it, so settle +// parked results before such a move. Until then each RunService returns +// ErrEventDataEncoding and records nothing more. The Handle that parked the result also +// holds the decoder to the type itself, as the live settle did; a recovered one has +// only the name, which two types of one package can share, such as two function-local +// types. A Fire or timer that leaves +// the state that declares the service stops it and discards the parked result; one that +// enters the state again starts a new activation, whose ServiceFn runs. A checkpoint +// keeps the parked result, and StateAt shows the instance as it was before the park. +// +// A result that won't encode, a ctx that ended during the service (whether or not the +// result decodes) 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. +// result that won't encode runs no Assign, as one that won't decode doesn't. 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 +// the result is recorded; on a step that parked its result, joined with the +// ErrEventDataEncoding. 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. func (h *Handle[S, E, C]) RunService(ctx context.Context, id string) (state.FireResult[S], bool, error) { if err := h.acquire(ctx); err != nil { return state.FireResult[S]{}, false, err } res, ran, rec, des, err := h.lockedServiceStep(ctx, id) - if err != nil || rec == nil { + if rec == nil { return res, ran, err } - // Dispatch after releasing the step lock, as Fire does. - return res, true, h.finishStep(ctx, rec, des) + // Dispatch after releasing the step lock, as Fire does. A step that parked its + // result is recorded and returns why it parked; it offers its checkpoint as any + // step does. + ferr := h.finishStep(ctx, rec, des) + if err == nil { + return res, true, ferr + } + if ferr != nil { + return res, true, errors.Join(err, ferr) + } + return res, true, err } // lockedServiceStep runs serviceStep and releases the step lock however it returns. A @@ -154,14 +224,47 @@ func (h *Handle[S, E, C]) serviceStep(ctx context.Context, id string) (state.Fir return state.FireResult[S]{}, false, nil, nil, nil } - results := h.svc.Tick(h.stepContext(ctx), id) - if len(results) == 0 { - return state.FireResult[S]{}, false, nil, nil, nil + // A parked result settles in place of a run: the ServiceFn ran once, and the journal + // holds what it returned. + parked, isParked := h.parked[id] + var res state.FireResult[S] + routed := true + if isParked { + res, routed = h.svc.SettleDone(h.stepContext(ctx), id, parked) + } else if results := h.svc.Tick(h.stepContext(ctx), id); len(results) > 0 { + res = results[0] + } else { + // HasPending found the service in flight, so the ServiceFn ran: Tick returns + // nothing only when its activation was stopped, or stopped and armed again, + // before the settle. + routed = false + } + // The JSON this settle decoded is the step's alone: take it, so no later step can + // journal it and the Handle doesn't hold it. + settled := h.svcJSON.take() + if derr := (*undecodableResult)(nil); errors.As(res.Err, &derr) { + // The result didn't decode for its onDone event, so the transform aborted the + // settle: nothing fired and no Assign ran. Park it, unless a context that ended + // during the service may have cut the result short: as for a result that + // settles, that records nothing, and Recover runs the service again. + if !isParked { + if err := stepCanceled(ctx); err != nil { + return state.FireResult[S]{}, true, nil, nil, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, err)) + } + } + return h.parkResult(ctx, id, derr, isParked) + } + if !routed { + // The activation the ServiceFn ran for was stopped, or stopped and armed again, + // before the settle: nothing fired, so there is nothing to record, and a new + // activation stays in flight. The step lock keeps any other step from doing that + // while this one runs, so only code that drives the ServiceRunner past the Handle + // can. It reports true: the service was in flight and its ServiceFn ran. + return state.FireResult[S]{}, true, nil, nil, nil } - res := results[0] // The service settled: unless the settle's own Fire leaves or re-enters the state // that declares it, which the absorb below notes, a checkpoint records it as settled. - h.noteSettled(id) + h.markSettled(id) // The settle re-fired the invocation's onDone / onError, which may enter a state // that arms a timer, starts another service, or spawns an actor. The ServiceRunner @@ -182,7 +285,7 @@ func (h *Handle[S, E, C]) serviceStep(ctx context.Context, id string) (state.Fir return res, true, nil, nil, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, err)) } - entry, err := recordServiceOutcome(id, h.svc.LastResult, h.svc.LastError()) + entry, err := recordServiceOutcome(id, settled, h.svc.LastError()) if err != nil { return res, true, nil, nil, h.fail(fmt.Errorf("durable: recording service %q result for %q: %w", id, h.id, err)) } @@ -208,63 +311,419 @@ func (h *Handle[S, E, C]) serviceStep(ctx context.Context, id string) (state.Fir return res, true, rec, des, nil } -// noteSettled records that the service id settled in its state's current activation. -func (h *Handle[S, E, C]) noteSettled(id string) { +// parkResult parks the result of service id that derr says didn't decode for its +// onDone event: it records the result's JSON and Go type in a Record of its own, so the +// ServiceFn never runs again, and keeps it for the next RunService of id to settle. The +// service stays in flight in the ServiceRunner and the Handle stays healthy. It returns +// the Record, which the caller finishes as any step's, and an error wrapping +// ErrEventDataEncoding that says the result is parked. A result already parked +// (already) is in the journal, so it records nothing. A result with no JSON form, which +// the transform aborted with no raw to record, fails the Handle, which leaves the +// service in flight for a recovered Handle to run again. +func (h *Handle[S, E, C]) parkResult(ctx context.Context, id string, derr *undecodableResult, already bool) (state.FireResult[S], bool, *Record, []dispatchableEffect, error) { + parkErr := fmt.Errorf("durable: settling service %q for %q: its result is parked until RunService can decode it: %w", id, h.id, derr) + if already { + return state.FireResult[S]{}, true, nil, nil, parkErr + } + if derr.raw == nil { + return state.FireResult[S]{}, true, nil, nil, h.fail(fmt.Errorf("durable: settling service %q for %q: %w", id, h.id, derr)) + } + payload, err := json.Marshal(serviceResultPayload{Result: derr.raw, Parked: true, Type: derr.typ}) + if err != nil { + return state.FireResult[S]{}, true, nil, nil, h.fail(fmt.Errorf("durable: recording service %q result for %q: %w", id, h.id, err)) + } + // Keep it before the Record is appended, so a checkpoint the step makes due carries + // it. A failed append fails the Handle, so a parked result it didn't record is never + // settled. + if h.parked == nil { + h.parked = map[string]recordedResult{} + } + h.parked[id] = recordedResult{raw: derr.raw, typ: derr.typ, rtype: derr.rtype} + entry := state.JournalEntry{Kind: state.JournalServiceResult, CorrelationID: id, Payload: payload} + rec := &Record{Step: h.nextStep, Entries: append(h.drainClock(), entry)} + if _, err := h.recordStep(ctx, rec, nil); err != nil { + return state.FireResult[S]{}, true, nil, nil, err + } + return state.FireResult[S]{}, true, rec, nil, parkErr +} + +// markSettled records that the service id settled in its state's current activation, so +// no result of it is parked. It and forgetServices are the only writers of settled +// alongside parked, so the two can't disagree. +func (h *Handle[S, E, C]) markSettled(id string) { if h.settled == nil { h.settled = map[string]bool{} } h.settled[id] = true + delete(h.parked, id) } -// replayableOutcome gives a service's outcome the form a replay supplies, so the live -// settle and a replay can't differ: a result in its JSON-decoded form, and an error as -// an error with its message as a Store keeps it (see normalizedErrorMessage). An Error -// method that panics settles with a message saying so, normalized the same way. A -// result with no JSON form is left as it is, and one whose JSON form won't decode is -// marked undecodableResult; recording either fails the Handle, so the step records -// nothing and a recovered Handle runs the service again. -func replayableOutcome(result any, err error) (any, error) { - if err != nil { - msg, perr := normalizedErrorMessage(err, "service error") - if perr != nil { - msg = validUTF8(perr.Error()) +// replayableOutcome returns the transform a ServiceRunner applies to every outcome as +// it settles, so the live settle and a replay can't differ. A result is encoded to +// JSON and decoded through decode for the invocation's onDone event, as a +// WithEventData payload is: the live run passes the ServiceFn's value, a replay the +// recorded JSON as a recordedResult, and both get decode's value. With the default +// decoder that is JSON's generic form. Live, a decoder that returns a concrete type +// other than the result's is refused, though JSON's generic form, including a +// json.Number, is always accepted, so the default keeps working. A settle that +// succeeds leaves in settled the JSON it decoded and the result's Go type, which +// serviceStep journals, so replay decodes the bytes live decoded and holds the decoder +// to the type live did; an error outcome leaves nothing there. +// +// A result that won't decode, or is refused, aborts the settle with an +// *undecodableResult before it fires anything, so no onDone or onError Assign runs; +// serviceStep sees it in the settle's FireResult.Err and parks the result, and +// replayService fails the replay. A parked result settles as a recordedResult that +// carries its Go type, and the decoder must return that type, or JSON's generic form, +// as live. A result with no JSON form aborts the settle too, with no JSON to park, and +// serviceStep fails the Handle. A legacyResult, which replay passes for a Record of an +// older format, settles as it is, as that version replayed it. +// +// An error becomes an error with its message as a Store keeps it (see +// normalizedErrorMessage), live and on replay. An Error method that panics settles +// with a message saying so, normalized the same way. +func replayableOutcome[E comparable](decode EventDataDecoder[E], settled *settledJSON) func(E, any, error) (any, error, error) { + return func(event E, result any, err error) (any, error, error) { + settled.set(recordedResult{}) + if err != nil { + msg, perr := normalizedErrorMessage(err, "service error") + if perr != nil { + msg = validUTF8(perr.Error()) + } + return nil, errors.New(msg), nil + } + if legacy, ok := result.(legacyResult); ok { + return legacy.value, nil, nil + } + recorded, replay := result.(recordedResult) + b := []byte(recorded.raw) + if !replay { + var jerr error + if b, jerr = marshalPayload(result); jerr != nil { + return nil, nil, &undecodableResult{err: fmt.Errorf("service result won't encode: %w", jerr)} + } + } + var value any + var derr error + if typedNil(b, recorded, replay, result) { + // A typed nil keeps its type through the decoder, live and on replay alike. + value, derr = decodeData(event, b, decode) + } else { + value, derr = decodePayload(eventPayload{data: b}, event, decode) + } + if derr != nil { + derr = fmt.Errorf("%w: service result won't decode for event %v: %w", ErrEventDataEncoding, event, derr) + } else if !replay { + derr = decodedAsPassed(value, result, "service result", true) + } else { + derr = decodedAsRecorded(value, recorded) + } + if derr != nil { + rtype := recorded.rtype + if !replay { + rtype = reflect.TypeOf(result) + } + return nil, nil, &undecodableResult{raw: b, typ: resultType(recorded, replay, result), rtype: rtype, err: derr} + } + settled.set(recordedResult{raw: b, typ: resultType(recorded, replay, result)}) + return value, nil, nil + } +} + +// typedNil reports whether b, a service result's JSON, is the null of a typed nil, +// such as a nil pointer or map: the ServiceFn's own value live, or the Go type the +// journal recorded on replay. An untyped nil, or a result recorded with no type, isn't. +func typedNil(b []byte, recorded recordedResult, replay bool, result any) bool { + if string(b) != "null" { + return false + } + if replay { + return recorded.typ != "" && recorded.typ != typeName(nil) + } + return result != nil +} + +// settledJSON holds the JSON the last successful settle decoded and the result's Go +// type, for serviceStep to journal. The transform sets it during the settle, which runs +// under the Handle's step lock live and on replay's one goroutine, and serviceStep +// takes it once the settle returns, so it holds nothing between steps. A nil +// settledJSON keeps nothing. +type settledJSON struct{ recordedResult } + +func (s *settledJSON) set(r recordedResult) { + if s != nil { + s.recordedResult = r + } +} + +// take returns what the last settle left and clears it. +func (s *settledJSON) take() recordedResult { + if s == nil { + return recordedResult{} + } + r := s.recordedResult + s.recordedResult = recordedResult{} + return r +} + +// legacyResult is a service result recorded in a Record of a format before +// decodedResultsFormat, decoded as that version replayed it: into an any, with no +// decoder or type check. The transform settles it as it is. +type legacyResult struct{ value any } + +// resultType returns the Go type a park, or a successful settle, records for result: +// the recorded one on replay, else the ServiceFn's value's. +func resultType(recorded recordedResult, replay bool, result any) string { + if replay { + return recorded.typ + } + return typeName(result) +} + +// recordedResult is a journaled service result's JSON, which replayService settles so +// the transform decodes it as the live run decoded the ServiceFn's value, and which a +// RunService settles for a parked result. +type recordedResult struct { + raw json.RawMessage + // typ is the result's Go type, as typeName gives it, which a park and every + // successful settle record; empty for a result recorded before settles recorded it, + // which replay doesn't type-check. + typ string + // rtype is the result's Go type itself, which only a result this Handle parked + // carries: typ can't tell apart two types of the same name and package, such as two + // function-local types, so a parked settle on the Handle that parked it compares the + // types, as the live settle did. A result read from the journal or a checkpoint has + // only typ. + rtype reflect.Type +} + +// typeName returns the full name of v's type, the form a parked result records: a +// named type's import path and name, so two packages' model.Result differ, and an +// unnamed type spelled from those (see fullTypeName). +func typeName(v any) string { + t := reflect.TypeOf(v) + if t == nil { + return "" + } + return fullTypeName(t) +} + +// fullTypeName spells t as reflect does, but with each named type's import path in +// place of its package name, so two packages' model.Result differ wherever they +// appear: in a pointer, slice, array, map or chan, a func's parameters and results, an +// interface's methods, and a struct literal's fields, whose tags and unexported names' +// packages are part of the type too. +func fullTypeName(t reflect.Type) string { + if name := t.Name(); name != "" { + if pkg := t.PkgPath(); pkg != "" { + return pkg + "." + name } - return nil, errors.New(msg) + return name } - b, jerr := marshalPayload(result) - if jerr != nil { - return result, nil + switch t.Kind() { + case reflect.Pointer: + return "*" + fullTypeName(t.Elem()) + case reflect.Slice: + return "[]" + fullTypeName(t.Elem()) + case reflect.Array: + return fmt.Sprintf("[%d]%s", t.Len(), fullTypeName(t.Elem())) + case reflect.Map: + return "map[" + fullTypeName(t.Key()) + "]" + fullTypeName(t.Elem()) + case reflect.Chan: + return chanTypeName(t) + case reflect.Func: + return "func" + signatureName(t) + case reflect.Struct: + return structTypeName(t) + case reflect.Interface: + return interfaceTypeName(t) } - var decoded any - if jerr = json.Unmarshal(b, &decoded); jerr != nil { - return undecodableResult{err: jerr}, nil + return t.String() +} + +// chanTypeName spells a chan type t, parenthesizing a receive-only element of a +// bidirectional chan, as reflect does. +func chanTypeName(t reflect.Type) string { + elem := fullTypeName(t.Elem()) + switch t.ChanDir() { + case reflect.RecvDir: + return "<-chan " + elem + case reflect.SendDir: + return "chan<- " + elem } - return decoded, nil + if t.Elem().Kind() == reflect.Chan && t.Elem().Name() == "" && t.Elem().ChanDir() == reflect.RecvDir { + return "chan (" + elem + ")" + } + return "chan " + elem } -// undecodableResult stands in for a service result whose JSON form won't decode, such -// as a number beyond float64, so recordServiceOutcome refuses it: a replay couldn't -// decode the journaled form, and every Recover would fail. -type undecodableResult struct{ err error } +// signatureName spells a func type t's parameters and results, without "func". +func signatureName(t reflect.Type) string { + var b strings.Builder + b.WriteByte('(') + for i := range t.NumIn() { + if i > 0 { + b.WriteString(", ") + } + if t.IsVariadic() && i == t.NumIn()-1 { + b.WriteString("..." + fullTypeName(t.In(i).Elem())) + continue + } + b.WriteString(fullTypeName(t.In(i))) + } + b.WriteByte(')') + switch n := t.NumOut(); n { + case 0: + case 1: + b.WriteString(" " + fullTypeName(t.Out(0))) + default: + b.WriteString(" (") + for i := range n { + if i > 0 { + b.WriteString(", ") + } + b.WriteString(fullTypeName(t.Out(i))) + } + b.WriteByte(')') + } + return b.String() +} + +// structTypeName spells a struct literal type t field by field: an unexported field's +// name with its package's import path, an embedded field by its type alone, and each +// tag quoted, as reflect does. +func structTypeName(t reflect.Type) string { + if t.NumField() == 0 { + return "struct {}" + } + var b strings.Builder + b.WriteString("struct {") + for i := range t.NumField() { + if i > 0 { + b.WriteByte(';') + } + f := t.Field(i) + b.WriteByte(' ') + if !f.Anonymous { + b.WriteString(qualifiedName(f.PkgPath, f.Name) + " ") + } + b.WriteString(fullTypeName(f.Type)) + if f.Tag != "" { + b.WriteString(" " + strconv.Quote(string(f.Tag))) + } + } + b.WriteString(" }") + return b.String() +} + +// interfaceTypeName spells an interface literal type t method by method, an unexported +// method's name with its package's import path. +func interfaceTypeName(t reflect.Type) string { + if t.NumMethod() == 0 { + return "interface {}" + } + var b strings.Builder + b.WriteString("interface {") + for i := range t.NumMethod() { + if i > 0 { + b.WriteByte(';') + } + m := t.Method(i) + b.WriteString(" " + qualifiedName(m.PkgPath, m.Name) + signatureName(m.Type)) + } + b.WriteString(" }") + return b.String() +} + +// qualifiedName prefixes an unexported name with the import path of its package, pkg, +// which is empty for an exported one. +func qualifiedName(pkg, name string) string { + if pkg == "" { + return name + } + return pkg + "." + name +} + +// decodedAsRecorded is decodedAsPassed for a recorded result, which records its type's +// name rather than a value: it reports, as an ErrEventDataEncoding error, a value the +// decoder returned as another type than the recorded one. As live, nil and JSON's +// generic form are always accepted. A result this Handle parked keeps its type, and is +// held to it as live held it; one read from the journal or a checkpoint is held to its +// name, which a type of the same name and package, such as another function-local type, +// also has. An empty name, a result recorded before settles recorded the type, accepts +// anything. +func decodedAsRecorded(value any, recorded recordedResult) error { + typ := recorded.typ + if typ == "" || value == nil || genericJSON(value) { + return nil + } + if recorded.rtype != nil && reflect.TypeOf(value) != recorded.rtype { + return fmt.Errorf("%w: a %s service result decodes as another type, %v, of the same name or not; decode it as the service's own %s with WithEventDataDecoder", + ErrEventDataEncoding, typ, reflect.TypeOf(value), typ) + } + if got := typeName(value); got != typ { + return fmt.Errorf("%w: a %s service result decodes as %s; decode it as %s with WithEventDataDecoder", + ErrEventDataEncoding, typ, got, typ) + } + return nil +} + +// undecodableResult is the abort replayableOutcome returns for a result that won't +// decode for its onDone event, or decodes as another type than the ServiceFn returned. +// The ServiceRunner fires no event for it and hands it back in the settle's +// FireResult.Err, where serviceStep finds it and parks the result, and replayService +// finds it and fails the replay. For a result that won't decode, or decodes as another +// type, err wraps ErrEventDataEncoding, as the park RunService returns does. For a +// result with no JSON form raw is nil, err says why it won't encode and wraps no +// sentinel, and serviceStep fails the Handle, so RunService returns ErrHandleFailed, +// not ErrEventDataEncoding, whose Handle stays usable. +type undecodableResult struct { + err error + raw json.RawMessage // the result's JSON, which a park records + typ string // the result's Go type, as typeName gives it, for a park + rtype reflect.Type // the result's Go type itself, which the Handle keeps with a park +} + +func (u *undecodableResult) Error() string { return u.err.Error() } +func (u *undecodableResult) Unwrap() error { return u.err } + +// genericJSON reports whether v is a type JSON decodes into an any: what the default +// decoder gives, or a json.Number from a decoder that keeps numbers with UseNumber. +func genericJSON(v any) bool { + switch v.(type) { + case map[string]any, []any, float64, json.Number, string, bool: + return true + } + return false +} + +// decodedAsPassed reports, as an ErrEventDataEncoding error, a value the decoder +// returned as another type than passed, the value the host handed over; what names it. +// A Fire's payload must come back as the caller's type. A service result may also come +// back as nil or in JSON's generic form (generic), so the default decoder serves every +// result: the service has already run, and refusing its result would only run it again. +func decodedAsPassed(value, passed any, what string, generic bool) error { + if generic && (value == nil || genericJSON(value)) { + return nil + } + if got, want := reflect.TypeOf(value), reflect.TypeOf(passed); got != want { + return fmt.Errorf("%w: a %v %s decodes as %v; decode it as %v with WithEventDataDecoder", + ErrEventDataEncoding, want, what, got, want) + } + return nil +} // recordServiceOutcome builds the JournalServiceResult entry for a just-settled -// service. It reads the success result through lastResult (valid only during the -// settle's synchronous window) and the error through lastErr, encoding whichever -// the service produced. -func recordServiceOutcome(id string, lastResult func() (any, bool), lastErr error) (state.JournalEntry, error) { +// service: the error lastErr, or, for a success, settled, the JSON the settle decoded +// and the result's Go type (see settledJSON), so replay decodes the bytes live decoded +// and holds the decoder to the type live did. +func recordServiceOutcome(id string, settled recordedResult, lastErr error) (state.JournalEntry, error) { var sp serviceResultPayload if lastErr != nil { msg := lastErr.Error() sp.Error = &msg - } else if result, ok := lastResult(); ok { - if u, bad := result.(undecodableResult); bad { - return state.JournalEntry{}, fmt.Errorf("service result won't decode from its JSON form: %w", u.err) - } - raw, err := marshalPayload(result) - if err != nil { - return state.JournalEntry{}, fmt.Errorf("marshaling service result: %w", err) - } - sp.Result = raw + } else { + sp.Result, sp.Type = settled.raw, settled.typ } payload, err := json.Marshal(sp) if err != nil { @@ -283,16 +742,16 @@ func recordServiceOutcome(id string, lastResult func() (any, bool), lastErr erro // SettleError (with the reconstructed error), so the kernel re-fires the same // onDone / onError event with the same data and re-derives identical context. It // returns the settle's effects, so the caller arms the timers its state declares, as -// the live RunService did. It reports an error only when the recorded entry cannot be -// decoded or names no in-flight service (a corrupt or mis-ordered journal). -func replayService[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], entry state.JournalEntry) ([]state.Effect, error) { +// the live RunService did. sp is entry's decoded payload. A result in a Record of a +// format before decodedResultsFormat (decoded false) replays as the version that wrote +// it replayed it, in JSON's generic form through no decoder: that version's live run +// saw the ServiceFn's own value, which no decoder of this one can be held to. It +// reports an error only when the recorded result cannot be decoded or names no +// in-flight service (a corrupt or mis-ordered journal). +func replayService[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], entry state.JournalEntry, sp serviceResultPayload, decoded bool) ([]state.Effect, error) { if svc == nil { return nil, errors.New("durable: replaying a service result requires a service registry (supply WithServiceRegistry)") } - var sp serviceResultPayload - if err := json.Unmarshal(entry.Payload, &sp); err != nil { - return nil, fmt.Errorf("durable: decoding recorded service %q outcome: %w", entry.CorrelationID, err) - } if sp.Error != nil { res, ok := svc.SettleError(ctx, entry.CorrelationID, errors.New(*sp.Error)) if !ok { @@ -300,19 +759,45 @@ func replayService[S comparable, E comparable, C any](ctx context.Context, svc * } return res.Effects, nil } + // The transform decodes the recorded JSON for the onDone event, as it did live. One + // that won't decode aborts the settle before it fires anything. var result any - if len(sp.Result) > 0 { - if err := json.Unmarshal(sp.Result, &result); err != nil { - return nil, fmt.Errorf("durable: decoding recorded service %q result: %w", entry.CorrelationID, err) + switch { + case !decoded: + var v any + if len(sp.Result) > 0 { + if err := json.Unmarshal(sp.Result, &v); err != nil { + return nil, fmt.Errorf("durable: decoding recorded service %q result: %w", entry.CorrelationID, err) + } } + result = legacyResult{value: v} + case len(sp.Result) > 0: + // The recorded type holds the decoder to it, as the settle did. + result = recordedResult{raw: sp.Result, typ: sp.Type} } res, ok := svc.SettleDone(ctx, entry.CorrelationID, result) + if derr := (*undecodableResult)(nil); errors.As(res.Err, &derr) { + return nil, fmt.Errorf("durable: decoding recorded service %q result: %w", entry.CorrelationID, derr) + } if !ok { return nil, fmt.Errorf("durable: replaying service %q: no in-flight service to settle", entry.CorrelationID) } return res.Effects, nil } +// replayPark checks a recorded parked result against the replay: its service must be in +// flight, as it was when the live run parked it, and stays in flight. It settles +// nothing, so no Assign runs. It reports an error for a corrupt or mis-ordered journal. +func replayPark[S comparable, E comparable, C any](svc *state.ServiceRunner[S, E, C], entry state.JournalEntry) error { + if svc == nil { + return errors.New("durable: replaying a parked service result requires a service registry (supply WithServiceRegistry)") + } + if !svc.HasPending(entry.CorrelationID) { + return fmt.Errorf("durable: replaying parked service %q: no in-flight service", entry.CorrelationID) + } + return nil +} + // serviceEntries returns the recorded service outcomes carried by a single // Record, in recorded (settle) order, so replay re-settles them in the order the // live run produced them. diff --git a/durable/service_activation_test.go b/durable/service_activation_test.go new file mode 100644 index 00000000..e4d52ad2 --- /dev/null +++ b/durable/service_activation_test.go @@ -0,0 +1,52 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// TestRunService_ServiceFnCantChangeItsActivation pins why a settle can't find its +// activation gone through durable's API: a ServiceFn runs under RunService's step lock, +// so a Fire it makes to leave the state is refused, with ErrReentrantStep on the step's +// context and with its own context's error on any other, and the settle routes as +// usual. Only code that drives the ServiceRunner past the Handle can stop the activation +// (see TestServiceStep_StaleSettleRecordsNothing). +func TestRunService_ServiceFnCantChangeItsActivation(t *testing.T) { + ctx := context.Background() + var h *durable.Handle[string, string, svcCtx] + var reentrant, other error + fn := func(sctx context.Context, _ state.ServiceCtx[svcCtx]) (any, error) { + _, reentrant = h.Fire(sctx, "next") + octx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + _, other = h.Fire(octx, "next") + return scnUser{ID: 7, Name: "ann"}, nil + } + m := forkMachine(fn) + st := durable.NewMemStore() + var err error + if h, err = durable.NewRunner(m, st, durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))). + Start(ctx, "o1", svcCtx{}, state.WithInitialState("loading")); err != nil { + t.Fatalf("Start: %v", err) + } + if _, ran, rerr := h.RunService(ctx, state.InvokeID("fork", "loading", 0)); !ran || rerr != nil { + t.Fatalf("RunService = %v, %v", ran, rerr) + } + if !errors.Is(reentrant, durable.ErrReentrantStep) { + t.Fatalf("a Fire on the step's context: %v, want ErrReentrantStep", reentrant) + } + if !errors.Is(other, context.DeadlineExceeded) { + t.Fatalf("a Fire on another context: %v, want its deadline", other) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("in %q, want ready: the settle routed", got) + } + if got := tailLen(t, st, "o1"); got != 1 { + t.Fatalf("the journal holds %d Records, want the settle's", got) + } +} diff --git a/durable/service_encode_internal_test.go b/durable/service_encode_internal_test.go new file mode 100644 index 00000000..e433bbce --- /dev/null +++ b/durable/service_encode_internal_test.go @@ -0,0 +1,83 @@ +package durable + +import ( + "encoding/json" + "testing" +) + +// f8Order's fields aren't in alphabetical order, so its JSON and the JSON of the map +// it decodes to by default list them in a different order. +type f8Order struct { + Zone string + ID int64 +} + +// TestServiceResult_JournalBytesAreWhatLiveDecoded pins that a live service result is +// encoded once. replayableOutcome encodes the ServiceFn's value and decodes those bytes; +// recordServiceOutcome journals the same bytes, so replay decodes what live decoded. +// They differ from the decoded value's own encoding for a struct decoded as a map (the +// keys come out sorted) and for an integer beyond 2^53 decoded as a float64 (the journal +// keeps digits the machine never saw), but replay decodes either to the value live saw, +// and only these bytes do for a decoder whose type doesn't survive its own round trip +// (see TestServiceResult_ReplayDecodesWhatLiveDecoded). +func TestServiceResult_JournalBytesAreWhatLiveDecoded(t *testing.T) { + asOrder := func(_ string, data []byte) (any, error) { return DecodeAs[f8Order](data) } + asInt64 := func(_ string, data []byte) (any, error) { return DecodeAs[int64](data) } + cases := []struct { + name string + result any + decode EventDataDecoder[string] + reencode bool // whether the decoded value's own encoding matches the journal's + recorded string // what the journal records + }{ + {"string", "ok", decodeAny[string], true, `"ok"`}, + {"small int, generic", 42, decodeAny[string], true, `42`}, + {"int64 above 2^53, generic", int64(1<<53 + 1), decodeAny[string], false, `9007199254740993`}, + {"int64 above 2^53, typed", int64(1<<53 + 1), asInt64, true, `9007199254740993`}, + {"struct, generic", f8Order{Zone: "w", ID: 7}, decodeAny[string], false, `{"Zone":"w","ID":7}`}, + {"struct, typed", f8Order{Zone: "w", ID: 7}, asOrder, true, `{"Zone":"w","ID":7}`}, + {"map, generic", map[string]any{"b": 1.0, "a": "x"}, decodeAny[string], true, `{"a":"x","b":1}`}, + {"slice, generic", []any{"x", 2.5}, decodeAny[string], true, `["x",2.5]`}, + {"nil", nil, decodeAny[string], true, `null`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + settled := &settledJSON{} + value, outErr, abort := replayableOutcome(tc.decode, settled)("done", tc.result, nil) + if outErr != nil || abort != nil { + t.Fatalf("the transform returned %v, %v", outErr, abort) + } + entry, err := recordServiceOutcome("svc", settled.take(), nil) + if err != nil { + t.Fatalf("recordServiceOutcome: %v", err) + } + var sp serviceResultPayload + if err = json.Unmarshal(entry.Payload, &sp); err != nil { + t.Fatalf("decoding the entry: %v", err) + } + if got := string(sp.Result); got != tc.recorded { + t.Fatalf("the journal records %s, want %s", got, tc.recorded) + } + reencoded, err := marshalPayload(value) + if err != nil { + t.Fatalf("encoding the decoded value: %v", err) + } + if same := string(reencoded) == string(sp.Result); same != tc.reencode { + t.Fatalf("decoded value's encoding %s, journal %s: same = %v, want %v", reencoded, sp.Result, same, tc.reencode) + } + // Replay decodes the journal to the value live saw. + replayed, _, rabort := replayableOutcome(tc.decode, nil)("done", recordedResult{raw: sp.Result}, nil) + if rabort != nil { + t.Fatalf("replaying %s: %v", sp.Result, rabort) + } + if describeValue(replayed) != describeValue(value) { + t.Fatalf("replaying %s gives %s, live saw %s", sp.Result, describeValue(replayed), describeValue(value)) + } + }) + } +} + +func describeValue(v any) string { + b, _ := json.Marshal(v) + return string(b) +} diff --git a/durable/service_error_message_test.go b/durable/service_error_message_test.go deleted file mode 100644 index 046c1d80..00000000 --- a/durable/service_error_message_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package durable_test - -import ( - "context" - "errors" - "testing" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// TestRunService_AnUnboundServiceErrorIsMessageOnly pins a documented limit: errors are -// message-only, so onError's Assign sees a plain error with the message of an unbound -// service's *state.UnboundRefError, which errors.As doesn't match, live or on replay. -func TestRunService_AnUnboundServiceErrorIsMessageOnly(t *testing.T) { - ctx := context.Background() - var seen []any - m := state.ForgeFor[svcCtx]("unbound"). - Service("fetch", func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return nil, nil }). - Reducer("noteFail", func(in state.AssignCtx[svcCtx]) svcCtx { - seen = append(seen, in.Event) - return in.Entity - }). - State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). - State("ready").Final(). - State("failed").Final(). - Initial("loading"). - Transition("loading").On("done").GoTo("ready"). - Transition("loading").On("fail").GoTo("failed").Assign("noteFail"). - Quench() - store := durable.NewMemStore() - // The registry binds no "fetch", so the service settles as unbound. - opt := durable.WithServiceRegistry[string, string, svcCtx](state.NewRegistry[svcCtx]()) - h, err := durable.NewRunner(m, store, opt).Start(ctx, "unb-1", svcCtx{}, state.WithInitialState("loading")) - if err != nil { - t.Fatalf("Start: %v", err) - } - if _, _, err = h.RunService(ctx, state.InvokeID("unbound", "loading", 0)); err != nil { - t.Fatalf("RunService: %v", err) - } - if _, err = durable.Recover(ctx, m, store, "unb-1", opt); err != nil { - t.Fatalf("Recover: %v", err) - } - if len(seen) != 2 { - t.Fatalf("onError's Assign ran %d times (%v), want 2: live and on replay", len(seen), seen) - } - want := (&state.UnboundRefError{Kind: "service", Name: "fetch"}).Error() - for i, when := range []string{"live", "on replay"} { - err, ok := seen[i].(error) - if !ok || err.Error() != want { - t.Fatalf("%s, onError's Assign saw %T %v, want an error saying %q", when, seen[i], seen[i], want) - } - var unbound *state.UnboundRefError - if errors.As(err, &unbound) { - t.Fatalf("%s, errors.As matched an *UnboundRefError, though errors are message-only", when) - } - } -} diff --git a/durable/service_outcome_test.go b/durable/service_outcome_test.go index b6b205e6..3cc8a6b9 100644 --- a/durable/service_outcome_test.go +++ b/durable/service_outcome_test.go @@ -3,7 +3,6 @@ package durable_test import ( "context" "encoding/json" - "errors" "strings" "testing" @@ -35,13 +34,18 @@ func outcomeMachine(fn state.ServiceFn[svcCtx], seen *[]string) *state.Machine[s Quench() } -// TestRunService_ResultThatEncodesButWontDecode_FailsTheStep proves a result whose -// JSON form a replay can't decode, such as a number beyond float64, fails RunService -// with ErrHandleFailed and records nothing, as a result that won't encode does, so the -// instance stays recoverable with the service in flight again. -func TestRunService_ResultThatEncodesButWontDecode_FailsTheStep(t *testing.T) { +// TestRunService_ResultThatEncodesButWontDecode_ParksIt proves a result whose JSON +// form won't decode, such as a number beyond float64, makes RunService return +// ErrEventDataEncoding before any onDone or onError Assign runs, and parks the result: +// the Handle stays healthy, and the recovered instance has the service parked, so +// RunService doesn't run it again. +func TestRunService_ResultThatEncodesButWontDecode_ParksIt(t *testing.T) { ctx := context.Background() - fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return json.RawMessage("1e400"), nil } + var runs int + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + runs++ + return json.RawMessage("1e400"), nil + } var seen []string m := outcomeMachine(fn, &seen) st := durable.NewMemStore() @@ -51,18 +55,25 @@ func TestRunService_ResultThatEncodesButWontDecode_FailsTheStep(t *testing.T) { t.Fatalf("Start: %v", err) } id := state.InvokeID("outcome", "loading", 0) - if _, _, err = h.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { - t.Fatalf("RunService: %v, want ErrHandleFailed", err) + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + if len(seen) != 0 { + t.Fatalf("an Assign saw %q, want none to run for a result that won't decode", seen) } - if _, recs, lerr := st.Load(ctx, "i1"); lerr != nil || len(recs) != 0 { - t.Fatalf("journal holds %d Records (err %v), want none", len(recs), lerr) + if _, recs, lerr := st.Load(ctx, "i1"); lerr != nil || len(recs) != 1 { + t.Fatalf("journal holds %d Records (err %v), want the one that parks the result", len(recs), lerr) } recovered, err := durable.Recover(ctx, m, st, "i1", opts...) if err != nil { t.Fatalf("Recover: %v, want the instance recoverable", err) } if got := recovered.Instance().Current(); got != "loading" { - t.Fatalf("recovered in %q, want loading with the service in flight again", got) + t.Fatalf("recovered in %q, want loading with the service parked", got) + } + _, ran, err = recovered.RunService(ctx, id) + mustPark(t, "RunService after Recover", ran, err) + if runs != 1 || len(seen) != 0 { + t.Fatalf("the ServiceFn ran %d times and Assigns saw %q; want 1 and none", runs, seen) } } diff --git a/durable/service_replay_bench_test.go b/durable/service_replay_bench_test.go new file mode 100644 index 00000000..87e4de3d --- /dev/null +++ b/durable/service_replay_bench_test.go @@ -0,0 +1,79 @@ +package durable_test + +import ( + "context" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// benchSettles is how many service results the replay benchmark's journal holds. +const benchSettles = 200 + +// pingPongMachine alternates between a and b, each invoking fetch, so every settle +// enters the other state and starts its service: a journal of settled results as long +// as the benchmark wants. +func pingPongMachine(fn state.ServiceFn[svcCtx]) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("pp"). + Service("fetch", fn). + State("a").Invoke("fetch", state.WithInvokeOnDone("next")). + State("b").Invoke("fetch", state.WithInvokeOnDone("next")). + Initial("a"). + Transition("a").On("next").GoTo("b"). + Transition("b").On("next").GoTo("a"). + Quench() +} + +func benchOpts(fn state.ServiceFn[svcCtx]) []durable.Option[string, string, svcCtx] { + return []durable.Option[string, string, svcCtx]{ + durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), + decoderFor("next", durable.DecodeAs[scnUser]), + } +} + +// runPingPong settles n results on h, alternating the two services. +func runPingPong(b *testing.B, h *durable.Handle[string, string, svcCtx], n int) { + b.Helper() + ids := [2]string{state.InvokeID("pp", "a", 0), state.InvokeID("pp", "b", 0)} + for i := 0; i < n; i++ { + if _, ok, err := h.RunService(context.Background(), ids[i%2]); !ok || err != nil { + b.Fatalf("RunService %d = %v, %v", i, ok, err) + } + } +} + +// BenchmarkRecover_ServiceResults measures Recover replaying benchSettles settled +// service results, each decoded through a decoder for onDone. +func BenchmarkRecover_ServiceResults(b *testing.B) { + fn := returning(scnUser{ID: 7, Name: "ann"}, nil) + m := pingPongMachine(fn) + store := durable.NewMemStore() + opts := benchOpts(fn) + h, err := durable.NewRunner(m, store, opts...).Start(context.Background(), "pp-1", svcCtx{}, state.WithInitialState("a")) + if err != nil { + b.Fatalf("Start: %v", err) + } + runPingPong(b, h, benchSettles) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := durable.Recover(context.Background(), m, store, "pp-1", opts...); err != nil { + b.Fatalf("Recover: %v", err) + } + } +} + +// BenchmarkRunService_Settle measures a live RunService that settles a result through +// a decoder for onDone. +func BenchmarkRunService_Settle(b *testing.B) { + fn := returning(scnUser{ID: 7, Name: "ann"}, nil) + m := pingPongMachine(fn) + h, err := durable.NewRunner(m, durable.NewMemStore(), benchOpts(fn)...).Start(context.Background(), "pp-1", svcCtx{}, state.WithInitialState("a")) + if err != nil { + b.Fatalf("Start: %v", err) + } + b.ReportAllocs() + b.ResetTimer() + runPingPong(b, h, b.N) +} diff --git a/durable/service_result_edges_test.go b/durable/service_result_edges_test.go new file mode 100644 index 00000000..f613e2d4 --- /dev/null +++ b/durable/service_result_edges_test.go @@ -0,0 +1,331 @@ +package durable_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "sync/atomic" + "testing" + + "github.com/stablekernel/crucible/durable" + alpha "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model" + beta "github.com/stablekernel/crucible/durable/internal/typefixture/beta/model" + "github.com/stablekernel/crucible/state" +) + +// These tests answer review findings on parked service results, the journal's bytes +// for a settled result, a result with no JSON form, and an effect whose MarshalJSON +// panics. Each fails if the defect it names is real. + +// A ctx that ended during the ServiceFn, with a result the decoder refuses, parks +// nothing: as for a result that decodes, RunService fails the Handle with the ctx's +// error and records nothing, and a recovered Handle runs the service again. MemStore's +// Append doesn't check ctx, so only RunService's own check keeps the park out of the +// journal. +func TestParkedResult_CanceledDuringService_RecordsNothing(t *testing.T) { + ctx := context.Background() + turnCtx, cancel := context.WithCancel(ctx) + defer cancel() + var runs int64 + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + atomic.AddInt64(&runs, 1) + cancel() // the turn's deadline passes while the call is in flight + return scnUser{ID: 7, Name: "ann"}, nil + } + a := &scnAssigns{} + m := scnMachine(fn, a) + store := durable.NewMemStore() + opts := []durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), failingDecoder()} + h := scnStart(t, m, store, opts...) + id := state.InvokeID(scnInvoke, "loading", 0) + + _, _, err := h.RunService(turnCtx, id) + if !errors.Is(err, durable.ErrHandleFailed) || !errors.Is(err, context.Canceled) { + t.Fatalf("RunService = %v, want ErrHandleFailed wrapping context.Canceled", err) + } + if got := tailLen(t, store, "scn-1"); got != 0 { + t.Fatalf("the journal holds %d Records, want none: the canceled turn's result was parked", got) + } + if a.done != 0 || a.fails != 0 { + t.Fatalf("onDone's Assign ran %d times and onError's %d, want neither", a.done, a.fails) + } + rh, err := durable.Recover(ctx, m, store, "scn-1", opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + _, ran, err := rh.RunService(ctx, id) + mustPark(t, "RunService after Recover", ran, err) + if got := atomic.LoadInt64(&runs); got != 2 { + t.Fatalf("the ServiceFn ran %d times, want 2: the canceled run recorded nothing", got) + } +} + +// The decoder is part of the Runner's options, so fixing it reaches only a Handle a +// Runner with the fix recovers. On the Handle that parked the result, every RunService +// returns ErrEventDataEncoding; Recover with the fixed decoder, then RunService, settles +// it. +func TestParkedResult_OnlyARecoveredHandleSeesTheFix(t *testing.T) { + r := newParkRun(t) + mustPark(t, "the first RunService", true, r.err) + h, err := durable.Recover(context.Background(), r.m, r.store, "scn-1", r.reg, failingDecoder()) + if err != nil { + t.Fatalf("Recover: %v", err) + } + id := state.InvokeID(scnInvoke, "loading", 0) + for i := 0; i < 3; i++ { + _, ran, rerr := h.RunService(context.Background(), id) + mustPark(t, fmt.Sprintf("RunService %d on the same Handle", i), ran, rerr) + } + fixed, runErr, err := r.recoverAndRun(decoderFor("done", durable.DecodeAs[scnUser])) + if err != nil || runErr != nil { + t.Fatalf("Recover: %v, RunService: %v, with the fixed decoder", err, runErr) + } + if got := fixed.Instance().Current(); got != "ready" { + t.Fatalf("in %q, want ready", got) + } +} + +// A parked result records its Go type with its import path, so a decoder for another +// package's type of the same short name (model.Result) can't settle it. Live, the same +// decoder is refused, since the live check compares reflect types. +func TestParkedResult_TypeCheckKeepsTheImportPath(t *testing.T) { + ctx := context.Background() + var runs int64 + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + atomic.AddInt64(&runs, 1) + return alpha.Result{ID: 7, Name: "ann"}, nil + } + id := state.InvokeID(scnInvoke, "loading", 0) + asBeta := decoderFor("done", durable.DecodeAs[beta.Result]) + + t.Run("live", func(t *testing.T) { + a := &scnAssigns{} + h := scnStart(t, scnMachine(fn, a), durable.NewMemStore(), durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), asBeta) + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService with beta's decoder", ran, err) + }) + t.Run("parked", func(t *testing.T) { + a := &scnAssigns{} + m := scnMachine(fn, a) + store := durable.NewMemStore() + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + h := scnStart(t, m, store, reg, failingDecoder()) + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + rh, err := durable.Recover(ctx, m, store, "scn-1", reg, asBeta) + if err != nil { + t.Fatalf("Recover: %v", err) + } + _, ran, err = rh.RunService(ctx, id) + mustPark(t, "RunService with beta's decoder", ran, err) + if a.done != 0 || a.fails != 0 { + t.Fatalf("an Assign ran: onDone %d (saw %v), onError %d", a.done, a.seen, a.fails) + } + rh, err = durable.Recover(ctx, m, store, "scn-1", reg, decoderFor("done", durable.DecodeAs[alpha.Result])) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, _, err = rh.RunService(ctx, id); err != nil { + t.Fatalf("RunService with alpha's decoder: %v", err) + } + if a.done != 1 || describe(a.seen[0]) != describe(alpha.Result{ID: 7, Name: "ann"}) { + t.Fatalf("onDone's Assign ran %d times and saw %v, want alpha's Result once", a.done, a.seen) + } + }) +} + +// A result with no JSON form runs no Assign: RunService fails the Handle before the +// settle fires anything, records nothing, and a recovered Handle has the service in +// flight again. This holds with the default decoder and with one for onDone. +func TestServiceResult_NoJSONForm_RunsNoAssign(t *testing.T) { + for _, tc := range []struct { + name string + opts []durable.Option[string, string, svcCtx] + }{ + {"default decoder", nil}, + {"decoder for onDone", []durable.Option[string, string, svcCtx]{decoderFor("done", durable.DecodeAs[scnUser])}}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + var runs int64 + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + atomic.AddInt64(&runs, 1) + return make(chan int), nil + } + a := &scnAssigns{} + m := scnMachine(fn, a) + store := durable.NewMemStore() + opts := append([]durable.Option[string, string, svcCtx]{durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn))}, tc.opts...) + h := scnStart(t, m, store, opts...) + id := state.InvokeID(scnInvoke, "loading", 0) + if _, _, err := h.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService = %v, want ErrHandleFailed", err) + } + if a.done != 0 || a.fails != 0 { + t.Fatalf("onDone's Assign ran %d times and onError's %d, want neither", a.done, a.fails) + } + if got := tailLen(t, store, "scn-1"); got != 0 { + t.Fatalf("the journal holds %d Records, want none", got) + } + rh, err := durable.Recover(ctx, m, store, "scn-1", opts...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if _, ran, err := rh.RunService(ctx, id); !ran || !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService after Recover = %v, %v; want the service run again, failing the Handle", ran, err) + } + if got := atomic.LoadInt64(&runs); got != 2 { + t.Fatalf("the ServiceFn ran %d times, want 2", got) + } + if a.done != 0 || a.fails != 0 { + t.Fatalf("onDone's Assign ran %d times and onError's %d, want neither", a.done, a.fails) + } + }) + } +} + +// unitBug's MarshalJSON writes milliseconds and its UnmarshalJSON reads seconds: an +// asymmetric pair, so decoding its own encoding scales the value a thousandfold. +type unitBug struct{ Seconds int64 } + +func (u unitBug) MarshalJSON() ([]byte, error) { return json.Marshal(u.Seconds * 1000) } + +func (u *unitBug) UnmarshalJSON(b []byte) error { return json.Unmarshal(b, &u.Seconds) } + +// sealed encodes as its Token until it is decoded; a decoded sealed won't encode again, +// as a type that keeps a handle it can't serialize won't. +type sealed struct { + Token string + decoded bool +} + +func (s sealed) MarshalJSON() ([]byte, error) { + if s.decoded { + return nil, errors.New("a decoded sealed won't encode again") + } + return json.Marshal(s.Token) +} + +func (s *sealed) UnmarshalJSON(b []byte) error { + s.decoded = true + return json.Unmarshal(b, &s.Token) +} + +// Replay decodes the bytes the live settle decoded, so the Assign sees the same value +// live and after Recover even when the decoder's type doesn't survive a round trip +// through its own encoding: an asymmetric MarshalJSON/UnmarshalJSON pair, or a decoded +// value that won't encode again. Journaling the decoded value's encoding instead +// replays the pair's value scaled again, and fails the Handle for the second, after +// its Assign ran. +func TestServiceResult_ReplayDecodesWhatLiveDecoded(t *testing.T) { + t.Run("asymmetric codec", func(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(unitBug{Seconds: 2}, nil), decoderFor("done", durable.DecodeAs[unitBug])) + mustTwo(t, a, runErr, recErr) + if got := a.seen[0].(unitBug); got.Seconds != 2000 { + t.Fatalf("live saw %+v, want the 2000 its own encoding decodes to", got) + } + }) + t.Run("decoded value won't encode", func(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(sealed{Token: "t"}, nil), decoderFor("done", durable.DecodeAs[sealed])) + mustTwo(t, a, runErr, recErr) + }) + t.Run("int64 above 2^53, no decoder", func(t *testing.T) { + a, runErr, recErr := scnRun(t, returning(int64(1<<53+1), nil)) + mustTwo(t, a, runErr, recErr) + if got, ok := a.seen[0].(float64); !ok || got != float64(1<<53) { + t.Fatalf("live saw %s, want the float64 9007199254740992", describe(a.seen[0])) + } + }) +} + +// panicky is a KindedEffect whose MarshalJSON panics. +type panicky struct{} + +func (panicky) Kind() string { return "demo.panicky" } +func (panicky) MarshalJSON() ([]byte, error) { panic("marshal blew up") } + +// panickyKind is a KindedEffect whose Kind panics. +type panickyKind struct{} + +func (panickyKind) Kind() string { panic("kind blew up") } + +func emitting(eff state.Effect) func(state.ActionCtx[svcCtx]) (state.Effect, error) { + return func(state.ActionCtx[svcCtx]) (state.Effect, error) { return eff, nil } +} + +func panickyMachine(eff state.Effect) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("pnk"). + Action("emit", emitting(eff)). + State("idle"). + State("done").Final(). + Initial("idle"). + Transition("idle").On("go").GoTo("done").Do("emit"). + Quench() +} + +// fireCatching fires event on h and returns the panic that escaped, or the error. +func fireCatching(h *durable.Handle[string, string, svcCtx], event string) (panicked any, err error) { + defer func() { panicked = recover() }() + _, err = h.Fire(context.Background(), event) + return nil, err +} + +// A KindedEffect whose MarshalJSON panics is recorded as one whose marshal fails: by id +// and kind, with the panic's message in Meta under crucible.marshalError. The step +// doesn't panic or fail, and Recover replays it. +func TestUnmarshalableEffect_PanickingMarshal_RecordsByIDAndKind(t *testing.T) { + ctx := context.Background() + m := panickyMachine(panicky{}) + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store).Start(ctx, "pnk-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + p, ferr := fireCatching(h, "go") + if p != nil || ferr != nil { + t.Fatalf("Fire = %v, panic %v; want neither", ferr, p) + } + _, recs, err := store.Load(ctx, "pnk-1") + if err != nil || len(recs) != 1 || len(recs[0].Effects) != 1 { + t.Fatalf("Load = %d Records (err %v), want one with one effect", len(recs), err) + } + env := recs[0].Effects[0] + if env.Kind != "demo.panicky" || env.EffectID != "0#0#demo.panicky" || len(env.Payload) != 0 { + t.Fatalf("recorded %+v, want kind demo.panicky, id 0#0#demo.panicky and no payload", env) + } + if msg, _ := env.Meta[metaMarshalError].(string); !strings.Contains(msg, "marshal blew up") { + t.Fatalf("Meta = %v, want the panic's message under %q", env.Meta, metaMarshalError) + } + rh, err := durable.Recover(ctx, m, store, "pnk-1") + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := rh.Instance().Current(); got != "done" { + t.Fatalf("recovered in %q, want done", got) + } +} + +// Pins current behavior: a KindedEffect whose Kind panics has no kind to record it by, +// so it can't take the id-and-kind fallback. The panic leaves the Fire, and the Handle +// is failed first, as for any panic in host code during a step, so the caller can +// Recover. The kernel applied the transition, but nothing was journaled. +func TestUnmarshalableEffect_PanickingKind_FailsTheHandle(t *testing.T) { + ctx := context.Background() + m := panickyMachine(panickyKind{}) + store := durable.NewMemStore() + h, err := durable.NewRunner(m, store).Start(ctx, "pnk-1", svcCtx{}, state.WithInitialState("idle")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if p, _ := fireCatching(h, "go"); p == nil || !strings.Contains(fmt.Sprint(p), "kind blew up") { + t.Fatalf("Fire panicked with %v, want the Kind panic", p) + } + if _, err := h.Fire(ctx, "go"); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("Fire after the panic = %v, want ErrHandleFailed", err) + } + if got := tailLen(t, store, "pnk-1"); got != 0 { + t.Fatalf("the journal holds %d Records, want none", got) + } +} diff --git a/durable/service_step_internal_test.go b/durable/service_step_internal_test.go new file mode 100644 index 00000000..fd753ab8 --- /dev/null +++ b/durable/service_step_internal_test.go @@ -0,0 +1,311 @@ +package durable + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// These tests answer review findings on serviceStep's bookkeeping: a settle that finds +// its activation gone records nothing, the JSON a settle decoded isn't held past its +// step, and the settled services and parked results are forgotten together. + +type stepCtx struct{} + +// stepMachine invokes fetch in loading; onDone "done" goes to ready, onError "fail" +// to failed. +func stepMachine(fn state.ServiceFn[stepCtx]) *state.Machine[string, string, stepCtx] { + return state.ForgeFor[stepCtx]("step"). + Service("fetch", fn). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready").Final(). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready"). + Transition("loading").On("fail").GoTo("failed"). + Quench() +} + +func stepOptions(fn state.ServiceFn[stepCtx]) []Option[string, string, stepCtx] { + return []Option[string, string, stepCtx]{WithServiceRegistry[string, string, stepCtx](state.NewRegistry[stepCtx]().Service("fetch", fn))} +} + +// TestServiceStep_StaleSettleRecordsNothing: when the activation a ServiceFn runs for is +// stopped, or stopped and armed again, before its settle, ServiceRunner.Tick fires +// nothing and returns nothing. serviceStep must record nothing for it: no +// JournalServiceResult, no settled service, and no JSON left behind, so a Recover still +// finds the service in flight. The step lock keeps durable's own steps from changing the +// activation while a ServiceFn runs (see TestRunService_ServiceFnCantChangeItsActivation), +// so this drives the ServiceRunner directly, as only code inside the package can. +func TestServiceStep_StaleSettleRecordsNothing(t *testing.T) { + for _, tc := range []struct { + name string + rearm bool + }{{"stopped", false}, {"stopped and armed again", true}} { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("step", "loading", 0) + var h *Handle[string, string, stepCtx] + runs := 0 + fn := func(ctx context.Context, _ state.ServiceCtx[stepCtx]) (any, error) { + runs++ + if runs == 1 { + effects := []state.Effect{state.StopService{ID: id}} + if tc.rearm { + effects = append(effects, h.inst.StartEffects()...) + } + h.svc.Absorb(ctx, effects) + } + return "late", nil + } + m := stepMachine(fn) + st := NewMemStore() + var err error + if h, err = NewRunner(m, st, stepOptions(fn)...).Start(ctx, "s1", stepCtx{}, state.WithInitialState("loading")); err != nil { + t.Fatalf("Start: %v", err) + } + // RunService reports the service ran, as its doc says: it was in flight and the + // ServiceFn ran, though nothing settled, so the result is the zero one. + res, ran, rerr := h.RunService(ctx, id) + if rerr != nil || !ran || runs != 1 { + t.Fatalf("RunService = %v, %v with the ServiceFn run %d times; want ran with no error, once", ran, rerr, runs) + } + if res.NewState != "" || len(res.Effects) != 0 || res.Err != nil || res.Trace.Event != "" { + t.Fatalf("RunService returned %+v, want the zero FireResult: nothing fired", res) + } + if _, recs, _ := st.Load(ctx, "s1"); len(recs) != 0 { + t.Fatalf("the journal holds %d Records, want none: the settle fired nothing", len(recs)) + } + if h.settled[id] { + t.Fatal("the service is noted settled, so a checkpoint would record it settled") + } + if h.svcJSON.raw != nil || h.svcJSON.typ != "" { + t.Fatalf("the Handle holds the stale settle's JSON %s (%s)", h.svcJSON.raw, h.svcJSON.typ) + } + if got := h.inst.Current(); got != "loading" { + t.Fatalf("in %q, want loading", got) + } + if got := h.svc.HasPending(id); got != tc.rearm { + t.Fatalf("HasPending = %v, want %v", got, tc.rearm) + } + rh, err := Recover(ctx, m, st, "s1", stepOptions(fn)...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if !rh.svc.HasPending(id) { + t.Fatal("the recovered Handle has the service settled; the journal holds no settle") + } + }) + } +} + +// TestServiceStep_StaleAbortParksNothing: when the activation a ServiceFn runs for is +// stopped and armed again before its settle, and the decoder refuses the stale result, +// ServiceRunner.Tick reports nothing, as for a settle that fired nothing, rather than +// the abort. serviceStep must park nothing: no Record, no parked result on the new +// activation, so the next RunService runs the ServiceFn for that activation. Before +// the fix, the stale abort parked the old run's result onto the new activation, which +// never ran its ServiceFn. It drives the ServiceRunner directly, as only code inside +// the package can (see TestServiceStep_StaleSettleRecordsNothing). +func TestServiceStep_StaleAbortParksNothing(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("step", "loading", 0) + var h *Handle[string, string, stepCtx] + runs := 0 + fn := func(ctx context.Context, _ state.ServiceCtx[stepCtx]) (any, error) { + runs++ + if runs == 1 { + h.svc.Absorb(ctx, append([]state.Effect{state.StopService{ID: id}}, h.inst.StartEffects()...)) + } + return "late", nil + } + refuse := WithEventDataDecoder[string, string, stepCtx](func(string, []byte) (any, error) { + return nil, errors.New("decoder refused") + }) + opts := append(stepOptions(fn), refuse) + m := stepMachine(fn) + st := NewMemStore() + var err error + if h, err = NewRunner(m, st, opts...).Start(ctx, "s1", stepCtx{}, state.WithInitialState("loading")); err != nil { + t.Fatalf("Start: %v", err) + } + res, ran, rerr := h.RunService(ctx, id) + if rerr != nil || !ran || runs != 1 { + t.Fatalf("RunService = %v, %v with the ServiceFn run %d times; want ran with no error, once: the stale settle parks nothing", ran, rerr, runs) + } + if res.NewState != "" || res.Err != nil { + t.Fatalf("RunService returned %+v, want the zero FireResult", res) + } + if _, recs, _ := st.Load(ctx, "s1"); len(recs) != 0 { + t.Fatalf("the journal holds %d Records, want none: the stale run parked nothing", len(recs)) + } + if _, ok := h.parked[id]; ok { + t.Fatal("the stale run's result is parked on the new activation") + } + if !h.svc.HasPending(id) { + t.Fatal("the new activation isn't in flight") + } + // The new activation runs its own ServiceFn; its result, refused too, parks. + if _, ran, rerr = h.RunService(ctx, id); !ran || !errors.Is(rerr, ErrEventDataEncoding) || runs != 2 { + t.Fatalf("RunService of the new activation = %v, %v with the ServiceFn run %d times; want it run again and parked", ran, rerr, runs) + } + if _, err = Recover(ctx, m, st, "s1", opts...); err != nil { + t.Fatalf("Recover: %v", err) + } +} + +// TestServiceStep_ZeroFireResultSettleIsRecorded: a middleware may return a zero +// FireResult for a Fire it ran. When that Fire is the onDone settle, the settle still +// happened: the runner dropped the service and the instance moved. serviceStep must +// record it as any settle, so the live Handle and the journal agree: the step is +// recorded, the service is noted settled, and Recover replays the result to the same +// state without running the ServiceFn again. +func TestServiceStep_ZeroFireResultSettleIsRecorded(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("step", "loading", 0) + runs := 0 + fn := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { + runs++ + return "ok", nil + } + hide := func(next state.FireFunc[string, string, stepCtx]) state.FireFunc[string, string, stepCtx] { + return func(ctx context.Context, event string) state.FireResult[string] { + res := next(ctx, event) + if event == "done" { + return state.FireResult[string]{} + } + return res + } + } + m := state.ForgeFor[stepCtx]("step"). + Use(hide). + Service("fetch", fn). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready").Final(). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready"). + Transition("loading").On("fail").GoTo("failed"). + Quench() + st := NewMemStore() + h, err := NewRunner(m, st, stepOptions(fn)...).Start(ctx, "s1", stepCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, ran, rerr := h.RunService(ctx, id); rerr != nil || !ran { + t.Fatalf("RunService = %v, %v; want ran with no error", ran, rerr) + } + if got := h.inst.Current(); got != "ready" || h.svc.HasPending(id) { + t.Fatalf("live: in %q with the service pending %v; want ready and settled", got, h.svc.HasPending(id)) + } + if !h.settled[id] { + t.Fatal("the live Handle doesn't note the service settled") + } + _, recs, err := st.Load(ctx, "s1") + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(recs) != 1 { + t.Fatalf("the journal holds %d Records, want the settle's one", len(recs)) + } + rh, err := Recover(ctx, m, st, "s1", stepOptions(fn)...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if got := rh.inst.Current(); got != "ready" || rh.svc.HasPending(id) { + t.Fatalf("recovered: in %q with the service pending %v; want ready and settled, as live", got, rh.svc.HasPending(id)) + } + if _, ran, rerr := rh.RunService(ctx, id); ran || rerr != nil { + t.Fatalf("the recovered RunService = %v, %v; want nothing in flight", ran, rerr) + } + if runs != 1 { + t.Fatalf("the ServiceFn ran %d times, want once", runs) + } +} + +// TestServiceStep_ClearsTheSettledJSON: the JSON a settle decoded is the step's alone. +// Once RunService returns, live or for a parked result, and once Recover has replayed +// the journal, the Handle holds none of it. +func TestServiceStep_ClearsTheSettledJSON(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("step", "loading", 0) + fn := func(context.Context, state.ServiceCtx[stepCtx]) (any, error) { return "ok", nil } + m := stepMachine(fn) + st := NewMemStore() + h, err := NewRunner(m, st, stepOptions(fn)...).Start(ctx, "s1", stepCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + if _, _, err = h.RunService(ctx, id); err != nil { + t.Fatalf("RunService: %v", err) + } + if h.svcJSON.raw != nil { + t.Fatalf("after RunService the Handle holds %s", h.svcJSON.raw) + } + rh, err := Recover(ctx, m, st, "s1", stepOptions(fn)...) + if err != nil { + t.Fatalf("Recover: %v", err) + } + if rh.svcJSON.raw != nil { + t.Fatalf("after Recover the Handle holds %s", rh.svcJSON.raw) + } + + // A parked result's settle. + refuse := WithEventDataDecoder[string, string, stepCtx](func(e string, data []byte) (any, error) { + if e == "done" { + return nil, ErrEventDataEncoding + } + return DecodeAs[any](data) + }) + st = NewMemStore() + if h, err = NewRunner(m, st, append(stepOptions(fn), refuse)...).Start(ctx, "s1", stepCtx{}, state.WithInitialState("loading")); err != nil { + t.Fatalf("Start: %v", err) + } + if _, _, err = h.RunService(ctx, id); err == nil { + t.Fatal("RunService settled a result the decoder refuses") + } + if rh, err = Recover(ctx, m, st, "s1", stepOptions(fn)...); err != nil { + t.Fatalf("Recover: %v", err) + } + if _, _, err = rh.RunService(ctx, id); err != nil { + t.Fatalf("RunService of the parked result: %v", err) + } + if rh.svcJSON.raw != nil { + t.Fatalf("after a parked result's settle the Handle holds %s", rh.svcJSON.raw) + } +} + +// TestServiceBookkeeping_SettledAndParkedMoveTogether pins that the Handle and the +// replay mirror keep a service out of the parked results once it settles, and forget +// both when a state that declares it is entered or exited, through one helper each. +func TestServiceBookkeeping_SettledAndParkedMoveTogether(t *testing.T) { + start := []state.Effect{state.StartService{ID: "a"}} + stop := []state.Effect{state.StopService{ID: "b"}} + h := &Handle[string, string, stepCtx]{parked: map[string]recordedResult{"a": {}, "b": {}}} + h.markSettled("a") + if _, ok := h.parked["a"]; ok || !h.settled["a"] { + t.Fatalf("after markSettled: settled %v, parked %v; want a settled and not parked", h.settled, h.parked) + } + h.settled["b"] = true // b settled in an earlier activation, then parked in this one + h.forgetServices(start) + h.forgetServices(stop) + if len(h.settled) != 0 || len(h.parked) != 0 { + t.Fatalf("after start and stop effects: settled %v, parked %v; want both empty", h.settled, h.parked) + } + + m := &armMirror{} + m.park("a", recordedResult{}) + m.park("b", recordedResult{}) + m.settle("a") + if _, ok := m.parked["a"]; ok || !m.settled["a"] { + t.Fatalf("after settle: settled %v, parked %v; want a settled and not parked", m.settled, m.parked) + } + m.settled["b"] = true + m.forget(start) + m.forget(stop) + if len(m.settled) != 0 || len(m.parked) != 0 { + t.Fatalf("after start and stop effects: settled %v, parked %v; want both empty", m.settled, m.parked) + } +} diff --git a/durable/service_undecodable_settle_test.go b/durable/service_undecodable_settle_test.go index fb5b3b19..7b51ef70 100644 --- a/durable/service_undecodable_settle_test.go +++ b/durable/service_undecodable_settle_test.go @@ -80,98 +80,114 @@ func undecodableOptions(fn state.ServiceFn[svcCtx], p *undecodableProbe) []durab } } -// TestRunService_UndecodableResult_SettlesOnDoneBeforeFailing pins what a ServiceFn -// result whose JSON form won't decode does today, and one with no JSON form at all, -// which takes the same path on the raw result. The live settle runs the onDone -// transition on a stand-in for the result: its Assign runs once and sees that -// stand-in, an unexported durable type, and the state it enters spawns its actor. -// Only then does recording refuse the result, so RunService fails the Handle with -// ErrHandleFailed, records nothing and dispatches nothing. The onError Assign never -// runs. A recovered Handle has the service in flight again and doesn't spawn the -// actor, and running the service again fails the same way. A reducer that asserts -// its event's type unchecked panics on the stand-in; the kernel turns that panic into -// the settle's Fire error, so the Fire doesn't apply, nothing spawns, and RunService -// still returns ErrHandleFailed rather than panicking. -func TestRunService_UndecodableResult_SettlesOnDoneBeforeFailing(t *testing.T) { +// TestRunService_UndecodableResult_ParksBeforeAnyAssign pins what a ServiceFn result +// whose JSON form won't decode does, and one with no JSON form at all. A result that +// encodes but won't decode is parked: RunService returns ErrEventDataEncoding, not +// ErrHandleFailed, before the onDone or onError Assign runs, so the onDone state spawns +// no actor and no effect dispatches. The journal holds one Record for the park, and +// each later RunService records nothing more. A recovered Handle has the service in +// flight and the result still parked, and its ServiceFn doesn't run again. A result +// with no JSON form fails the Handle with ErrHandleFailed, also before any Assign, and +// records nothing, so after Recover the ServiceFn runs again. A reducer that asserts +// its event's type unchecked never sees the result, so it can't panic on it. +func TestRunService_UndecodableResult_ParksBeforeAnyAssign(t *testing.T) { ctx := context.Background() - results := map[string]struct { - result any - seenType string - }{ - "json.Number": {json.Number("1e400"), "durable.undecodableResult"}, - "custom MarshalJSON": {outOfRangeResult{}, "durable.undecodableResult"}, - "json.RawMessage": {json.RawMessage("1e400"), "durable.undecodableResult"}, - // A result with no JSON form at all takes the same path, on the raw result. - "won't encode": {make(chan int), "chan int"}, - } id := state.InvokeID("undecodable", "loading", 0) - for name, tc := range results { + start := func(t *testing.T, result any, assertString bool) (*undecodableProbe, *int, *state.Machine[string, string, svcCtx], *durable.MemStore, []durable.Option[string, string, svcCtx], *durable.Handle[string, string, svcCtx]) { + t.Helper() + calls := new(int) + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { *calls++; return result, nil } + p := &undecodableProbe{} + m := undecodableMachine(fn, p, assertString) + st := durable.NewMemStore() + opts := undecodableOptions(fn, p) + h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", svcCtx{}, state.WithInitialState("loading")) + if err != nil { + t.Fatalf("Start: %v", err) + } + return p, calls, m, st, opts, h + } + untouched := func(t *testing.T, p *undecodableProbe) { + t.Helper() + if p.doneAssigns != 0 || p.errorAssigns != 0 || p.spawns != 0 || p.dispatched != 0 { + t.Fatalf("onDone Assign ran %d times, onError %d, child spawned %d, %d dispatched; want none of them", + p.doneAssigns, p.errorAssigns, p.spawns, p.dispatched) + } + } + journal := func(t *testing.T, st *durable.MemStore, want int) { + t.Helper() + if _, recs, err := st.Load(ctx, "i1"); err != nil || len(recs) != want { + t.Fatalf("journal holds %d Records (err %v), want %d", len(recs), err, want) + } + } + parked := map[string]any{ + "json.Number": json.Number("1e400"), + "custom MarshalJSON": outOfRangeResult{}, + "json.RawMessage": json.RawMessage("1e400"), + } + for name, result := range parked { t.Run(name, func(t *testing.T) { - fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return tc.result, nil } - p := &undecodableProbe{} - m := undecodableMachine(fn, p, false) - st := durable.NewMemStore() - opts := undecodableOptions(fn, p) - h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", svcCtx{}, state.WithInitialState("loading")) - if err != nil { - t.Fatalf("Start: %v", err) + p, calls, m, st, opts, h := start(t, result, false) + _, _, err := h.RunService(ctx, id) + if !errors.Is(err, durable.ErrEventDataEncoding) || errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService = %v, want ErrEventDataEncoding and not ErrHandleFailed", err) } - if _, _, err = h.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { - t.Fatalf("RunService = %v, want ErrHandleFailed", err) - } - if p.doneAssigns != 1 || p.doneEventType != tc.seenType || p.errorAssigns != 0 { - t.Fatalf("onDone Assign ran %d times on %s, onError Assign %d times; want onDone once on %s, onError never", - p.doneAssigns, p.doneEventType, p.errorAssigns, tc.seenType) - } - if p.spawns != 1 || p.dispatched != 0 { - t.Fatalf("child spawned %d times, %d effects dispatched; want the onDone state's actor spawned once and nothing dispatched", p.spawns, p.dispatched) - } - if _, recs, lerr := st.Load(ctx, "i1"); lerr != nil || len(recs) != 0 { - t.Fatalf("journal holds %d Records (err %v), want none", len(recs), lerr) + untouched(t, p) + journal(t, st, 1) + if _, _, err = h.RunService(ctx, id); !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("second RunService = %v, want ErrEventDataEncoding", err) } + journal(t, st, 1) recovered, err := durable.Recover(ctx, m, st, "i1", opts...) if err != nil { t.Fatalf("Recover: %v", err) } - if got := recovered.Instance().Current(); got != "loading" || p.spawns != 1 { - t.Fatalf("recovered in %q, child spawned %d times; want loading, with no new spawn", got, p.spawns) + if got := recovered.Instance().Current(); got != "loading" { + t.Fatalf("recovered in %q, want loading", got) } - if _, _, err = recovered.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { - t.Fatalf("RunService after Recover = %v, want ErrHandleFailed again", err) + if _, _, err = recovered.RunService(ctx, id); !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("RunService after Recover = %v, want ErrEventDataEncoding", err) } - if p.doneAssigns != 2 || p.spawns != 2 { - t.Fatalf("after the retry: onDone Assign ran %d times, child spawned %d; want 2 and 2", p.doneAssigns, p.spawns) + untouched(t, p) + if *calls != 1 { + t.Fatalf("ServiceFn ran %d times, want once: a parked result doesn't run it again", *calls) } }) } - t.Run("unchecked assertion refuses the Fire", func(t *testing.T) { - fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return json.Number("1e400"), nil } - p := &undecodableProbe{} - m := undecodableMachine(fn, p, true) - st := durable.NewMemStore() - opts := undecodableOptions(fn, p) - h, err := durable.NewRunner(m, st, opts...).Start(ctx, "i1", svcCtx{}, state.WithInitialState("loading")) + t.Run("won't encode", func(t *testing.T) { + p, calls, m, st, opts, h := start(t, make(chan int), false) + if _, _, err := h.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService = %v, want ErrHandleFailed", err) + } + untouched(t, p) + journal(t, st, 0) + recovered, err := durable.Recover(ctx, m, st, "i1", opts...) if err != nil { - t.Fatalf("Start: %v", err) + t.Fatalf("Recover: %v", err) + } + if _, _, err = recovered.RunService(ctx, id); !errors.Is(err, durable.ErrHandleFailed) { + t.Fatalf("RunService after Recover = %v, want ErrHandleFailed again", err) + } + untouched(t, p) + if *calls != 2 { + t.Fatalf("ServiceFn ran %d times, want twice: nothing was recorded, so it runs again after Recover", *calls) } + }) + t.Run("unchecked assertion never sees the result", func(t *testing.T) { + p, _, _, st, _, h := start(t, json.Number("1e400"), true) var panicked any - var res state.FireResult[string] + var err error func() { defer func() { panicked = recover() }() - res, _, err = h.RunService(ctx, id) + _, _, err = h.RunService(ctx, id) }() - if panicked != nil || !errors.Is(err, durable.ErrHandleFailed) { - t.Fatalf("RunService panicked %v, returned %v; want ErrHandleFailed and no panic", panicked, err) - } - if res.Err == nil || p.doneAssigns != 1 || p.spawns != 0 || p.dispatched != 0 { - t.Fatalf("settle's Fire error %v, onDone Assign ran %d times, child spawned %d, %d dispatched; want the Fire refused for the panic after one Assign, and no spawn or dispatch", - res.Err, p.doneAssigns, p.spawns, p.dispatched) + if panicked != nil || !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("RunService panicked %v, returned %v; want ErrEventDataEncoding and no panic", panicked, err) } + untouched(t, p) if got := h.Instance().Current(); got != "loading" { - t.Fatalf("live instance in %q, want loading: the refused Fire didn't apply", got) - } - if _, recs, lerr := st.Load(ctx, "i1"); lerr != nil || len(recs) != 0 { - t.Fatalf("journal holds %d Records (err %v), want none", len(recs), lerr) + t.Fatalf("live instance in %q, want loading", got) } + journal(t, st, 1) }) } diff --git a/durable/settle_absorb_internal_test.go b/durable/settle_absorb_internal_test.go index 272d2c34..ab3ee44f 100644 --- a/durable/settle_absorb_internal_test.go +++ b/durable/settle_absorb_internal_test.go @@ -2,6 +2,7 @@ package durable import ( "context" + "errors" "fmt" "reflect" "testing" @@ -49,6 +50,17 @@ func absorbMachine(svcA, svcB state.ServiceFn[absorbCtx]) *state.Machine[string, Quench() } +// serviceArms reads how many service activations svc has armed: the ServiceRunner +// numbers each one it absorbs, so the count is the activations it absorbed. +func serviceArms[S comparable, E comparable, C any](t *testing.T, svc *state.ServiceRunner[S, E, C]) uint64 { + t.Helper() + f := reflect.ValueOf(svc).Elem().FieldByName("gen") + if !f.IsValid() { + t.Fatal("state.ServiceRunner has no gen field; update serviceArms") + } + return f.Uint() +} + // TestRunService_SettleArmsItsFollowOnServiceOnce: svcA's onDone enters a state that // invokes svcB. Live, the settle arms svcB once, as the replay of the journal does, so // the live runner and a recovered one have armed the same activations; a checkpoint @@ -83,9 +95,17 @@ func TestRunService_SettleArmsItsFollowOnServiceOnce(t *testing.T) { if err != nil { t.Fatalf("Start: %v", err) } + if got := serviceArms(t, h.svc); got != 1 { + t.Fatalf("Start armed %d service activations, want 1 (svcA)", got) + } if ok, rerr := runOnce(ctx, h, aID); rerr != nil || !ok { t.Fatalf("RunService(svcA) = %v, %v", ok, rerr) } + // svcA's activation, then svcB's, once. + live := serviceArms(t, h.svc) + if live != 2 { + t.Errorf("live: the runner armed %d service activations, want 2: the settle armed svcB more than once", live) + } if len(h.timers) != 1 { t.Errorf("live: the timer table is %v, want second's timer armed", h.timers) } @@ -96,6 +116,9 @@ func TestRunService_SettleArmsItsFollowOnServiceOnce(t *testing.T) { if run, err = Recover(ctx, m, store, "a1", opts...); err != nil { t.Fatalf("Recover: %v", err) } + if got := serviceArms(t, run.svc); got != live { + t.Errorf("journal: the recovered runner armed %d service activations, the live one %d", got, live) + } case "checkpoint": snap, tail, lerr := store.Load(ctx, "a1") if lerr != nil || len(tail) != 0 || snap == nil { @@ -104,6 +127,10 @@ func TestRunService_SettleArmsItsFollowOnServiceOnce(t *testing.T) { if run, err = Recover(ctx, m, store, "a1", opts...); err != nil { t.Fatalf("Recover: %v", err) } + // The checkpoint restores the one service in flight, svcB. + if got := serviceArms(t, run.svc); got != 1 { + t.Errorf("checkpoint: the recovered runner armed %d service activations, want 1 (svcB)", got) + } } if !run.svc.HasPending(bID) || run.svc.Pending() != 1 { t.Fatalf("%s: svcB in flight = %v with %d pending, want svcB alone", mode, run.svc.HasPending(bID), run.svc.Pending()) @@ -127,6 +154,37 @@ func TestRunService_SettleArmsItsFollowOnServiceOnce(t *testing.T) { } } +// TestUndecodableResult_WrapsErrEventDataEncodingOnlyForADecodeFailure pins what the +// abort replayableOutcome returns wraps: a result that won't decode wraps +// ErrEventDataEncoding, as the park RunService returns does; one with no JSON form +// wraps no sentinel, since serviceStep fails the Handle for it. +func TestUndecodableResult_WrapsErrEventDataEncodingOnlyForADecodeFailure(t *testing.T) { + refuse := func(string, []byte) (any, error) { return nil, errors.New("decoder refused") } + for _, tc := range []struct { + name string + result any + wantRaw bool + encoding bool + }{ + {"won't decode", "ok", true, true}, + {"won't encode", make(chan int), false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + _, _, abort := replayableOutcome[string](refuse, &settledJSON{})("done", tc.result, nil) + var derr *undecodableResult + if !errors.As(abort, &derr) { + t.Fatalf("abort = %v, want an *undecodableResult", abort) + } + if got := derr.raw != nil; got != tc.wantRaw { + t.Errorf("raw = %q, want raw %v", derr.raw, tc.wantRaw) + } + if got := errors.Is(derr, ErrEventDataEncoding); got != tc.encoding { + t.Errorf("errors.Is(%v, ErrEventDataEncoding) = %v, want %v", derr, got, tc.encoding) + } + }) + } +} + // TestRunService_SettleThatReentersItsStateForgetsTheSettle: svcA's onDone leaves and // re-enters the state that invokes it, so the settle starts a new activation of svcA. // With the services left to the settle's own absorb, serviceStep must still forget that diff --git a/durable/settled_type_test.go b/durable/settled_type_test.go new file mode 100644 index 00000000..e6513fad --- /dev/null +++ b/durable/settled_type_test.go @@ -0,0 +1,102 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/durable" + "github.com/stablekernel/crucible/state" +) + +// These tests answer a review finding on a result that settles when its service runs: +// its Record kept no Go type, only a parked result's did, so replay let the decoder +// return any type, though the live settle held it to the type the ServiceFn returned. +// Every successful settle in a Record of this format now records the type, and replay +// holds the decoder to it as for a settled parked result. + +// settledUser runs the scn service live, settling a scnUser under live, and returns +// what Recover needs. +func settledUser(t *testing.T, fn state.ServiceFn[svcCtx], live ...durable.Option[string, string, svcCtx]) (*state.Machine[string, string, svcCtx], *scnAssigns, durable.Option[string, string, svcCtx], *durable.MemStore) { + t.Helper() + a := &scnAssigns{} + m := scnMachine(fn, a) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + store := durable.NewMemStore() + h := scnStart(t, m, store, append([]durable.Option[string, string, svcCtx]{reg}, live...)...) + mustRunService(t, h, state.InvokeID(scnInvoke, "loading", 0)) + return m, a, reg, store +} + +// TestServiceResult_SettledRecordKeepsTheType: a scnUser settled live under a decoder +// for it records its type, and a Recover whose decoder returns another type, a pointer +// to it or another struct, fails with ErrEventDataEncoding and runs no Assign, as for a +// settled parked result (see TestParkedResult_SettledRecordKeepsTheType). The same +// decoder, and JSON's generic form, still replay it. +func TestServiceResult_SettledRecordKeepsTheType(t *testing.T) { + ctx := context.Background() + userType := "github.com/stablekernel/crucible/durable_test.scnUser" + for _, tc := range []struct { + name string + live []durable.Option[string, string, svcCtx] + }{ + {"decoded live as its type", []durable.Option[string, string, svcCtx]{decoderFor("done", durable.DecodeAs[scnUser])}}, + {"decoded live as JSON's generic form", nil}, + } { + t.Run(tc.name, func(t *testing.T) { + m, a, reg, store := settledUser(t, returning(scnUser{ID: 7, Name: "ann"}, nil), tc.live...) + if got := serviceTypes(t, store); len(got) != 1 || got[0] != userType { + t.Fatalf("the settle records the type %q, want %s", got, userType) + } + for _, wrong := range []struct { + name string + opt durable.Option[string, string, svcCtx] + }{ + {"a pointer to it", decoderFor("done", durable.DecodeAs[*scnUser])}, + {"another struct", decoderFor("done", durable.DecodeAs[scnAdmin])}, + } { + done := a.done + _, err := durable.Recover(ctx, m, store, "scn-1", reg, wrong.opt) + if !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Recover with a decoder for %s: %v, want ErrEventDataEncoding", wrong.name, err) + } + if a.done != done { + t.Fatalf("replay ran onDone's Assign with %s, a type the live settle refuses", describe(a.seen[len(a.seen)-1])) + } + } + for _, right := range []struct { + name string + opt []durable.Option[string, string, svcCtx] + }{ + {"its own type", []durable.Option[string, string, svcCtx]{decoderFor("done", durable.DecodeAs[scnUser])}}, + {"JSON's generic form", nil}, + } { + if _, err := durable.Recover(ctx, m, store, "scn-1", append([]durable.Option[string, string, svcCtx]{reg}, right.opt...)...); err != nil { + t.Fatalf("Recover with a decoder for %s: %v", right.name, err) + } + } + }) + } +} + +// TestServiceResult_SettledNilResultReplays: a nil result settles and replays under any +// decoder, as live: it arrives as nil whatever the decoder (see +// TestServiceResult_NilResult_ArrivesNil). +func TestServiceResult_SettledNilResultReplays(t *testing.T) { + ctx := context.Background() + m, a, reg, store := settledUser(t, returning(nil, nil), decoderFor("done", durable.DecodeAs[scnUser])) + for _, opt := range []durable.Option[string, string, svcCtx]{ + decoderFor("done", durable.DecodeAs[scnUser]), + decoderFor("done", durable.DecodeAs[scnAdmin]), + decoderFor("done", durable.DecodeAs[any]), + } { + if _, err := durable.Recover(ctx, m, store, "scn-1", reg, opt); err != nil { + t.Fatalf("Recover: %v", err) + } + } + for i, v := range a.seen { + if v != nil { + t.Fatalf("run %d saw %s, want nil", i, describe(v)) + } + } +} diff --git a/durable/store.go b/durable/store.go index 033cd3d4..6e51cd5f 100644 --- a/durable/store.go +++ b/durable/store.go @@ -126,7 +126,12 @@ type Record struct { // 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. + // different number of timers than TickSteps. From format 4 the live run decoded each + // service result through WithEventDataDecoder, and replay does too; a result in an + // older Record replays in JSON's generic form, as that version replayed it. A Store + // keeps it as it keeps Step. A version reads up to the format it writes: Recover, + // StateAt and Steps refuse a journal with a Record or checkpoint of a higher format, + // one a newer version wrote. Versions built before that check don't refuse one. Format int `json:",omitempty"` } diff --git a/durable/tick_service_checkpoint_test.go b/durable/tick_service_checkpoint_test.go deleted file mode 100644 index d34e7251..00000000 --- a/durable/tick_service_checkpoint_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package durable_test - -import ( - "context" - "sync/atomic" - "testing" - "time" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// These tests pin what a Tick does to a service in flight: a timer transition hands its -// effects to the service runner, as a Fire does, so a timer that leaves the state that -// declares the service stops it, and one that re-enters the state starts a fresh -// activation. The live Handle, one recovered from the journal and one recovered from a -// checkpoint agree. - -var timerSvc = state.InvokeID("tsvc", "loading", 0) - -// timerSvcMachine invokes fn in "loading", which "begin" enters from "prep", itself -// entered from "idle" by "prep", so a run's Tick can land on a checkpoint. Its after -// timer leaves for "timedOut", or with reenter re-enters "loading". -func timerSvcMachine(fn state.ServiceFn[svcCtx], reenter bool) *state.Machine[string, string, svcCtx] { - f := state.ForgeFor[svcCtx]("tsvc"). - Service("fetch", fn). - State("idle"). - State("prep"). - State("loading").Invoke("fetch", state.WithInvokeOnDone("done")). - State("ready").Final(). - State("timedOut"). - Initial("idle"). - Transition("idle").On("prep").GoTo("prep"). - Transition("prep").On("begin").GoTo("loading"). - Transition("loading").On("done").GoTo("ready") - if reenter { - f = f.Transition("loading").After(5 * time.Second).On("redo").GoTo("loading").Reenter() - } else { - f = f.Transition("loading").After(5 * time.Second).On("timeout").GoTo("timedOut") - } - return f.Quench() -} - -// timerSvcRun starts an instance of timerSvcMachine, fires prep and begin, so loading's -// service is in flight, and Ticks its after timer, failing unless the timer fired. -// Every third step checkpoints, so the Tick's Record carries a checkpoint and anything -// recorded after it follows the checkpoint. -func timerSvcRun(t *testing.T, reenter bool) (*durable.Handle[string, string, svcCtx], *state.Machine[string, string, svcCtx], *durable.MemStore, []durable.Option[string, string, svcCtx], *int64) { - t.Helper() - ctx := context.Background() - runs := new(int64) - fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { - return atomic.AddInt64(runs, 1), nil - } - m := timerSvcMachine(fn, reenter) - clk := state.NewFakeClock(epoch) - store := durable.NewMemStore() - opts := []durable.Option[string, string, svcCtx]{ - durable.WithRunnerClock[string, string, svcCtx](clk), - durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)), - durable.WithCheckpointEvery[string, string, svcCtx](3), - } - h, err := durable.NewRunner(m, store, opts...).Start(ctx, "t-1", svcCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatalf("Start: %v", err) - } - for _, ev := range []string{"prep", "begin"} { - if _, err = h.Fire(ctx, ev); err != nil { - t.Fatalf("Fire %s: %v", ev, err) - } - } - clk.Advance(6 * time.Second) - if results, terr := h.Tick(ctx); terr != nil || len(results) != 1 { - t.Fatalf("Tick = %d results, %v; want the timer to fire", len(results), terr) - } - if ckpt, recs, lerr := store.Load(ctx, "t-1"); lerr != nil || len(ckpt) == 0 || len(recs) != 0 { - t.Fatalf("after the Tick the store holds a %d-byte checkpoint and %d Records (%v); want the Tick's checkpoint and nothing after it", len(ckpt), len(recs), lerr) - } - return h, m, store, opts, runs -} - -// TestTimerLeavingTheState_SettleAfterCheckpointStaysRecoverable: loading's service is -// in flight, its after timer leaves for timedOut, the Tick's Record carries a -// checkpoint, which holds only the services of the states the instance is in, and the -// live Handle then calls RunService. While Tick left the service in flight, that ran it -// and journaled its settle after the checkpoint, which replay couldn't apply ("no -// in-flight service to settle"), so every Recover failed. Now the timer stopped the -// service: RunService finds nothing in flight, records nothing, and every Recover -// succeeds. -func TestTimerLeavingTheState_SettleAfterCheckpointStaysRecoverable(t *testing.T) { - ctx := context.Background() - h, m, store, opts, runs := timerSvcRun(t, false) - _, ran, rerr := h.RunService(ctx, timerSvc) - for i := range 2 { - rh, err := durable.Recover(ctx, m, store, "t-1", opts...) - if err != nil { - t.Fatalf("Recover %d: %v; want the instance recoverable", i, err) - } - if got := rh.Instance().Current(); got != "timedOut" { - t.Fatalf("Recover %d in %q, want timedOut", i, got) - } - if _, hran, herr := rh.RunService(ctx, timerSvc); hran || herr != nil { - t.Fatalf("RunService after Recover %d = %v, %v; want nothing in flight", i, hran, herr) - } - } - if ran || rerr != nil || atomic.LoadInt64(runs) != 0 { - t.Fatalf("live RunService after the Tick = %v, %v with the ServiceFn run %d times; want nothing in flight: the timer stopped the service", ran, rerr, atomic.LoadInt64(runs)) - } -} - -// TestTimerReenteringTheState_SettleAfterCheckpointRunsTheFreshActivation: the timer -// re-enters loading, so the Tick stops the old activation and starts a fresh one, and -// the checkpoint the Tick's Record carries holds it in flight. RunService on the live -// Handle runs it, and a Recover after that settle, which follows the checkpoint, replays -// it and ends in ready, as live did, with the ServiceFn run once. -func TestTimerReenteringTheState_SettleAfterCheckpointRunsTheFreshActivation(t *testing.T) { - ctx := context.Background() - h, m, store, opts, runs := timerSvcRun(t, true) - if _, ran, err := h.RunService(ctx, timerSvc); !ran || err != nil { - t.Fatalf("live RunService after the Tick = %v, %v; want the fresh activation run and settled", ran, err) - } - if got := h.Instance().Current(); got != "ready" { - t.Fatalf("live in %q, want ready", got) - } - rh, err := durable.Recover(ctx, m, store, "t-1", opts...) - if err != nil { - t.Fatalf("Recover after the settle: %v; want the instance recoverable", err) - } - if got := rh.Instance().Current(); got != "ready" { - t.Fatalf("recovered in %q, want ready, as live", got) - } - if _, ran, rerr := rh.RunService(ctx, timerSvc); ran || rerr != nil { - t.Fatalf("RunService after Recover = %v, %v; want nothing in flight", ran, rerr) - } - if got := atomic.LoadInt64(runs); got != 1 { - t.Fatalf("the ServiceFn ran %d times, want once", got) - } -} diff --git a/durable/timetravel.go b/durable/timetravel.go index 66b647de..09240acd 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -103,9 +103,13 @@ func (v *TimeTravelView[S, E, C]) Step() int { return v.step } // // step must be in [BaselineStep, lastRecordedStep]; a step outside that range // reports ErrStepOutOfRange, an unknown instance reports ErrInstanceNotFound, and an -// ended ctx reports its error. 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. +// ended ctx reports its error. A journal a newer version wrote, whose baseline or any +// Record records a journal format above this version's, is refused whatever the step, +// as Recover refuses it, and so is one mixed versions wrote, where any Record, before +// or after step, records a lower format than one before it. +// It also fails when a baseline timer's event won't decode with the event codec passed, +// and when a tick of journal format 3 or later fires a different number of timers on +// replay than it recorded. func StateAt[S comparable, E comparable, C any]( ctx context.Context, m *state.Machine[S, E, C], @@ -123,6 +127,10 @@ func StateAt[S comparable, E comparable, C any]( if baseline == nil { return nil, fmt.Errorf("durable: instance %q has no baseline to reconstruct", id) } + format := unmarshalCheckpoint(baseline).Format + if err = checkJournal(id, format, records); err != nil { + return nil, err + } last := lastStep(records) if step < BaselineStep || step > last { @@ -152,12 +160,16 @@ func StateAt[S comparable, E comparable, C any]( // 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. +// ErrInstanceNotFound, and a journal a newer version, or mixed versions, wrote is +// refused, as StateAt refuses it. func Steps(ctx context.Context, st Store, id InstanceID) ([]int, error) { - _, records, err := loadHistory(ctx, st, id) + baseline, records, err := loadHistory(ctx, st, id) if err != nil { return nil, err } + if err = checkJournal(id, unmarshalCheckpoint(baseline).Format, records); err != nil { + return nil, err + } out := make([]int, 0, len(records)) for i := range records { out = append(out, records[i].Step) @@ -165,6 +177,20 @@ func Steps(ctx context.Context, st Store, id InstanceID) ([]int, error) { return out, nil } +// checkJournal refuses a journal Recover refuses, whatever step a reader targets: one +// a newer version wrote (see checkNotNewer), or one mixed versions wrote (see +// checkFormats). It checks every loaded Record, not only those up to a target step, so +// StateAt and Steps refuse the same journals at every step. +func checkJournal(id InstanceID, baseline int, records []Record) error { + if err := checkNotNewer(id, baseline, records); err != nil { + return err + } + if err := checkFormats(baseline, records); err != nil { + return fmt.Errorf("durable: reading %q: %w", id, err) + } + return nil +} + // loadHistory returns an instance's baseline snapshot and full ordered Record log, // using the HistoryStore seam when the Store implements it (so a compacted step is // still reachable) and falling back to Load's latest-checkpoint-plus-tail otherwise. @@ -226,7 +252,8 @@ func restoreBaseline[S comparable, E comparable, C any]( // It is the bounded, read-only analog of Recover's replay loop: it builds its own // service host driver (to settle recorded outcomes) and ticks a scheduler over the // instance's recorded-instant clock, consuming exactly the records the caller bounded -// to the target step. +// to the target step. StateAt has already checked the formats of every Record, those +// past the window too. func replayThrough[S comparable, E comparable, C any]( ctx context.Context, inst *state.Instance[S, E, C], @@ -265,9 +292,6 @@ func replayThrough[S comparable, E comparable, C any]( } // A domain effect is never dispatched here: a time-travel read applies no // side effect. - if err := checkFormat(env.Format, &bounded[i]); err != nil { - return err - } reads += clockReadCount(&bounded[i]) if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, armsActorFires(&bounded[i])); err != nil { return err @@ -305,5 +329,5 @@ func newReplayServiceRunner[S comparable, E comparable, C any]( if cfg.serviceReg == nil { return nil } - return state.NewServiceRunner(inst, cfg.serviceReg) + return state.NewServiceRunner(inst, cfg.serviceReg).WithResultTransform(replayableOutcome(cfg.eventDataDecoder, nil)) } diff --git a/durable/typename_internal_test.go b/durable/typename_internal_test.go new file mode 100644 index 00000000..f3513c36 --- /dev/null +++ b/durable/typename_internal_test.go @@ -0,0 +1,95 @@ +package durable + +import ( + "testing" + + alpha "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model" + beta "github.com/stablekernel/crucible/durable/internal/typefixture/beta/model" +) + +// TestTypeName_UnnamedTypesKeepTheImportPath answers whether a parked result's type +// name tells two packages' types apart inside an unnamed type: a struct literal, func +// or chan spelled from alpha's model.Result must differ from one spelled from beta's, +// as the named types do, or a decoder for the one settles a result parked as the other. +// A struct's tags and its unexported fields' packages are part of its type, so they +// are part of the name too. +func TestTypeName_UnnamedTypesKeepTheImportPath(t *testing.T) { + type tagged struct { + R alpha.Result `json:"r"` + } + cases := []struct { + name string + a, b any + }{ + {"named", alpha.Result{}, beta.Result{}}, + {"struct field", struct{ R alpha.Result }{}, struct{ R beta.Result }{}}, + {"embedded field", struct{ alpha.Result }{}, struct{ beta.Result }{}}, + {"nested struct", struct{ S struct{ R *alpha.Result } }{}, struct{ S struct{ R *beta.Result } }{}}, + {"struct in a slice", []struct{ R alpha.Result }{}, []struct{ R beta.Result }{}}, + {"tag", struct { + R alpha.Result `json:"r"` + }{}, struct { + R alpha.Result `json:"x"` + }{}}, + {"named struct vs literal", tagged{}, struct { + R alpha.Result `json:"r"` + }{}}, + {"func", func(alpha.Result) error { return nil }, func(beta.Result) error { return nil }}, + {"func result", func() alpha.Result { return alpha.Result{} }, func() beta.Result { return beta.Result{} }}, + {"chan", make(chan alpha.Result), make(chan beta.Result)}, + {"chan direction", make(<-chan alpha.Result), make(chan<- alpha.Result)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if a, b := typeName(tc.a), typeName(tc.b); a == b { + t.Fatalf("typeName gives %q for both %T and %T", a, tc.a, tc.b) + } + }) + } +} + +// TestTypeName_SpellsUnnamedTypesAsGoDoes pins the form: reflect's own spelling, with +// every named type's import path in place of its package name, so a type with no +// named parts reads as reflect gives it. +func TestTypeName_SpellsUnnamedTypesAsGoDoes(t *testing.T) { + const a = "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model.Result" + cases := []struct { + v any + want string + }{ + {struct{}{}, "struct {}"}, + {struct { + A int + B string `json:"b"` + }{}, `struct { A int; B string "json:\"b\"" }`}, + {struct{ R alpha.Result }{}, "struct { R " + a + " }"}, + {struct{ alpha.Result }{}, "struct { " + a + " }"}, + {struct{ r alpha.Result }{}, "struct { github.com/stablekernel/crucible/durable.r " + a + " }"}, + {func(int, ...alpha.Result) (bool, error) { return false, nil }, "func(int, ..." + a + ") (bool, error)"}, + {func() alpha.Result { return alpha.Result{} }, "func() " + a}, + {func() {}, "func()"}, + {make(chan alpha.Result), "chan " + a}, + {make(<-chan alpha.Result), "<-chan " + a}, + {make(chan<- alpha.Result), "chan<- " + a}, + {make(chan (<-chan int)), "chan (<-chan int)"}, + {map[string][]struct{ N int }{}, "map[string][]struct { N int }"}, + } + for _, tc := range cases { + if got := typeName(tc.v); got != tc.want { + t.Errorf("typeName(%T) = %q, want %q", tc.v, got, tc.want) + } + } +} + +// TestTypeName_InterfaceFieldKeepsTheImportPath covers an interface literal inside a +// struct literal, the one place an interface type can appear in a value's type. +func TestTypeName_InterfaceFieldKeepsTheImportPath(t *testing.T) { + a := typeName(struct{ X interface{ M() alpha.Result } }{}) + b := typeName(struct{ X interface{ M() beta.Result } }{}) + if a == b { + t.Fatalf("typeName gives %q for both", a) + } + if got, want := typeName(struct{ X any }{}), "struct { X interface {} }"; got != want { + t.Fatalf("typeName = %q, want %q", got, want) + } +} diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 632deef1..2763d187 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -36,10 +36,16 @@ counts as an additive (minor) versus breaking (major) change. Use the onError doesn't escalate again, since its start already escalated it; a respawned actor's own failure with no onError does. The durable runner's `Recover` uses it for the actors that were running. It's additive, within v1.1.0. -- **`ServiceRunner.WithResultTransform`** rewrites a service's outcome before `Tick` - settles it, so a host that records outcomes can give the live run what a replay will see. - An unbound service still settles through onError: a transform that returns no error for - its `UnboundRefError` doesn't make it succeed. +- **`ServiceRunner.WithResultTransform`** rewrites every service outcome before it + settles, whether `Tick`, `SettleDone` or `SettleError` settles it, so a host that records + outcomes can give the live run and a replay the same value. The transform takes the + event that will carry the outcome, the invocation's onDone for a result and its onError + for an error: `func(event E, result any, err error) (out any, outErr error, abort error)`. + It runs before any event fires and before the service is dropped. A non-nil `abort` + stops the settle: no event fires, the service stays in flight, `SettleDone` and + `SettleError` return false with `abort` in `FireResult.Err`, and `Tick` returns that + `FireResult` as its one element. An unbound service still settles through onError: a + transform that returns no error for its `UnboundRefError` doesn't make it succeed. - **`FireEventData`** reports the payload a `WithEventData` option carries, so a host that records a Fire can persist it. It's additive, so the next release is v1.1.0. - **Callbacks get the step's context.** `GuardCtx`, `ActionCtx` and `AssignCtx` have a new @@ -76,6 +82,16 @@ counts as an additive (minor) versus breaking (major) change. Use the whole system, so a message another goroutine's delivery sent the parent while it ran was dropped. The quiet now rides the call chain that spawns each actor, and ends when `AbsorbRespawn` returns. +- **A `ServiceRunner` settle can't settle a later activation of its service.** A + `SettleDone` or `SettleError` whose result transform was running, or a `Tick` whose + `ServiceFn` was running, while the service was stopped and armed again under the same + invoke id, settled the new activation with the old outcome. It now returns false, or + an empty slice from `Tick`, as for an id not in flight, fires nothing, and leaves the + new activation in flight. That holds when the transform aborts too: a stale abort + returns no `Err`, since the activation it ran for is gone, where it used to return the + abort as if the service were still in flight. A `Tick` that returns a `FireResult` has + fired its event, or been aborted with the service still in flight, whatever that + `FireResult` holds. ## [1.0.0] — 2026-06-13 diff --git a/state/result_transform_test.go b/state/result_transform_test.go index 71d81fa5..d9dc9334 100644 --- a/state/result_transform_test.go +++ b/state/result_transform_test.go @@ -9,33 +9,42 @@ import ( "github.com/stablekernel/crucible/state" ) -// TestWithResultTransform_RewritesTheOutcomeTickSettles proves Tick settles a bound -// service with the transform's outcome, a result or an error, and that LastResult and -// LastError report the rewritten form. -func TestWithResultTransform_RewritesTheOutcomeTickSettles(t *testing.T) { - ctx := context.Background() - upper := func(result any, err error) (any, error) { +// upperTransform uppercases a string result and wraps an error's message, and notes +// the event it was given for each outcome in *events. +func upperTransform(events *[]string) func(string, any, error) (any, error, error) { + return func(event string, result any, err error) (any, error, error) { + *events = append(*events, event) if err != nil { - return nil, errors.New("wrapped: " + err.Error()) + return nil, errors.New("wrapped: " + err.Error()), nil } - return strings.ToUpper(result.(string)), nil + return strings.ToUpper(result.(string)), nil, nil } +} + +// TestWithResultTransform_RewritesTheOutcomeTickSettles proves Tick settles a bound +// service with the transform's outcome, a result or an error, that LastResult and +// LastError report the rewritten form, and that the transform gets onDone's event for +// a result and onError's for an error. +func TestWithResultTransform_RewritesTheOutcomeTickSettles(t *testing.T) { + ctx := context.Background() cases := []struct { name string fn state.ServiceFn[*trec] wantState string wantNotes string + wantEvent string }{ - {"result", func(context.Context, state.ServiceCtx[*trec]) (any, error) { return "payload", nil }, "ready", "result:PAYLOAD"}, - {"error", func(context.Context, state.ServiceCtx[*trec]) (any, error) { return nil, errors.New("boom") }, "errored", "error:wrapped: boom"}, + {"result", func(context.Context, state.ServiceCtx[*trec]) (any, error) { return "payload", nil }, "ready", "result:PAYLOAD", "ok"}, + {"error", func(context.Context, state.ServiceCtx[*trec]) (any, error) { return nil, errors.New("boom") }, "errored", "error:wrapped: boom", "fail"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { var run *state.ServiceRunner[string, string, *trec] + var events []string m := invokeMachine(&run) entity := &trec{} inst := m.Cast(entity, state.WithInitialState("idle")) - run = state.NewServiceRunner(inst, state.NewRegistry[*trec]().Service("fetch", tc.fn)).WithResultTransform(upper) + run = state.NewServiceRunner(inst, state.NewRegistry[*trec]().Service("fetch", tc.fn)).WithResultTransform(upperTransform(&events)) run.Absorb(ctx, inst.Fire(ctx, "start").Effects) res := run.Tick(ctx, state.InvokeID("loader", "loading", 0)) if len(res) != 1 || res[0].NewState != tc.wantState { @@ -44,10 +53,166 @@ func TestWithResultTransform_RewritesTheOutcomeTickSettles(t *testing.T) { if got := join(entity.notes); got != tc.wantNotes { t.Fatalf("notes = %q, want %q", got, tc.wantNotes) } + if len(events) != 1 || events[0] != tc.wantEvent { + t.Fatalf("the transform got events %q, want [%q]", events, tc.wantEvent) + } + }) + } +} + +// TestWithResultTransform_AppliesToSettleDoneAndSettleError proves the transform runs +// on an outcome a host settles directly, as a replay does, with the event that carries +// it. +func TestWithResultTransform_AppliesToSettleDoneAndSettleError(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("loader", "loading", 0) + cases := []struct { + name string + settle func(*state.ServiceRunner[string, string, *trec]) (state.FireResult[string], bool) + wantState string + wantNotes string + wantEvent string + }{ + {"SettleDone", func(r *state.ServiceRunner[string, string, *trec]) (state.FireResult[string], bool) { + return r.SettleDone(ctx, id, "payload") + }, "ready", "result:PAYLOAD", "ok"}, + {"SettleError", func(r *state.ServiceRunner[string, string, *trec]) (state.FireResult[string], bool) { + return r.SettleError(ctx, id, errors.New("boom")) + }, "errored", "error:wrapped: boom", "fail"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var run *state.ServiceRunner[string, string, *trec] + var events []string + m := invokeMachine(&run) + entity := &trec{} + inst := m.Cast(entity, state.WithInitialState("idle")) + run = state.NewServiceRunner(inst, nil).WithResultTransform(upperTransform(&events)) + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + res, ok := tc.settle(run) + if !ok || res.NewState != tc.wantState { + t.Fatalf("settled to %+v (%v), want %q", res, ok, tc.wantState) + } + if got := join(entity.notes); got != tc.wantNotes { + t.Fatalf("notes = %q, want %q", got, tc.wantNotes) + } + if len(events) != 1 || events[0] != tc.wantEvent { + t.Fatalf("the transform got events %q, want [%q]", events, tc.wantEvent) + } + }) + } +} + +// TestWithResultTransform_AbortFiresNoEvent proves a transform that aborts stops the +// settle, whether Tick, SettleDone or SettleError drives it: no event fires, so no +// Assign, inspector or history entry; the caller gets the abort in FireResult.Err, with +// false from SettleDone and SettleError and as Tick's one element; LastResult and +// LastError keep the previous settle; and the service stays in flight, so a later +// settle the transform lets through routes it. +func TestWithResultTransform_AbortFiresNoEvent(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("loader", "loading", 0) + refused := errors.New("refused") + fetch := func(context.Context, state.ServiceCtx[*trec]) (any, error) { return "payload", nil } + cases := []struct { + name string + settle func(*state.ServiceRunner[string, string, *trec]) (state.FireResult[string], bool) + }{ + {"Tick", func(r *state.ServiceRunner[string, string, *trec]) (state.FireResult[string], bool) { + res := r.Tick(ctx, id) + if len(res) != 1 { + t.Fatalf("Tick returned %d results, want 1", len(res)) + } + return res[0], false + }}, + {"SettleDone", func(r *state.ServiceRunner[string, string, *trec]) (state.FireResult[string], bool) { + return r.SettleDone(ctx, id, "payload") + }}, + {"SettleError", func(r *state.ServiceRunner[string, string, *trec]) (state.FireResult[string], bool) { + return r.SettleError(ctx, id, errors.New("boom")) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var run *state.ServiceRunner[string, string, *trec] + m := invokeMachine(&run) + entity := &trec{} + var inspected int + inst := m.Cast(entity, state.WithInitialState("idle"), state.WithUnboundedHistory[string](), + state.WithInspector[string](state.InspectorFunc(func(state.InspectionEvent) { inspected++ }))) + abort := true + run = state.NewServiceRunner(inst, state.NewRegistry[*trec]().Service("fetch", fetch)). + WithResultTransform(func(_ string, result any, err error) (any, error, error) { + if abort { + return "ignored", nil, refused + } + return result, err, nil + }) + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + history, events := len(inst.History()), inspected + + res, ok := tc.settle(run) + if ok || !errors.Is(res.Err, refused) { + t.Fatalf("an aborted settle returned %+v, %v; want false and the abort in Err", res, ok) + } + if res.NewState != "" || len(res.Effects) != 0 { + t.Fatalf("an aborted settle returned %+v, want no state or effects", res) + } + if got := inst.Current(); got != "loading" || len(entity.notes) != 0 { + t.Fatalf("after the abort the instance is in %q with notes %q, want loading and none", got, entity.notes) + } + if len(inst.History()) != history || inspected != events { + t.Fatalf("the abort added %d history entries and %d inspection events, want none", + len(inst.History())-history, inspected-events) + } + if _, ok := run.LastResult(); ok || run.LastError() != nil { + t.Fatalf("the abort set LastResult or LastError (%v)", run.LastError()) + } + if !run.HasPending(id) { + t.Fatalf("the aborted service isn't in flight, want it kept") + } + + // The service is still in flight, so a settle the transform lets through + // routes it. + abort = false + res, _ = tc.settle(run) + if res.Err != nil || res.NewState == "" || run.HasPending(id) { + t.Fatalf("settling after the abort gave %+v, pending %v; want it routed", res, run.HasPending(id)) + } }) } } +// TestWithResultTransform_PanicLeavesServiceInFlight proves a transform that panics +// panics out of the settle, as any host panic does, before any event fires and +// before the service is dropped. +func TestWithResultTransform_PanicLeavesServiceInFlight(t *testing.T) { + ctx := context.Background() + var run *state.ServiceRunner[string, string, *trec] + m := invokeMachine(&run) + entity := &trec{} + inst := m.Cast(entity, state.WithInitialState("idle")) + run = state.NewServiceRunner(inst, nil).WithResultTransform(func(string, any, error) (any, error, error) { + panic("boom") + }) + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + id := state.InvokeID("loader", "loading", 0) + func() { + defer func() { + if p := recover(); p != "boom" { + t.Fatalf("recovered %v, want the transform's panic", p) + } + }() + run.SettleDone(ctx, id, "payload") + }() + if got := inst.Current(); got != "loading" || len(entity.notes) != 0 { + t.Fatalf("after the panic the instance is in %q with notes %q, want loading and none", got, entity.notes) + } + if !run.HasPending(id) { + t.Fatalf("the service isn't in flight after the panic, want it kept") + } +} + // TestWithResultTransform_UnboundServiceStillRoutesOnError proves a transform can't // turn an unbound service into a success: a transform that returns a result and no // error for the UnboundRefError still settles the service through onError, with the @@ -59,8 +224,8 @@ func TestWithResultTransform_UnboundServiceStillRoutesOnError(t *testing.T) { entity := &trec{} inst := m.Cast(entity, state.WithInitialState("idle")) // A nil registry leaves "fetch" unbound. - run = state.NewServiceRunner(inst, nil).WithResultTransform(func(any, error) (any, error) { - return "fallback", nil + run = state.NewServiceRunner(inst, nil).WithResultTransform(func(string, any, error) (any, error, error) { + return "fallback", nil, nil }) run.Absorb(ctx, inst.Fire(ctx, "start").Effects) res := run.Tick(ctx, state.InvokeID("loader", "loading", 0)) diff --git a/state/runner.go b/state/runner.go index 504c078f..e211db1c 100644 --- a/state/runner.go +++ b/state/runner.go @@ -2,6 +2,7 @@ package state import ( "context" + "errors" "sort" "sync" "sync/atomic" @@ -69,6 +70,10 @@ type running[E comparable] struct { onDone E onError E state string + // gen identifies this activation: a service stopped and armed again under the same + // invoke id gets a new one, so a settle that captured the old activation can't + // settle the new one. + gen uint64 } // ServiceRunner is the reusable host-driver that turns the kernel's StartService / @@ -89,6 +94,7 @@ type ServiceRunner[S comparable, E comparable, C any] struct { mu sync.Mutex running map[string]running[E] + gen uint64 // the latest activation's gen, under mu // lastResult holds the most recently settled service outcome so the host // action bound to the onDone / onError transition can read the result or error @@ -98,8 +104,9 @@ type ServiceRunner[S comparable, E comparable, C any] struct { // snapshot. lastResult atomic.Value // serviceOutcome - // transform, when set, rewrites a ServiceFn's outcome before Tick settles it. - transform func(any, error) (any, error) + // transform, when set, rewrites every outcome before it settles, given the event + // that will carry it, or aborts the settle. + transform func(event E, result any, err error) (out any, outErr error, abort error) } // serviceOutcome is the result/error pair a settled service exposes through @@ -140,12 +147,14 @@ func (r *ServiceRunner[S, E, C]) Absorb(ctx context.Context, effects []Effect) { if !ok { continue } + r.gen++ r.running[e.ID] = running[E]{ src: e.Src, input: e.Input, onDone: done, onError: erev, state: e.State, + gen: r.gen, } case StopService: delete(r.running, e.ID) @@ -174,7 +183,10 @@ func (r *ServiceRunner[S, E, C]) HasPending(id string) bool { // and fires its OnDone event (carrying result) through the instance, then absorbs // the resulting effects so a chained invoke arms its successor. It returns the // FireResult and true, or the zero result and false when id names no in-flight -// service (already stopped or settled). result is delivered to the onDone +// service (already stopped or settled). When a WithResultTransform function aborts +// the settle, it returns false and a FireResult whose Err is the abort error, fires +// nothing, and leaves the service in flight, unless the service was stopped while the +// transform ran: then the abort returns the zero result and false. result is delivered to the onDone // transition's effects through the instance entity by the host's actions — the // kernel routes the event; the action reads the result. func (r *ServiceRunner[S, E, C]) SettleDone(ctx context.Context, id string, result any) (FireResult[S], bool) { @@ -184,23 +196,49 @@ func (r *ServiceRunner[S, E, C]) SettleDone(ctx context.Context, id string, resu // SettleError fails the in-flight service id: it drops the service and fires its // OnError event (carrying err) through the instance, then absorbs the resulting // effects. It returns the FireResult and true, or the zero result and false when -// id names no in-flight service. +// id names no in-flight service. When a WithResultTransform function aborts the +// settle, it returns false and a FireResult whose Err is the abort error, fires +// nothing, and leaves the service in flight, unless the service was stopped while the +// transform ran: then the abort returns the zero result and false. func (r *ServiceRunner[S, E, C]) SettleError(ctx context.Context, id string, err error) (FireResult[S], bool) { return r.settle(ctx, id, nil, err) } -// settle is the shared body of SettleDone / SettleError: drop the running service -// under lock, then fire its routing event and absorb the follow-on effects. +// settle is the shared body of SettleDone / SettleError: it settles the activation +// of id in flight now. func (r *ServiceRunner[S, E, C]) settle(ctx context.Context, id string, result any, err error) (FireResult[S], bool) { r.mu.Lock() rs, ok := r.running[id] - if ok { - delete(r.running, id) - } r.mu.Unlock() if !ok { return FireResult[S]{}, false } + return r.settleActivation(ctx, id, rs, result, err) +} + +// settleActivation settles rs, one activation of id: run the transform on the +// outcome, drop the activation under lock, then fire its routing event and absorb the +// follow-on effects. The transform runs outside the lock before the activation is +// dropped, so one that aborts, or panics, leaves the service in flight. It returns +// false and fires nothing when rs is no longer in flight, settled or stopped meanwhile, +// even if the service was armed again under the same id: that new activation stays in +// flight. That holds for an abort too: a stale abort returns no Err, as for an id not +// in flight, since it leaves nothing in flight. +func (r *ServiceRunner[S, E, C]) settleActivation(ctx context.Context, id string, rs running[E], result any, err error) (FireResult[S], bool) { + if r.transform != nil { + var abort error + if result, err, abort = r.applyTransform(rs, result, err); abort != nil { + if !r.current(id, rs, false) { + return FireResult[S]{}, false + } + return FireResult[S]{Err: abort}, false + } + } + ok := r.current(id, rs, true) + if !ok { + // Settled or stopped while the transform ran, and perhaps armed again. + return FireResult[S]{}, false + } r.lastResult.Store(serviceOutcome{result: result, err: err}) var ev E var payload any @@ -220,18 +258,66 @@ func (r *ServiceRunner[S, E, C]) settle(ctx context.Context, id string, result a return res, true } -// WithResultTransform sets a function that rewrites a ServiceFn's outcome before Tick -// settles it, and returns the runner. A host that records outcomes uses it to give the -// live run the form a replay will see. LastResult and LastError then report the rewritten -// outcome. It also runs on an UnboundRefError, where only a non-nil returned error is -// used: a nil one leaves the UnboundRefError, so the service still settles through onError. It -// doesn't apply to SettleDone or SettleError, which take the outcome as given. Set it -// before the first Tick: the field isn't guarded. -func (r *ServiceRunner[S, E, C]) WithResultTransform(f func(result any, err error) (any, error)) *ServiceRunner[S, E, C] { +// WithResultTransform sets a function that rewrites every outcome before it settles, +// whether Tick, SettleDone or SettleError settles it, and returns the runner. f gets +// the event that will carry the outcome: the invocation's onDone for a result, its +// onError for an error. A host that records outcomes uses it to give the live run and +// a replay the same value, decoded for that event. +// +// f returns the outcome to settle with, out and outErr. A non-nil outErr settles +// through onError, and a nil one through onDone with out, except for an +// UnboundRefError: a nil outErr leaves the UnboundRefError, so an unbound service +// still settles through onError. LastResult and LastError report the rewritten +// outcome. +// +// A non-nil abort stops the settle instead: no event fires, so no Assign, middleware +// or inspector runs, and the service stays in flight, so it can be settled again. +// SettleDone and SettleError return false with abort, as given, in FireResult.Err; +// Tick returns a one-element slice holding that FireResult. LastResult and LastError +// still report the previous settle. +// +// f runs outside the runner's lock before the service is dropped, so it may run for a +// settle that then finds the service stopped or settled by another goroutine, and +// returns false. That holds even if the service was armed again under the same invoke +// id meanwhile: the new activation stays in flight. Such a settle reports no abort: +// SettleDone and SettleError return the zero result, and Tick an empty slice. A panic in f goes on out of the settle, leaving the service in +// flight. Set f before the first settle: the field isn't guarded. +func (r *ServiceRunner[S, E, C]) WithResultTransform(f func(event E, result any, err error) (out any, outErr error, abort error)) *ServiceRunner[S, E, C] { r.transform = f return r } +// current reports whether rs is still the activation of id in flight, and with drop +// removes it when it is. +func (r *ServiceRunner[S, E, C]) current(id string, rs running[E], drop bool) bool { + r.mu.Lock() + defer r.mu.Unlock() + cur, ok := r.running[id] + ok = ok && cur.gen == rs.gen + if ok && drop { + delete(r.running, id) + } + return ok +} + +// applyTransform runs the transform on an outcome of rs. An UnboundRefError stays an +// error: a transform that returns no error for it can't turn it into a success. +func (r *ServiceRunner[S, E, C]) applyTransform(rs running[E], result any, err error) (any, error, error) { + ev := rs.onDone + if err != nil { + ev = rs.onError + } + out, terr, abort := r.transform(ev, result, err) + if abort != nil { + return nil, nil, abort + } + var unbound *UnboundRefError + if terr == nil && errors.As(err, &unbound) { + return nil, err, nil + } + return out, terr, nil +} + // Tick resolves and runs the in-flight service id against the bound registry, // settling it with the ServiceFn's result or error. It is the ServiceRunner's // advance verb — the host-driver counterpart of Scheduler.Tick and @@ -242,7 +328,14 @@ func (r *ServiceRunner[S, E, C]) WithResultTransform(f func(result any, err erro // Scheduler.Tick and ActorSystem.Tick, or an empty slice when id is not in flight. // A missing registry / unresolved ServiceFn still settles the service as an error // (so the machine routes onError rather than hanging) and that routed result is -// returned in the slice. +// returned in the slice. When a WithResultTransform function aborts the settle, the +// slice holds one FireResult whose Err is the abort error, no event fires, and the +// service stays in flight. A service stopped while its ServiceFn or the transform ran +// settles nothing and reports no abort, even if it was armed again under the same id: +// Tick returns an empty slice, as for an id not in flight, and the new activation +// stays in flight. So a non-empty slice always means the settle fired its event, or +// was aborted with the service still in flight, whatever FireResult the Fire +// returned. func (r *ServiceRunner[S, E, C]) Tick(ctx context.Context, id string) []FireResult[S] { r.mu.Lock() rs, ok := r.running[id] @@ -250,28 +343,25 @@ func (r *ServiceRunner[S, E, C]) Tick(ctx context.Context, id string) []FireResu if !ok { return nil } + // Settle the activation the ServiceFn runs for, not one armed under id meanwhile. fn := r.resolve(rs.src.Name) if fn == nil { - var err error = &UnboundRefError{Kind: "service", Name: rs.src.Name} - if r.transform != nil { - // An unbound service always settles as an error: a transform that returns - // no error can't turn it into a success. - if _, terr := r.transform(nil, err); terr != nil { - err = terr - } - } - res, _ := r.SettleError(ctx, id, err) - return []FireResult[S]{res} + return tickResult(r.settleActivation(ctx, id, rs, nil, &UnboundRefError{Kind: "service", Name: rs.src.Name})) } out, err := fn(ctx, ServiceCtx[C]{Entity: r.inst.entity, Params: rs.src.Params, Input: rs.input}) - if r.transform != nil { - out, err = r.transform(out, err) - } if err != nil { - res, _ := r.SettleError(ctx, id, err) - return []FireResult[S]{res} + out = nil + } + return tickResult(r.settleActivation(ctx, id, rs, out, err)) +} + +// tickResult is Tick's return for a settle: the settle's FireResult when it fired or +// was aborted, which leaves the abort in Err, and nothing when it found its +// activation gone. +func tickResult[S comparable](res FireResult[S], settled bool) []FireResult[S] { + if !settled && res.Err == nil { + return nil } - res, _ := r.SettleDone(ctx, id, out) return []FireResult[S]{res} } diff --git a/state/settle_stale_test.go b/state/settle_stale_test.go new file mode 100644 index 00000000..09500152 --- /dev/null +++ b/state/settle_stale_test.go @@ -0,0 +1,194 @@ +package state_test + +import ( + "context" + "errors" + "testing" + + "github.com/stablekernel/crucible/state" +) + +// rearm stops the in-flight "loading" service by leaving the state, then enters it +// again, which arms a new activation under the same InvokeID. +func rearm(ctx context.Context, t *testing.T, inst *state.Instance[string, string, *trec], run *state.ServiceRunner[string, string, *trec], id string) { + t.Helper() + run.Absorb(ctx, inst.Fire(ctx, "cancel").Effects) + if run.HasPending(id) { + t.Fatalf("leaving loading left %q in flight", id) + } + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + if !run.HasPending(id) || inst.Current() != "loading" { + t.Fatalf("re-entering loading didn't arm %q again", id) + } +} + +// TestSettle_StaleTransformDoesNotSettleARearmedActivation proves a settle whose +// transform ran for one activation of a service can't settle a later one. The +// transform blocks while the test stops the service and re-arms it under the same +// InvokeID; once released, the old settle must return false, fire nothing, and leave +// the new activation in flight. +func TestSettle_StaleTransformDoesNotSettleARearmedActivation(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("loader", "loading", 0) + var run *state.ServiceRunner[string, string, *trec] + m := invokeMachine(&run) + entity := &trec{} + inst := m.Cast(entity, state.WithInitialState("idle")) + entered, release := make(chan struct{}), make(chan struct{}) + block := true + run = state.NewServiceRunner(inst, nil).WithResultTransform(func(_ string, result any, err error) (any, error, error) { + if block { + close(entered) + <-release + } + return result, err, nil + }) + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + + type settled struct { + res state.FireResult[string] + ok bool + } + done := make(chan settled) + go func() { + res, ok := run.SettleDone(ctx, id, "old") + done <- settled{res, ok} + }() + <-entered + rearm(ctx, t, inst, run, id) + block = false + close(release) + got := <-done + + if got.ok || got.res.NewState != "" { + t.Fatalf("the stale settle returned %+v, %v; want false and nothing fired", got.res, got.ok) + } + if inst.Current() != "loading" || len(entity.notes) != 0 { + t.Fatalf("the stale settle moved the instance to %q with notes %q, want loading and none", inst.Current(), entity.notes) + } + if !run.HasPending(id) { + t.Fatalf("the stale settle dropped the re-armed activation, want it in flight") + } + // The new activation still settles with its own outcome. + if res, ok := run.SettleDone(ctx, id, "new"); !ok || res.NewState != "ready" || join(entity.notes) != "result:new" { + t.Fatalf("settling the new activation gave %+v, %v, notes %q; want ready with result:new", res, ok, entity.notes) + } +} + +// TestTick_StaleServiceRunDoesNotSettleARearmedActivation proves the same for the +// ServiceFn's own run: a Tick whose ServiceFn ran for one activation can't settle a +// later one armed under the same InvokeID while it ran. It returns nil, as for an id +// not in flight, so a caller can't mistake it for a settle whose Fire returned a zero +// FireResult. +func TestTick_StaleServiceRunDoesNotSettleARearmedActivation(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("loader", "loading", 0) + var run *state.ServiceRunner[string, string, *trec] + m := invokeMachine(&run) + entity := &trec{} + inst := m.Cast(entity, state.WithInitialState("idle")) + entered, release := make(chan struct{}), make(chan struct{}) + block := true + reg := state.NewRegistry[*trec]().Service("fetch", func(context.Context, state.ServiceCtx[*trec]) (any, error) { + if block { + close(entered) + <-release + } + return "payload", nil + }) + run = state.NewServiceRunner(inst, reg) + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + + done := make(chan []state.FireResult[string]) + go func() { done <- run.Tick(ctx, id) }() + <-entered + rearm(ctx, t, inst, run, id) + block = false + close(release) + got := <-done + + if got != nil { + t.Fatalf("the stale Tick returned %+v, want nil: it settled nothing", got) + } + if inst.Current() != "loading" || len(entity.notes) != 0 { + t.Fatalf("the stale Tick moved the instance to %q with notes %q, want loading and none", inst.Current(), entity.notes) + } + if !run.HasPending(id) { + t.Fatalf("the stale Tick dropped the re-armed activation, want it in flight") + } +} + +// TestSettle_StaleAbortSettlesNothing proves an aborted settle of an activation stopped, +// and armed again, while its transform ran reports nothing: the activation it ran for +// is gone, so the abort has nothing to leave in flight. SettleDone and SettleError +// return false with no Err, and Tick an empty slice, as for an id not in flight. The +// re-armed activation stays in flight and settles with its own outcome. +func TestSettle_StaleAbortSettlesNothing(t *testing.T) { + abortErr := errors.New("transform aborted") + for _, verb := range []string{"SettleDone", "SettleError", "Tick"} { + t.Run(verb, func(t *testing.T) { + ctx := context.Background() + id := state.InvokeID("loader", "loading", 0) + var run *state.ServiceRunner[string, string, *trec] + m := invokeMachine(&run) + entity := &trec{} + inst := m.Cast(entity, state.WithInitialState("idle")) + entered, release := make(chan struct{}), make(chan struct{}) + block := true + reg := state.NewRegistry[*trec]().Service("fetch", func(context.Context, state.ServiceCtx[*trec]) (any, error) { + return "payload", nil + }) + run = state.NewServiceRunner(inst, reg).WithResultTransform(func(_ string, result any, err error) (any, error, error) { + if block { + close(entered) + <-release + return nil, nil, abortErr + } + return result, err, nil + }) + run.Absorb(ctx, inst.Fire(ctx, "start").Effects) + + type settled struct { + res []state.FireResult[string] + ok bool + } + done := make(chan settled) + go func() { + var res state.FireResult[string] + var ok bool + switch verb { + case "SettleDone": + res, ok = run.SettleDone(ctx, id, "old") + case "SettleError": + res, ok = run.SettleError(ctx, id, errors.New("old")) + default: + done <- settled{res: run.Tick(ctx, id)} + return + } + done <- settled{[]state.FireResult[string]{res}, ok} + }() + <-entered + rearm(ctx, t, inst, run, id) + block = false + close(release) + got := <-done + + if verb == "Tick" { + if len(got.res) != 0 { + t.Fatalf("the stale aborted Tick returned %+v, want an empty slice: it settled nothing", got.res) + } + } else if got.ok || got.res[0].Err != nil || got.res[0].NewState != "" { + t.Fatalf("the stale aborted %s returned %+v, %v; want false with no Err: it settled nothing", verb, got.res[0], got.ok) + } + if inst.Current() != "loading" || len(entity.notes) != 0 { + t.Fatalf("the stale settle moved the instance to %q with notes %q, want loading and none", inst.Current(), entity.notes) + } + if !run.HasPending(id) { + t.Fatalf("the stale settle dropped the re-armed activation, want it in flight") + } + if res, ok := run.SettleDone(ctx, id, "new"); !ok || res.NewState != "ready" || join(entity.notes) != "result:new" { + t.Fatalf("settling the new activation gave %+v, %v, notes %q; want ready with result:new", res, ok, entity.notes) + } + }) + } +} From 889d9481667ba14831ed9ef4eae4259455cb3bd8 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Thu, 19 Nov 2026 08:59:24 -0700 Subject: [PATCH 2/4] refactor(durable): scope service-result decoding to typed results Cuts the parts of #258 beyond #264's scope, under the greenfield rule: durable has never been released, so a journal format bump and old-journal compatibility gates have nothing to protect. Cut: - Journal format 4: journalFormat is back to main's timersFirstFormat (3), and decodedResultsFormat is gone. Replay always decodes a recorded service result through the Runner's EventDataDecoder for the onDone event, exactly as the live settle did, and is held to the recorded Go type; the decoded parameter and the legacyResult replay of format 0-3 results as generic JSON are gone with it. Deleted journal_format_service_test.go, which only pinned that legacy replay, and the format-4 parts of journal_format_internal_test.go (its checkFormats and checkNotNewer tables and the older-reader parked-entry test); what's left pins main's checkFormat only. - The newer-journal refusal: checkNotNewer, newerFormatOf and the unmarshalCheckpoint probe for a newer format's envelope are gone; 6d3453d was already out. - The mixed-version extension of the format check: checkFormats (the running max, the upfront move, its extension to StateAt and Steps) is gone; checkFormat is exactly main's, called per Record in Recover's and replayThrough's loops, as on main. Deleted journal_format_midtail and journal_format_mixed, and the format-extension tests of journal_format_stateat; its sentinel test, which pins kept parking behavior, moved to result_decoding_scenarios_test.go, and forkMachine, whose format tests are gone, to service_activation_test.go, its only remaining user. Main's format machinery from #236/#237 is unchanged: checkFormat, the format constants, unmarshalCheckpoint, store.go's Record.Format docs and StateAt/Steps all diff empty against origin/main. Kept: typed decode live and on replay, parking, the abort return, activation generations, and the Type record with its replay check. Wording fixes: - state: WithResultTransform's doc says f gets the invocation's onDone event for an incoming result and its onError event for an incoming error, and reconciles that with the outErr that settles through onError; the state CHANGELOG entry matches. - durable: decodedAsRecorded's type-mismatch error states got versus want plainly, like its sibling branches, without "of the same name or not" and without printing the same type twice. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 44 +--- durable/checkpoint.go | 32 +-- durable/journal_format_internal_test.go | 72 +------ durable/journal_format_midtail_test.go | 118 ----------- durable/journal_format_mixed_test.go | 104 ---------- durable/journal_format_newer_test.go | 235 ---------------------- durable/journal_format_service_test.go | 96 --------- durable/journal_format_stateat_test.go | 96 --------- durable/result_decoding_scenarios_test.go | 20 ++ durable/runner.go | 87 ++------ durable/service.go | 57 ++---- durable/service_activation_test.go | 19 ++ durable/store.go | 7 +- durable/timetravel.go | 42 +--- state/CHANGELOG.md | 4 +- state/runner.go | 7 +- 16 files changed, 104 insertions(+), 936 deletions(-) delete mode 100644 durable/journal_format_midtail_test.go delete mode 100644 durable/journal_format_mixed_test.go delete mode 100644 durable/journal_format_newer_test.go delete mode 100644 durable/journal_format_service_test.go delete mode 100644 durable/journal_format_stateat_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index be9ed1b9..b59da216 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -17,12 +17,10 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. onError was refused because a context ended, so `Recover` can tell them from the actors that were running. A Store must keep an empty set distinct from nil. - **`Record.Format`** records the journal format of the version that wrote the Record, - which is 4 from this version. Replay arms the timers and services an actor-driven + which is 3 from this version. Replay arms the timers and services an actor-driven parent Fire's state declares only for a Record of format 1 or later. `Recover` sends a tick's and a service settle's effects, and replay hands a tick's timer transitions' - effects to the service runner, only for a Record of format 2 or later. Replay decodes - a service result through `WithEventDataDecoder` only for a Record of format 4 or - later. + effects to the service runner, only for a Record of format 2 or later. **For Store authors:** a Store must keep `Format`, `EndedActors` and `UnstartedActors`, and keep an empty set distinct from nil. A Store that drops them, or maps an empty set to nil as an SQL array column or a protobuf repeated field can, @@ -92,31 +90,6 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. older `durable`'s `Recover` re-arms a baseline's or checkpoint's timers only after the tail, so it misses one a tail tick fired, with no error, and its `StateAt` ignores a baseline's timers. Don't downgrade a Store this version has written to. -- **Don't run mixed versions on one instance.** During a rolling deploy, let only - replicas of one version own a given instance: drain an instance's owner before a - replica of another version recovers it (#253). An older replica that appends to a - journal this version wrote stamps a lower journal format after this version's - checkpoint or Records. This version's `Recover` and stateless `Fire` then fail with an - error saying an older version appended to a newer journal, before replaying any of it, - so a refused journal sends no effect. `StateAt` and `Steps` fail with it too, on - whatever step `StateAt` targets, even one before the lower-format Record, so they - refuse the journals `Recover` refuses. This version - can't replay such a Record by the older format's rules, because the older version - reads the journal differently, settling a parked result through onDone, for one. A - version older than this one checks no journal format, so it reads the mixed journal - without refusing it, and that can't be fixed for binaries already built. When this version is the older one, it - refuses a later version's journal, with an error saying a newer version wrote it, - whenever the checkpoint or any Record it loads records a format above its own, and - doesn't then look for a lower-format Record among them. Each version checks only - what it loads, so none of this makes mixed versions safe. -- **A journal a newer version wrote is refused.** `Recover`, a stateless - `Runner.Fire`, `StateAt` and `Steps` fail, before they restore or replay anything, - on a journal whose checkpoint or any Record records a journal format above this - version's, with an error naming both formats, also when the checkpoint's envelope has - a shape this version can't unmarshal, such as a field whose type changed, rather than - restore it as a bare snapshot and fail later. A version from this one onward refuses - a newer journal, so a rollback across a later format bump fails cleanly instead of - replaying the journal as its own. Versions already built don't refuse one. - **A journal an older version wrote replays as it did.** Its actor entries carry no refusal, so `Recover` still fails on one whose parent Fire was refused, and an output recorded with a delivery's last Fire still replays into that transition. Only steps @@ -190,10 +163,7 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. panicked, its invalid UTF-8 replaced too. The journal records the JSON the live settle decoded, so replay decodes the same bytes, even for a decoder whose type doesn't survive a round trip through its own encoding. A result with no JSON form fails the - Handle, as before, but now before any `Assign` runs. A service result in a Record an - older version wrote, of format 3 or lower, replays as that version replayed it: in JSON's - generic form, through no decoder, so a decoder added for its onDone event can't fail - `Recover` on it. + Handle, as before, but now before any `Assign` runs. - **A service result that won't decode is parked.** `RunService` returns `ErrEventDataEncoding`, not `ErrHandleFailed`, before any onDone or onError `Assign` runs. The decode aborts the settle through `ServiceRunner.WithResultTransform`'s abort @@ -305,11 +275,9 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. registry. `Recover` without a registry still refuses a journal tail that holds a service's settle or park. - **`Recover` and `StateAt` fail when a Store loses `Record.Format`.** The Start baseline - and every checkpoint record the journal format too, and a Record with a lower format - than the checkpoint or any Record before it fails replay, before any Record replays, where it used to replay as an older journal's and silently skip - the timers and services an actor-driven Fire armed. The error says the Store didn't - keep `Record.Format` for a Record with no format, and that an older version appended - it, a mixed-version deploy, for one with a lower format. + and every checkpoint record the journal format too, and a Record after one with a lower + format fails replay, where it used to replay as an older journal's and silently skip + the timers and services an actor-driven Fire armed. - **A step that touches no actor doesn't recompute the actor sets.** Each append rebuilt the declared actors from every active state; it now reuses the last sets while the configuration, the running actors and the step's spawns are unchanged. diff --git a/durable/checkpoint.go b/durable/checkpoint.go index 26ef9399..12cce5dd 100644 --- a/durable/checkpoint.go +++ b/durable/checkpoint.go @@ -3,7 +3,6 @@ package durable import ( "encoding/json" "fmt" - "math" "sort" "time" @@ -116,9 +115,7 @@ type checkpointEnvelope struct { ParkedServices []parkedServiceWire `json:"parkedServices,omitempty"` // Format is the journal format of the version that wrote the checkpoint, as // Record.Format is. Zero means a checkpoint from before this field. A Record after - // it with a lower Format means the Store lost the field, and replay fails. A Format - // above this version's journalFormat means a newer version wrote it, and every reader - // refuses the journal. + // it with a lower Format means the Store lost the field, and replay fails. Format int `json:"format,omitempty"` } @@ -159,38 +156,17 @@ func marshalCheckpoint(env checkpointEnvelope, timers map[string]pendingTimer) ( // tolerates a bare (pre-envelope) snapshot: bytes that are not a checkpoint envelope // are returned as the snapshot with no timers and a zero ordinal, so an older // checkpoint still restores. A checkpoint envelope is distinguished by carrying a -// non-empty "snapshot" member. Bytes this version's envelope can't unmarshal but whose -// "format" member is a number above journalFormat are a newer version's envelope, one -// that may have changed a field's type: they keep that Format, so checkNotNewer -// refuses them rather than restore them as a bare snapshot. A bare kernel snapshot has -// no "format" member. +// non-empty "snapshot" member. func unmarshalCheckpoint(b []byte) checkpointEnvelope { var env checkpointEnvelope if err := json.Unmarshal(b, &env); err != nil || len(env.Snapshot) == 0 { // Not an envelope (or an envelope without the wrapped snapshot member): treat - // the bytes as a bare kernel snapshot, the pre-timer-survival checkpoint form, - // unless they record a newer format. - return checkpointEnvelope{Snapshot: b, Format: newerFormatOf(b)} + // the bytes as a bare kernel snapshot, the pre-timer-survival checkpoint form. + return checkpointEnvelope{Snapshot: b} } return env } -// newerFormatOf returns the "format" member of b, a JSON object, when it is an integer -// above journalFormat, capped to fit an int on any platform, and zero otherwise. -func newerFormatOf(b []byte) int { - var probe struct { - Format json.Number `json:"format"` - } - if json.Unmarshal(b, &probe) != nil { - return 0 - } - f, err := probe.Format.Int64() - if err != nil || f <= journalFormat { - return 0 - } - return int(min(f, math.MaxInt32)) -} - // decodeTimerEvent decodes a persisted timer event wire back into the machine's // event type E through the same codec the Runner replays driving events with, so // the re-armed ScheduleAfter carries a correctly-typed event the scheduler accepts. diff --git a/durable/journal_format_internal_test.go b/durable/journal_format_internal_test.go index f94f2069..8fc42177 100644 --- a/durable/journal_format_internal_test.go +++ b/durable/journal_format_internal_test.go @@ -1,79 +1,17 @@ package durable import ( - "encoding/json" "testing" ) -// TestCheckFormat_RefusesAHigherFormat pins what a downgrade meets. checkFormat fails -// on a Record of a lower format than its checkpoint's, a Store that lost the field, and -// accepts a higher one, as every version since Record.Format has. checkFormats holds -// each Record to the highest format before it, the checkpoint's or a Record's, so an -// older version's Record is refused anywhere in the tail. checkNotNewer, which -// every reader calls first, refuses a checkpoint or a Record of a format above -// journalFormat, one a newer version wrote, so each later bump of journalFormat makes -// this version refuse that version's journal. A binary built before checkNotNewer -// replays a newer journal as its own format. -func TestCheckFormat_RefusesAHigherFormat(t *testing.T) { +// TestCheckFormat_HoldsRecordsToTheCheckpointFormat pins what a Store that drops +// Record.Format meets. checkFormat fails on a Record of a lower format than its +// checkpoint's, and accepts a higher one, as every version since Record.Format has. +func TestCheckFormat_HoldsRecordsToTheCheckpointFormat(t *testing.T) { if err := checkFormat(1, &Record{Format: 2}); err != nil { t.Errorf("checkFormat(1, a Record of format 2) = %v, want nil", err) } if err := checkFormat(2, &Record{Format: 1}); err == nil { - t.Errorf("checkFormat(2, a Record of format 1) = nil, want the older-version error") - } - for _, tc := range []struct { - checkpoint int - recs []Record - refused bool - }{ - {0, []Record{{Format: 0}, {Format: 1}, {Format: 1}, {Format: 2}}, false}, - {1, []Record{{Format: 1}, {Format: 2}, {Format: 2}}, false}, - {1, []Record{{Format: 2}, {Format: 1}}, true}, - {0, []Record{{Format: 1}, {Format: 0}}, true}, - {2, []Record{{Format: 1}}, true}, - } { - err := checkFormats(tc.checkpoint, tc.recs) - if (err != nil) != tc.refused { - t.Errorf("checkFormats(%d, %+v) = %v, want refused %v", tc.checkpoint, tc.recs, err, tc.refused) - } - } - for _, tc := range []struct { - checkpoint int - recs []Record - refused bool - }{ - {0, nil, false}, - {journalFormat, nil, false}, - {0, []Record{{Format: 0}, {Format: 1}, {Format: journalFormat}}, false}, - {journalFormat + 1, nil, true}, - {journalFormat, []Record{{Format: journalFormat}, {Format: journalFormat + 1}}, true}, - {0, []Record{{Format: journalFormat + 5}}, true}, - } { - err := checkNotNewer("x", tc.checkpoint, tc.recs) - if (err != nil) != tc.refused { - t.Errorf("checkNotNewer(%d, %+v) = %v, want refused %v", tc.checkpoint, tc.recs, err, tc.refused) - } - } -} - -// TestParkedEntry_AnOlderReaderSettlesIt pins what a version from before parking reads -// in a parked entry: its serviceResultPayload has only Result and Error, so the entry -// decodes as a result that settled, and its replay would settle the parked result -// through onDone, running the Assign the park held back. The CHANGELOG says not to -// downgrade a Store this version has written to; this is one reason. -func TestParkedEntry_AnOlderReaderSettlesIt(t *testing.T) { - payload, err := json.Marshal(serviceResultPayload{Result: json.RawMessage(`{"ID":7}`), Parked: true, Type: "x.T"}) - if err != nil { - t.Fatal(err) - } - var older struct { - Result json.RawMessage `json:"result,omitempty"` - Error *string `json:"error,omitempty"` - } - if err := json.Unmarshal(payload, &older); err != nil { - t.Fatalf("an older reader fails on a parked entry: %v", err) - } - if older.Error != nil || string(older.Result) != `{"ID":7}` { - t.Fatalf("an older reader reads %+v, want a settled result", older) + t.Errorf("checkFormat(2, a Record of format 1) = nil, want the Store-lost-field error") } } diff --git a/durable/journal_format_midtail_test.go b/durable/journal_format_midtail_test.go deleted file mode 100644 index eaaa3652..00000000 --- a/durable/journal_format_midtail_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package durable_test - -import ( - "context" - "strings" - "testing" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// These tests answer a review finding on the journal format check: it compared each -// Record's format only with the checkpoint's, so an older version's Record appended -// after this version's Records, past an older checkpoint, replayed by its own format's -// rules. A journal's format never goes down, so a Record below any format before it, -// the checkpoint's or an earlier Record's, means mixed versions wrote it, and Recover -// and StateAt refuse it before replaying anything. - -// TestRecover_OlderRecordMidTailIsRefused: a format-1 checkpoint, then this version's -// format-4 Record that parks a result, then an older replica's format-1 Fire. The older -// replica reads the park as a settle (see TestRecover_OlderVersionAfterAParkIsRefused), -// so the two versions disagree about the journal, and Recover must refuse it, naming -// the older version, as it does when the checkpoint itself is newer. -func TestRecover_OlderRecordMidTailIsRefused(t *testing.T) { - ctx := context.Background() - fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return scnUser{ID: 7, Name: "ann"}, nil } - m := forkMachine(fn) - reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) - st := durable.NewMemStore() - // An older version, of format 1, started the instance and wrote its checkpoint. - older := &olderWriter{MemStore: st, format: 1} - if _, err := durable.NewRunner(m, older, reg, failingDecoder()).Start(ctx, "o1", svcCtx{}, state.WithInitialState("loading")); err != nil { - t.Fatalf("Start: %v", err) - } - // This version recovers it and parks the result, in a format-4 Record. - h, err := durable.Recover(ctx, m, st, "o1", reg, failingDecoder()) - if err != nil { - t.Fatalf("Recover the older checkpoint: %v", err) - } - _, ran, err := h.RunService(ctx, state.InvokeID("fork", "loading", 0)) - mustPark(t, "RunService", ran, err) - _, recs, err := st.Load(ctx, "o1") - if err != nil || len(recs) != 1 || recs[0].Format != 4 { - t.Fatalf("the journal holds %+v (err %v), want the park's one format-4 Record", recs, err) - } - // The older replica fires "next" after it, in its format. - if _, err = st.Append(ctx, "o1", durable.Record{Step: recs[0].Step + 1, Event: []byte(`"next"`), Format: 1}); err != nil { - t.Fatalf("Append: %v", err) - } - - rh, err := durable.Recover(ctx, m, st, "o1", reg, failingDecoder()) - if err == nil { - t.Fatalf("Recover replayed a format-1 Record after a format-4 one, into %q", rh.Instance().Current()) - } - if msg := err.Error(); !strings.Contains(msg, "older version") || !strings.Contains(msg, "don't run mixed versions") { - t.Fatalf("Recover: %v, want the mixed-version error", err) - } - if _, err = durable.StateAt(ctx, m, st, "o1", recs[0].Step+1, reg, failingDecoder()); err == nil || !strings.Contains(err.Error(), "older version") { - t.Fatalf("StateAt: %v, want the mixed-version error", err) - } -} - -// TestRecover_RefusesAMixedJournalBeforeReplaying: Recover checks every Record's format -// before it replays any, so a journal it refuses sends no effect. This version's Fire -// records an effect no handler sent, and an older replica appends after it; the effect -// would be sent if Recover only refused on reaching the older Record. -func TestRecover_RefusesAMixedJournalBeforeReplaying(t *testing.T) { - ctx := context.Background() - st := durable.NewMemStore() - h, err := durable.NewRunner(effectMachine(), st).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")) - if err != nil { - t.Fatalf("Start: %v", err) - } - // No handler: step 0's effect is recorded and not sent. - if _, err = h.Fire(ctx, "go"); err != nil { - t.Fatalf("Fire go: %v", err) - } - if _, err = durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: 1}).Fire(ctx, "i1", "bill"); err != nil { - t.Fatalf("the older replica's Fire: %v", err) - } - rec := newEffectRecorder() - _, err = durable.Recover(ctx, effectMachine(), st, "i1", durable.WithEffectHandler[string, string, *runCtx](rec.handler())) - if err == nil || !strings.Contains(err.Error(), "older version") { - t.Fatalf("Recover: %v, want the mixed-version error", err) - } - if n := rec.totalApplies(); n != 0 { - t.Fatalf("Recover sent %v before refusing the journal, want nothing sent", rec.ids()) - } -} - -// TestRecover_NonDecreasingFormatsLoad: a journal whose formats never go down loads, -// whatever they are: an older version's checkpoint and Records, then this version's. -func TestRecover_NonDecreasingFormatsLoad(t *testing.T) { - ctx := context.Background() - for _, formats := range [][]int{{0, 0, 2}, {0, 1, 2}, {1, 1, 1}, {1, 2, 2}, {0, 2, 2}} { - st := durable.NewMemStore() - r := durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: formats[0]}) - if _, err := r.Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { - t.Fatalf("%v: Start: %v", formats, err) - } - if _, err := durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: formats[1]}).Fire(ctx, "i1", "go"); err != nil { - t.Fatalf("%v: Fire go: %v", formats, err) - } - if _, err := durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: formats[2]}).Fire(ctx, "i1", "bill"); err != nil { - t.Fatalf("%v: Fire bill: %v", formats, err) - } - rh, err := durable.Recover(ctx, effectMachine(), st, "i1") - if err != nil { - t.Fatalf("%v: Recover: %v", formats, err) - } - if got := rh.Instance().Current(); got != "billed" { - t.Fatalf("%v: recovered in %q, want billed", formats, got) - } - if _, err = durable.StateAt(ctx, effectMachine(), st, "i1", 1); err != nil { - t.Fatalf("%v: StateAt: %v", formats, err) - } - } -} diff --git a/durable/journal_format_mixed_test.go b/durable/journal_format_mixed_test.go deleted file mode 100644 index 1abc32e9..00000000 --- a/durable/journal_format_mixed_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package durable_test - -import ( - "context" - "strings" - "testing" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// These tests answer a review finding on a rolling deploy that runs two versions on one -// instance: an older replica appends a Record of its own, lower journal format after -// this version's checkpoint. Recover must refuse the journal, and say that mixed -// versions wrote it rather than blame the Store. - -// TestRecover_OlderVersionAppendedAfterThisVersionsCheckpoint: this version's Start -// writes a baseline in its own format, and an older replica, which stamps format 1, appends the -// next step. Recover refuses, naming the older version, not a Store that lost -// Record.Format. -func TestRecover_OlderVersionAppendedAfterThisVersionsCheckpoint(t *testing.T) { - ctx := context.Background() - st := durable.NewMemStore() - if _, err := durable.NewRunner(effectMachine(), st).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { - t.Fatalf("Start: %v", err) - } - // The older replica: a Runner of this version, whose Store stamps format 1 on every - // Record it appends, as that version's Runner did. - if _, err := durable.NewRunner(effectMachine(), &olderWriter{MemStore: st, format: 1}).Fire(ctx, "i1", "go"); err != nil { - t.Fatalf("the older replica's Fire: %v", err) - } - _, err := durable.Recover(ctx, effectMachine(), st, "i1") - if err == nil { - t.Fatal("Recover replayed a format-1 Record after a checkpoint of this version's format") - } - if msg := err.Error(); !strings.Contains(msg, "older version") || strings.Contains(msg, "didn't keep Record.Format") { - t.Fatalf("Recover: %v, want it to say an older version appended to this version's journal, not blame the Store", err) - } -} - -// TestRecover_FormatlessRecordAfterThisVersionsCheckpoint keeps the diagnosis for a -// Record with no format at all, which a Store that drops the field gives, as does a -// version from before the field: Recover refuses and names both. -func TestRecover_FormatlessRecordAfterThisVersionsCheckpoint(t *testing.T) { - ctx := context.Background() - st := durable.NewMemStore() - if _, err := durable.NewRunner(effectMachine(), st).Start(ctx, "i1", &runCtx{}, state.WithInitialState("idle")); err != nil { - t.Fatalf("Start: %v", err) - } - if _, err := durable.NewRunner(effectMachine(), formatDroppingStore{st}).Fire(ctx, "i1", "go"); err != nil { - t.Fatalf("Fire: %v", err) - } - _, err := durable.Recover(ctx, effectMachine(), st, "i1") - if err == nil || !strings.Contains(err.Error(), "didn't keep Record.Format") { - t.Fatalf("Recover: %v, want it to say the Store may not have kept Record.Format", err) - } -} - -// forkMachine invokes fetch in loading. "next" is declared in loading and in ready, -// with different targets, so a journal replayed from the wrong state still replays, -// to the wrong place. -func forkMachine(fn state.ServiceFn[svcCtx]) *state.Machine[string, string, svcCtx] { - return state.ForgeFor[svcCtx]("fork"). - Service("fetch", fn). - State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). - State("ready"). - State("canceled").Final(). - State("shipped").Final(). - State("failed").Final(). - Initial("loading"). - Transition("loading").On("done").GoTo("ready"). - Transition("loading").On("fail").GoTo("failed"). - Transition("loading").On("next").GoTo("canceled"). - Transition("ready").On("next").GoTo("shipped"). - Quench() -} - -// TestRecover_OlderVersionAfterAParkIsRefused shows why Recover can't replay an older -// replica's Record by its own format's rules. This version parks a result; the older -// replica, which has no parking, reads the parked entry as a settle, so it moves to -// ready, and its "next" ships the order. Replayed here, the park leaves the instance in -// loading, where "next" cancels it: the two versions disagree about what the journal -// means, so Recover must refuse rather than recover canceled. -func TestRecover_OlderVersionAfterAParkIsRefused(t *testing.T) { - ctx := context.Background() - fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { return scnUser{ID: 7, Name: "ann"}, nil } - m := forkMachine(fn) - reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) - st := durable.NewMemStore() - h, err := durable.NewRunner(m, st, reg, failingDecoder()).Start(ctx, "o1", svcCtx{}, state.WithInitialState("loading")) - if err != nil { - t.Fatalf("Start: %v", err) - } - _, ran, err := h.RunService(ctx, state.InvokeID("fork", "loading", 0)) - mustPark(t, "RunService", ran, err) - // The older replica's step: the "next" it fired from ready, in its format. - if _, err = st.Append(ctx, "o1", durable.Record{Step: 1, Event: []byte(`"next"`), Format: 1}); err != nil { - t.Fatalf("Append: %v", err) - } - rh, err := durable.Recover(ctx, m, st, "o1", reg, failingDecoder()) - if err == nil { - t.Fatalf("Recover replayed the older replica's step into %q; the older replica left the order shipped", rh.Instance().Current()) - } -} diff --git a/durable/journal_format_newer_test.go b/durable/journal_format_newer_test.go deleted file mode 100644 index d5e5b354..00000000 --- a/durable/journal_format_newer_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package durable_test - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strconv" - "testing" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// newerFormat is a journal format above this version's, as a later version would write. -const newerFormat = 9 - -// newerWriter stamps every Record it keeps with older's format, and the checkpoint too -// when checkpoint is set, as the version that wrote that format would. -type newerWriter struct { - older *olderWriter - checkpoint bool - *durable.MemStore -} - -func (s *newerWriter) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { - return s.older.Append(ctx, id, rec, opts...) -} - -func (s *newerWriter) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { - if s.checkpoint { - return s.older.Checkpoint(ctx, id, snapshot, throughStep, opts...) - } - return s.MemStore.Checkpoint(ctx, id, snapshot, throughStep, opts...) -} - -func newWriter(format int, checkpoint bool) *newerWriter { - mem := durable.NewMemStore(durable.WithHistory()) - return &newerWriter{older: &olderWriter{MemStore: mem, format: format}, checkpoint: checkpoint, MemStore: mem} -} - -// journalCase is a journal some version wrote: a Start baseline, and, when step is set, -// one service settlement after it. -type journalCase struct { - name string - checkpoint bool // the baseline records format, not this version's - step bool // the journal holds a Record, of format -} - -// newerCases are the journals a newer version could leave: a newer Record after this -// version's baseline, a newer baseline with an empty tail, and both. -var newerCases = []journalCase{ - {"newer Record", false, true}, - {"newer checkpoint, empty tail", true, false}, - {"newer checkpoint and Record", true, true}, -} - -// writeJournal starts scn-1 on a store that writes format as c says, and settles its -// service once when c.step is set. -func writeJournal(t *testing.T, c journalCase, format int, a *scnAssigns) (*state.Machine[string, string, svcCtx], *newerWriter, durable.Option[string, string, svcCtx]) { - t.Helper() - fn := returning(scnUser{ID: 7, Name: "ann"}, nil) - m := scnMachine(fn, a) - store := newWriter(format, c.checkpoint) - reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) - h := scnStart(t, m, store, reg) - if c.step { - mustRunService(t, h, state.InvokeID(scnInvoke, "loading", 0)) - } - return m, store, reg -} - -// mustBeNewer fails unless err is the refusal of a journal of newerFormat, which names -// the instance and both formats and wraps none of the package's sentinels. -func mustBeNewer(t *testing.T, what string, err error) { - t.Helper() - want := fmt.Sprintf("durable: %q was written by a newer version (journal format %d; this version reads up to 4)", "scn-1", newerFormat) - if err == nil || err.Error() != want { - t.Fatalf("%s = %v, want %q", what, err, want) - } - for _, sentinel := range []error{ - durable.ErrInstanceNotFound, durable.ErrStepOutOfOrder, durable.ErrStepConflict, - durable.ErrFenced, durable.ErrCheckpointNotAdvancing, durable.ErrInstanceExists, - durable.ErrEffectDispatch, durable.ErrStepOutOfRange, durable.ErrEventDataEncoding, - durable.ErrRecordTooLarge, durable.ErrHandleFailed, durable.ErrReentrantStep, - durable.ErrNoDispatchStore, - } { - if errors.Is(err, sentinel) { - t.Fatalf("%s's refusal matches %v, want no sentinel", what, sentinel) - } - } -} - -// A version refuses a journal a newer version wrote, a checkpoint or a Record of a -// format above its own, rather than replay it as its own format. Recover refuses it -// before it restores or replays anything, so no Assign runs again. -func TestJournalFormat_NewerJournal_RecoverRefuses(t *testing.T) { - for _, c := range newerCases { - t.Run(c.name, func(t *testing.T) { - a := &scnAssigns{} - m, store, reg := writeJournal(t, c, newerFormat, a) - live := a.done - _, err := durable.Recover(context.Background(), m, store, "scn-1", reg) - mustBeNewer(t, "Recover", err) - if a.done != live { - t.Fatalf("onDone's Assign ran %d times, want only live's %d", a.done, live) - } - }) - } -} - -// The stateless Runner.Fire loads the instance as Recover does, so it refuses a newer -// journal too, and appends nothing to it. -func TestJournalFormat_NewerJournal_StatelessFireRefuses(t *testing.T) { - for _, c := range newerCases { - t.Run(c.name, func(t *testing.T) { - m, store, reg := writeJournal(t, c, newerFormat, &scnAssigns{}) - ctx := context.Background() - _, before, err := store.Load(ctx, "scn-1") - if err != nil { - t.Fatal(err) - } - _, err = durable.NewRunner(m, store, reg).Fire(ctx, "scn-1", "done") - mustBeNewer(t, "Runner.Fire", err) - _, after, err := store.Load(ctx, "scn-1") - if err != nil || len(after) != len(before) { - t.Fatalf("the journal holds %d Records (err %v) after the refused Fire, want %d", len(after), err, len(before)) - } - }) - } -} - -// StateAt refuses a newer journal whatever the step, even the baseline, which a newer -// Record after it doesn't reach. -func TestJournalFormat_NewerJournal_StateAtRefuses(t *testing.T) { - for _, c := range newerCases { - t.Run(c.name, func(t *testing.T) { - m, store, reg := writeJournal(t, c, newerFormat, &scnAssigns{}) - steps := []int{durable.BaselineStep} - if c.step { - steps = append(steps, 0) - } - for _, step := range steps { - _, err := durable.StateAt(context.Background(), m, store, "scn-1", step, reg) - mustBeNewer(t, fmt.Sprintf("StateAt(%d)", step), err) - } - }) - } -} - -// Steps refuses a newer journal, as StateAt does. -func TestJournalFormat_NewerJournal_StepsRefuses(t *testing.T) { - for _, c := range newerCases { - t.Run(c.name, func(t *testing.T) { - _, store, _ := writeJournal(t, c, newerFormat, &scnAssigns{}) - _, err := durable.Steps(context.Background(), store, "scn-1") - mustBeNewer(t, "Steps", err) - }) - } -} - -// The ceiling refuses only a newer format: a journal of format 0 (the 0.1.0 release), 1 -// or 2, this version's, still loads on every read path, with a checkpoint and an empty -// tail or a Record after it. -func TestJournalFormat_OlderAndCurrentJournal_Loads(t *testing.T) { - for _, format := range []int{0, 1, 2} { - for _, c := range []journalCase{ - {"checkpoint, empty tail", true, false}, - {"checkpoint and Record", true, true}, - } { - t.Run(fmt.Sprintf("format %d, %s", format, c.name), func(t *testing.T) { - ctx := context.Background() - m, store, reg := writeJournal(t, c, format, &scnAssigns{}) - if _, err := durable.Recover(ctx, m, store, "scn-1", reg); err != nil { - t.Fatalf("Recover: %v", err) - } - if _, err := durable.StateAt(ctx, m, store, "scn-1", durable.BaselineStep, reg); err != nil { - t.Fatalf("StateAt: %v", err) - } - if _, err := durable.Steps(ctx, store, "scn-1"); err != nil { - t.Fatalf("Steps: %v", err) - } - if !c.step { // the instance is still loading, so its onDone event fires - if _, err := durable.NewRunner(m, store, reg).Fire(ctx, "scn-1", "done"); err != nil { - t.Fatalf("Runner.Fire: %v", err) - } - } - }) - } - } -} - -// reshapedWriter writes every checkpoint as a later version might: format newerFormat, -// with nextStep changed from a number to a string, so this version's envelope type -// can't unmarshal it. -type reshapedWriter struct { - *durable.MemStore -} - -func (s *reshapedWriter) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { - var env map[string]json.RawMessage - if err := json.Unmarshal(snapshot, &env); err != nil { - return err - } - env["format"] = json.RawMessage(strconv.Itoa(newerFormat)) - env["nextStep"] = json.RawMessage(`"x"`) - b, err := json.Marshal(env) - if err != nil { - return err - } - return s.MemStore.Checkpoint(ctx, id, b, throughStep, opts...) -} - -// TestJournalFormat_NewerEnvelopeOfAnotherShape_IsRefused: a later version may change -// the type of an envelope field, so this version's envelope type can't unmarshal its -// checkpoint. Every reader must still read the checkpoint's format and refuse it as a -// newer version's, rather than take the bytes for a bare pre-envelope snapshot of -// format 0 and fail later with an obscure error. -func TestJournalFormat_NewerEnvelopeOfAnotherShape_IsRefused(t *testing.T) { - ctx := context.Background() - fn := returning(scnUser{ID: 7, Name: "ann"}, nil) - m := scnMachine(fn, &scnAssigns{}) - store := &reshapedWriter{MemStore: durable.NewMemStore(durable.WithHistory())} - reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) - scnStart(t, m, store, reg) - - _, err := durable.Recover(ctx, m, store, "scn-1", reg) - mustBeNewer(t, "Recover", err) - _, err = durable.NewRunner(m, store, reg).Fire(ctx, "scn-1", "done") - mustBeNewer(t, "Runner.Fire", err) - _, err = durable.StateAt(ctx, m, store, "scn-1", durable.BaselineStep, reg) - mustBeNewer(t, "StateAt", err) - _, err = durable.Steps(ctx, store, "scn-1") - mustBeNewer(t, "Steps", err) -} diff --git a/durable/journal_format_service_test.go b/durable/journal_format_service_test.go deleted file mode 100644 index 81313f6a..00000000 --- a/durable/journal_format_service_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package durable_test - -import ( - "context" - "encoding/json" - "testing" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// olderWriter is a MemStore that stamps every Record and checkpoint it keeps with -// format, as a version that wrote that journal format did. The scnUser result these -// tests record needs no rewrite: an older version journaled json.Marshal of the value -// the ServiceFn returned, and for a scnUser those are the bytes this version records. -type olderWriter struct { - *durable.MemStore - format int -} - -func (s *olderWriter) Append(ctx context.Context, id durable.InstanceID, rec durable.Record, opts ...durable.AppendOption) (int64, error) { - rec.Format = s.format - return s.MemStore.Append(ctx, id, rec, opts...) -} - -func (s *olderWriter) Checkpoint(ctx context.Context, id durable.InstanceID, snapshot []byte, throughStep int, opts ...durable.CheckpointOption) error { - var env map[string]json.RawMessage - if err := json.Unmarshal(snapshot, &env); err != nil { - return err - } - delete(env, "format") - if s.format > 0 { - env["format"] = json.RawMessage([]byte{byte('0' + s.format)}) - } - b, err := json.Marshal(env) - if err != nil { - return err - } - return s.MemStore.Checkpoint(ctx, id, b, throughStep, opts...) -} - -// TestJournalFormat_OlderServiceResult_ReplaysAsItDid: a service result an older -// version journaled, at format 0 (the 0.1.0 release), 1, 2 or 3 (each before results -// were decoded through WithEventDataDecoder), replays as that version replayed it: in -// JSON's generic form, through no decoder and no type check. Formats 2 and 3 are the -// ones the versions just before this one write, so this version can't take either for -// its own. A Runner whose decoder covers onDone, and fails, returns another type or -// returns the service's own type, still recovers it, and the replayed Assign sees the -// map the older version's replay gave it. Records this version writes, at format 4, -// decode through the decoder (see -// TestServiceResult_RecordedResultThatWontDecode_RunsNoAssignOnReplay). -func TestJournalFormat_OlderServiceResult_ReplaysAsItDid(t *testing.T) { - decoders := []struct { - name string - opt durable.Option[string, string, svcCtx] - }{ - {"decoder fails", failingDecoder()}, - {"decoder returns another type", decoderFor("done", durable.DecodeAs[scnAdmin])}, - {"decoder returns the service's type", decoderFor("done", durable.DecodeAs[scnUser])}, - } - for _, format := range []int{0, 1, 2, 3} { - for _, dc := range decoders { - t.Run(dc.name+", format "+string(rune('0'+format)), func(t *testing.T) { - ctx := context.Background() - fn := returning(scnUser{ID: 7, Name: "ann"}, nil) - a := &scnAssigns{} - m := scnMachine(fn, a) - store := &olderWriter{MemStore: durable.NewMemStore(durable.WithHistory()), format: format} - reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) - h := scnStart(t, m, store, reg) - mustRunService(t, h, state.InvokeID(scnInvoke, "loading", 0)) - _, recs, err := store.Load(ctx, "scn-1") - if err != nil || len(recs) != 1 || recs[0].Format != format { - t.Fatalf("the journal holds %+v (err %v), want one Record of format %d", recs, err, format) - } - - rh, err := durable.Recover(ctx, m, store, "scn-1", reg, dc.opt) - if err != nil { - t.Fatalf("Recover: %v; the older version recovered this journal", err) - } - if got := rh.Instance().Current(); got != "ready" { - t.Fatalf("recovered in %q, want ready", got) - } - if a.done != 2 { - t.Fatalf("onDone's Assign ran %d times, want 2 (live, replay)", a.done) - } - if _, ok := a.seen[1].(map[string]any); !ok { - t.Fatalf("replay saw %s, want the map[string]any the older version's replay gave", describe(a.seen[1])) - } - if _, err := durable.StateAt(ctx, m, store, "scn-1", 0, reg, dc.opt); err != nil { - t.Fatalf("StateAt: %v", err) - } - }) - } - } -} diff --git a/durable/journal_format_stateat_test.go b/durable/journal_format_stateat_test.go deleted file mode 100644 index ebfb8319..00000000 --- a/durable/journal_format_stateat_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package durable_test - -import ( - "context" - "errors" - "strconv" - "strings" - "testing" - - "github.com/stablekernel/crucible/durable" - "github.com/stablekernel/crucible/state" -) - -// These tests answer two review findings. StateAt checked the journal formats only of -// the Records up to its target step, while Recover checks its whole tail, so a journal -// Recover refuses as mixed-version still reconstructed through StateAt before the older -// Record. And undecodableResult's doc said its error always wraps ErrEventDataEncoding, -// though a result with no JSON form fails the Handle with an error that doesn't. - -// loopMachine stays in spin on every "go". -func loopMachine() *state.Machine[string, string, svcCtx] { - return state.ForgeFor[svcCtx]("loop"). - State("spin"). - Initial("spin"). - Transition("spin").On("go").GoTo("spin"). - Quench() -} - -// TestStateAt_RefusesAMixedJournalAtEveryStep: this version records steps 0 to 6 in -// format 2, and an older replica appends step 7 in format 1. Recover refuses the -// journal, so StateAt must refuse it at every step, before step 7 too, and Steps -// must refuse it, as each refuses a journal a newer version wrote. -func TestStateAt_RefusesAMixedJournalAtEveryStep(t *testing.T) { - for _, history := range []bool{false, true} { - name := "Load" - if history { - name = "History" - } - t.Run(name, func(t *testing.T) { - ctx := context.Background() - m := loopMachine() - var st *durable.MemStore - if history { - st = durable.NewMemStore(durable.WithHistory()) - } else { - st = durable.NewMemStore() - } - h, err := durable.NewRunner(m, st).Start(ctx, "l1", svcCtx{}, state.WithInitialState("spin")) - if err != nil { - t.Fatalf("Start: %v", err) - } - for i := range 7 { - if _, err = h.Fire(ctx, "go"); err != nil { - t.Fatalf("Fire %d: %v", i, err) - } - } - if _, err = st.Append(ctx, "l1", durable.Record{Step: 7, Event: []byte(`"go"`), Format: 1}); err != nil { - t.Fatalf("Append: %v", err) - } - mixed := func(what string, err error) { - t.Helper() - if err == nil || !strings.Contains(err.Error(), "older version") { - t.Errorf("%s = %v, want the mixed-version error", what, err) - } - } - _, err = durable.Recover(ctx, m, st, "l1") - mixed("Recover", err) - for _, step := range []int{durable.BaselineStep, 0, 5, 6, 7} { - _, err = durable.StateAt(ctx, m, st, "l1", step) - mixed("StateAt("+strconv.Itoa(step)+")", err) - } - _, err = durable.Steps(ctx, st, "l1") - mixed("Steps", err) - }) - } -} - -// TestRunService_ResultEncodingErrorsMatchTheirSentinels pins which sentinel each -// failed settle wraps. A result that won't decode is parked: RunService returns -// ErrEventDataEncoding with the Handle healthy. A result with no JSON form fails the -// Handle: RunService returns ErrHandleFailed, not ErrEventDataEncoding, whose Handle -// stays usable. -func TestRunService_ResultEncodingErrorsMatchTheirSentinels(t *testing.T) { - t.Run("won't decode", func(t *testing.T) { - _, runErr, _ := scnRun(t, returning(scnUser{ID: 7, Name: "ann"}, nil), failingDecoder()) - if !errors.Is(runErr, durable.ErrEventDataEncoding) || errors.Is(runErr, durable.ErrHandleFailed) { - t.Errorf("RunService = %v, want ErrEventDataEncoding without ErrHandleFailed", runErr) - } - }) - t.Run("won't encode", func(t *testing.T) { - _, runErr, _ := scnRun(t, returning(make(chan int), nil)) - if !errors.Is(runErr, durable.ErrHandleFailed) || errors.Is(runErr, durable.ErrEventDataEncoding) { - t.Errorf("RunService = %v, want ErrHandleFailed without ErrEventDataEncoding", runErr) - } - }) -} diff --git a/durable/result_decoding_scenarios_test.go b/durable/result_decoding_scenarios_test.go index 1e1f9d68..c41cbbf6 100644 --- a/durable/result_decoding_scenarios_test.go +++ b/durable/result_decoding_scenarios_test.go @@ -369,3 +369,23 @@ func TestServiceResult_RecordedResultThatWontDecode_RunsNoAssignOnReplay(t *test t.Fatalf("after StateAt: onDone ran %d times and onError %d, want no more than live's 1 and 0", a.done, a.fails) } } + +// TestRunService_ResultEncodingErrorsMatchTheirSentinels pins which sentinel each +// failed settle wraps. A result that won't decode is parked: RunService returns +// ErrEventDataEncoding with the Handle healthy. A result with no JSON form fails the +// Handle: RunService returns ErrHandleFailed, not ErrEventDataEncoding, whose Handle +// stays usable. +func TestRunService_ResultEncodingErrorsMatchTheirSentinels(t *testing.T) { + t.Run("won't decode", func(t *testing.T) { + _, runErr, _ := scnRun(t, returning(scnUser{ID: 7, Name: "ann"}, nil), failingDecoder()) + if !errors.Is(runErr, durable.ErrEventDataEncoding) || errors.Is(runErr, durable.ErrHandleFailed) { + t.Errorf("RunService = %v, want ErrEventDataEncoding without ErrHandleFailed", runErr) + } + }) + t.Run("won't encode", func(t *testing.T) { + _, runErr, _ := scnRun(t, returning(make(chan int), nil)) + if !errors.Is(runErr, durable.ErrHandleFailed) || errors.Is(runErr, durable.ErrEventDataEncoding) { + t.Errorf("RunService = %v, want ErrHandleFailed without ErrEventDataEncoding", runErr) + } + }) +} diff --git a/durable/runner.go b/durable/runner.go index d6471ad0..99387387 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -1662,12 +1662,9 @@ func (h *Handle[S, E, C]) respawn(ctx context.Context, effects []state.Effect, u // effect not yet marked dispatched, so it returns ErrEffectDispatch and no Handle while // the effect handler keeps failing. With an effect handler wired, it refuses a Store // that isn't a DispatchStore with ErrNoDispatchStore before it loads anything, whether -// or not an effect is waiting. It refuses a journal a newer version of this module -// wrote, whose checkpoint or any Record records a journal format above this version's, -// before it restores or replays anything; that error wraps none of the package's -// sentinel errors. 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. +// or not an effect is waiting. It re-arms the checkpoint's timers before replaying the +// tail, and fails when a tick of journal format 3 or later fires a different number of +// timers on replay than it recorded. func Recover[S comparable, E comparable, C any](ctx context.Context, m *state.Machine[S, E, C], st Store, id InstanceID, opts ...Option[S, E, C]) (*Handle[S, E, C], error) { r := NewRunner(m, st, opts...) return r.recover(ctx, id) @@ -1693,14 +1690,6 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // deadlines of the timers armed at the checkpoint, and the next step ordinal. A bare // (pre-envelope) checkpoint yields the snapshot with no persisted timers. env := unmarshalCheckpoint(snapBytes) - if err = checkNotNewer(id, env.Format, tail); err != nil { - return nil, err - } - // Refuse a journal mixed versions wrote before replaying any of it, so a refused one - // sends no effect. - if err = checkFormats(env.Format, tail); err != nil { - return nil, fmt.Errorf("durable: recovering %q: %w", id, err) - } kernelSnap, persistedTimers, checkpointNext := env.Snapshot, env.Timers, env.NextStep snap, err := state.UnmarshalSnapshot[S, E, C](kernelSnap) @@ -1799,6 +1788,9 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S // The mirror tracks the still-pending timers in armed as replay arms, cancels and // fires them, with deadlines drawn from the recorded clock reads, not the live // wall clock. + if err := checkFormat(env.Format, rec); err != nil { + return nil, fmt.Errorf("durable: recovering %q: %w", id, err) + } reads += clockReadCount(rec) stepEffects, err := replayRecord(ctx, inst, &r.cfg, sched, svc, rec, mirror, armsActorFires(rec)) if err != nil { @@ -2311,7 +2303,7 @@ func replayRecord[S comparable, E comparable, C any]( mirror.park(entry.CorrelationID, recordedResult{raw: sp.Result, typ: sp.Type}) continue } - effects, err := replayService(ctx, svc, entry, sp, rec.Format >= decodedResultsFormat) + effects, err := replayService(ctx, svc, entry, sp) if err != nil { return stepEffects, fmt.Errorf("at step %d: %w", rec.Step, err) } @@ -2384,52 +2376,12 @@ func replayActors[S comparable, E comparable, C any]( return nil } -// checkFormats fails when a Record in records has a lower journal Format than the -// checkpoint's that replay starts from, or than any Record before it (see checkFormat). -// A journal's format never goes down, so this catches an older version's Record -// appended after a newer one's anywhere in the tail, not only after a newer checkpoint. -// Recover calls it on its tail, and StateAt and Steps on every Record they load, past -// the step StateAt targets too, before any of them replays one. -func checkFormats(checkpoint int, records []Record) error { - highest := checkpoint - for i := range records { - if err := checkFormat(highest, &records[i]); err != nil { - return err - } - highest = max(highest, records[i].Format) - } - return nil -} - -// checkFormat fails when rec's journal Format is lower than highest, the highest format -// the journal records before it: the checkpoint's, or an earlier Record's. A version -// doesn't write an older format than it did, so either an older version appended rec to -// a journal a newer one wrote, which a rolling deploy that runs mixed versions on one -// instance does, or, for a Record with no format, the Store lost the field. Either way -// the two versions may read the journal differently (an older one settles a parked -// result, for one), so replaying rec by its own format's rules would recover wrong. -func checkFormat(highest int, rec *Record) error { - switch { - case rec.Format >= highest: - return nil - case rec.Format == 0: - return fmt.Errorf("durable: step %d records no journal format after one of format %d: the Store didn't keep Record.Format, or a version from before that field appended the Record (mixed versions on one instance)", rec.Step, highest) - } - return fmt.Errorf("durable: step %d was appended by an older version, of journal format %d, after one of format %d: don't run mixed versions on one instance", rec.Step, rec.Format, highest) -} - -// checkNotNewer fails when id's checkpoint, of journal format checkpoint, or any of its -// records was written in a journal format above journalFormat: by a newer version, whose -// journal this version can't tell from its own, so replaying it could recover wrong. -// Every reader calls it on what it loaded before it restores or replays anything. The -// error wraps no sentinel. -func checkNotNewer(id InstanceID, checkpoint int, records []Record) error { - format := checkpoint - for i := range records { - format = max(format, records[i].Format) - } - if format > journalFormat { - return fmt.Errorf("durable: %q was written by a newer version (journal format %d; this version reads up to %d)", id, format, journalFormat) +// checkFormat fails when rec's journal Format is lower than the checkpoint's that replay +// started from: a version doesn't write an older format than it did, so the Store lost +// the field, and replaying the Record as an older format's would recover wrong. +func checkFormat(checkpoint int, rec *Record) error { + if rec.Format < checkpoint { + return fmt.Errorf("durable: step %d records journal format %d after a checkpoint of format %d: the Store didn't keep Record.Format", rec.Step, rec.Format, checkpoint) } return nil } @@ -2448,10 +2400,8 @@ func armsActorFires(rec *Record) bool { return rec.Format >= actorArmsFormat } -// journalFormat is the format this version writes in every Record and checkpoint, and -// the highest it reads: Recover, the stateless Fire, StateAt and Steps refuse a journal -// whose checkpoint or any Record records a higher one (see checkNotNewer). It is -// decodedResultsFormat. actorArmsFormat is the first format that arms the timers and +// journalFormat is the format this version writes in every Record and checkpoint. It is +// timersFirstFormat. actorArmsFormat is the first format that arms the timers and // services an actor-driven parent Fire's state declares. dispatchedStepsFormat is the // first that dispatches a tick's and a service settle's domain effects, so Recover sends // them. tickDriversFormat is the first whose Tick hands its timer transitions' effects @@ -2460,17 +2410,12 @@ func armsActorFires(rec *Record) bool { // before the tail, so its replayed ticks fire exactly the timers they record. An older // version's recovery re-armed them after the tail, so a journal it continued can record // a tick replay can't reproduce: a timer the tail had fired or canceled, fired again. -// decodedResultsFormat is the first whose service results the live run decoded through -// WithEventDataDecoder, so replay decodes them the same way; it is also the first that -// can park a result. A result in a Record of an older format replays as that version -// replayed it, in JSON's generic form. const ( actorArmsFormat = 1 dispatchedStepsFormat = 2 tickDriversFormat = 2 timersFirstFormat = 3 - decodedResultsFormat = 4 - journalFormat = decodedResultsFormat + journalFormat = timersFirstFormat ) // replayArm arms the timers and services a replayed Fire's effects declare, as the live diff --git a/durable/service.go b/durable/service.go index bd0d83ae..94d6f732 100644 --- a/durable/service.go +++ b/durable/service.go @@ -62,9 +62,7 @@ type serviceResultPayload struct { // SettleDone outcome: the bytes the live settle decoded. Replay decodes them through // the Runner's EventDataDecoder for the onDone event and re-fires them through // onDone, so the transition's Assign reads from AssignCtx.Event the value the live - // run's decode gave (see replayableOutcome). A Record of a format before - // decodedResultsFormat replays them in JSON's generic form, as the version that - // wrote it did. + // run's decode gave (see replayableOutcome). Result json.RawMessage `json:"result,omitempty"` // Error is the failure message for a SettleError outcome. It is reconstructed // into an error and re-fired through onError so the transition's Assign reads it @@ -80,7 +78,7 @@ type serviceResultPayload struct { // holds the decoder to that type, as the live settle did, and every successful // settle records it, the one that settles a parked result too, so replay holds the // decoder to it as the settle did. It is empty for an error, and for a result - // recorded before this field, which replays with no type check. + // recorded with no type, which replays with no type check. Type string `json:"type,omitempty"` } @@ -376,8 +374,7 @@ func (h *Handle[S, E, C]) markSettled(id string) { // replayService fails the replay. A parked result settles as a recordedResult that // carries its Go type, and the decoder must return that type, or JSON's generic form, // as live. A result with no JSON form aborts the settle too, with no JSON to park, and -// serviceStep fails the Handle. A legacyResult, which replay passes for a Record of an -// older format, settles as it is, as that version replayed it. +// serviceStep fails the Handle. // // An error becomes an error with its message as a Store keeps it (see // normalizedErrorMessage), live and on replay. An Error method that panics settles @@ -392,9 +389,6 @@ func replayableOutcome[E comparable](decode EventDataDecoder[E], settled *settle } return nil, errors.New(msg), nil } - if legacy, ok := result.(legacyResult); ok { - return legacy.value, nil, nil - } recorded, replay := result.(recordedResult) b := []byte(recorded.raw) if !replay { @@ -466,11 +460,6 @@ func (s *settledJSON) take() recordedResult { return r } -// legacyResult is a service result recorded in a Record of a format before -// decodedResultsFormat, decoded as that version replayed it: into an any, with no -// decoder or type check. The transform settles it as it is. -type legacyResult struct{ value any } - // resultType returns the Go type a park, or a successful settle, records for result: // the recorded one on replay, else the ServiceFn's value's. func resultType(recorded recordedResult, replay bool, result any) string { @@ -486,8 +475,8 @@ func resultType(recorded recordedResult, replay bool, result any) string { type recordedResult struct { raw json.RawMessage // typ is the result's Go type, as typeName gives it, which a park and every - // successful settle record; empty for a result recorded before settles recorded it, - // which replay doesn't type-check. + // successful settle record; empty for a result recorded with no type, which replay + // doesn't type-check. typ string // rtype is the result's Go type itself, which only a result this Handle parked // carries: typ can't tell apart two types of the same name and package, such as two @@ -650,21 +639,23 @@ func qualifiedName(pkg, name string) string { // generic form are always accepted. A result this Handle parked keeps its type, and is // held to it as live held it; one read from the journal or a checkpoint is held to its // name, which a type of the same name and package, such as another function-local type, -// also has. An empty name, a result recorded before settles recorded the type, accepts -// anything. +// also has. An empty name, a result recorded with no type, accepts anything. func decodedAsRecorded(value any, recorded recordedResult) error { typ := recorded.typ if typ == "" || value == nil || genericJSON(value) { return nil } - if recorded.rtype != nil && reflect.TypeOf(value) != recorded.rtype { - return fmt.Errorf("%w: a %s service result decodes as another type, %v, of the same name or not; decode it as the service's own %s with WithEventDataDecoder", - ErrEventDataEncoding, typ, reflect.TypeOf(value), typ) - } if got := typeName(value); got != typ { return fmt.Errorf("%w: a %s service result decodes as %s; decode it as %s with WithEventDataDecoder", ErrEventDataEncoding, typ, got, typ) } + // The names agree, so only a result this Handle parked, which carries its type + // itself, can be another type: one of the same name and package, such as another + // function-local type. + if recorded.rtype != nil && reflect.TypeOf(value) != recorded.rtype { + return fmt.Errorf("%w: a %s service result decodes as another type of the same name; decode it as the service's own type with WithEventDataDecoder", + ErrEventDataEncoding, typ) + } return nil } @@ -742,13 +733,10 @@ func recordServiceOutcome(id string, settled recordedResult, lastErr error) (sta // SettleError (with the reconstructed error), so the kernel re-fires the same // onDone / onError event with the same data and re-derives identical context. It // returns the settle's effects, so the caller arms the timers its state declares, as -// the live RunService did. sp is entry's decoded payload. A result in a Record of a -// format before decodedResultsFormat (decoded false) replays as the version that wrote -// it replayed it, in JSON's generic form through no decoder: that version's live run -// saw the ServiceFn's own value, which no decoder of this one can be held to. It -// reports an error only when the recorded result cannot be decoded or names no -// in-flight service (a corrupt or mis-ordered journal). -func replayService[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], entry state.JournalEntry, sp serviceResultPayload, decoded bool) ([]state.Effect, error) { +// the live RunService did. sp is entry's decoded payload. It reports an error only when +// the recorded result cannot be decoded or names no in-flight service (a corrupt or +// mis-ordered journal). +func replayService[S comparable, E comparable, C any](ctx context.Context, svc *state.ServiceRunner[S, E, C], entry state.JournalEntry, sp serviceResultPayload) ([]state.Effect, error) { if svc == nil { return nil, errors.New("durable: replaying a service result requires a service registry (supply WithServiceRegistry)") } @@ -762,16 +750,7 @@ func replayService[S comparable, E comparable, C any](ctx context.Context, svc * // The transform decodes the recorded JSON for the onDone event, as it did live. One // that won't decode aborts the settle before it fires anything. var result any - switch { - case !decoded: - var v any - if len(sp.Result) > 0 { - if err := json.Unmarshal(sp.Result, &v); err != nil { - return nil, fmt.Errorf("durable: decoding recorded service %q result: %w", entry.CorrelationID, err) - } - } - result = legacyResult{value: v} - case len(sp.Result) > 0: + if len(sp.Result) > 0 { // The recorded type holds the decoder to it, as the settle did. result = recordedResult{raw: sp.Result, typ: sp.Type} } diff --git a/durable/service_activation_test.go b/durable/service_activation_test.go index e4d52ad2..3a3fb4e5 100644 --- a/durable/service_activation_test.go +++ b/durable/service_activation_test.go @@ -50,3 +50,22 @@ func TestRunService_ServiceFnCantChangeItsActivation(t *testing.T) { t.Fatalf("the journal holds %d Records, want the settle's", got) } } + +// forkMachine invokes fetch in loading. "next" is declared in loading and in ready, +// with different targets, so a journal replayed from the wrong state still replays, +// to the wrong place. +func forkMachine(fn state.ServiceFn[svcCtx]) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("fork"). + Service("fetch", fn). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done"), state.WithInvokeOnError("fail")). + State("ready"). + State("canceled").Final(). + State("shipped").Final(). + State("failed").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("ready"). + Transition("loading").On("fail").GoTo("failed"). + Transition("loading").On("next").GoTo("canceled"). + Transition("ready").On("next").GoTo("shipped"). + Quench() +} diff --git a/durable/store.go b/durable/store.go index 6e51cd5f..033cd3d4 100644 --- a/durable/store.go +++ b/durable/store.go @@ -126,12 +126,7 @@ type Record struct { // 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. From format 4 the live run decoded each - // service result through WithEventDataDecoder, and replay does too; a result in an - // older Record replays in JSON's generic form, as that version replayed it. A Store - // keeps it as it keeps Step. A version reads up to the format it writes: Recover, - // StateAt and Steps refuse a journal with a Record or checkpoint of a higher format, - // one a newer version wrote. Versions built before that check don't refuse one. + // different number of timers than TickSteps. A Store keeps it as it keeps Step. Format int `json:",omitempty"` } diff --git a/durable/timetravel.go b/durable/timetravel.go index 09240acd..1c3b6a4b 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -103,13 +103,9 @@ func (v *TimeTravelView[S, E, C]) Step() int { return v.step } // // step must be in [BaselineStep, lastRecordedStep]; a step outside that range // reports ErrStepOutOfRange, an unknown instance reports ErrInstanceNotFound, and an -// ended ctx reports its error. A journal a newer version wrote, whose baseline or any -// Record records a journal format above this version's, is refused whatever the step, -// as Recover refuses it, and so is one mixed versions wrote, where any Record, before -// or after step, records a lower format than one before it. -// 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. +// ended ctx reports its error. It also fails when a baseline timer's event won't decode +// with the event codec passed, and when a tick of journal format 3 or later fires a +// different number of timers on replay than it recorded. func StateAt[S comparable, E comparable, C any]( ctx context.Context, m *state.Machine[S, E, C], @@ -127,10 +123,6 @@ func StateAt[S comparable, E comparable, C any]( if baseline == nil { return nil, fmt.Errorf("durable: instance %q has no baseline to reconstruct", id) } - format := unmarshalCheckpoint(baseline).Format - if err = checkJournal(id, format, records); err != nil { - return nil, err - } last := lastStep(records) if step < BaselineStep || step > last { @@ -160,16 +152,12 @@ func StateAt[S comparable, E comparable, C any]( // 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, and a journal a newer version, or mixed versions, wrote is -// refused, as StateAt refuses it. +// ErrInstanceNotFound. func Steps(ctx context.Context, st Store, id InstanceID) ([]int, error) { - baseline, records, err := loadHistory(ctx, st, id) + _, records, err := loadHistory(ctx, st, id) if err != nil { return nil, err } - if err = checkJournal(id, unmarshalCheckpoint(baseline).Format, records); err != nil { - return nil, err - } out := make([]int, 0, len(records)) for i := range records { out = append(out, records[i].Step) @@ -177,20 +165,6 @@ func Steps(ctx context.Context, st Store, id InstanceID) ([]int, error) { return out, nil } -// checkJournal refuses a journal Recover refuses, whatever step a reader targets: one -// a newer version wrote (see checkNotNewer), or one mixed versions wrote (see -// checkFormats). It checks every loaded Record, not only those up to a target step, so -// StateAt and Steps refuse the same journals at every step. -func checkJournal(id InstanceID, baseline int, records []Record) error { - if err := checkNotNewer(id, baseline, records); err != nil { - return err - } - if err := checkFormats(baseline, records); err != nil { - return fmt.Errorf("durable: reading %q: %w", id, err) - } - return nil -} - // loadHistory returns an instance's baseline snapshot and full ordered Record log, // using the HistoryStore seam when the Store implements it (so a compacted step is // still reachable) and falling back to Load's latest-checkpoint-plus-tail otherwise. @@ -252,8 +226,7 @@ func restoreBaseline[S comparable, E comparable, C any]( // It is the bounded, read-only analog of Recover's replay loop: it builds its own // service host driver (to settle recorded outcomes) and ticks a scheduler over the // instance's recorded-instant clock, consuming exactly the records the caller bounded -// to the target step. StateAt has already checked the formats of every Record, those -// past the window too. +// to the target step. func replayThrough[S comparable, E comparable, C any]( ctx context.Context, inst *state.Instance[S, E, C], @@ -292,6 +265,9 @@ func replayThrough[S comparable, E comparable, C any]( } // A domain effect is never dispatched here: a time-travel read applies no // side effect. + if err := checkFormat(env.Format, &bounded[i]); err != nil { + return err + } reads += clockReadCount(&bounded[i]) if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, armsActorFires(&bounded[i])); err != nil { return err diff --git a/state/CHANGELOG.md b/state/CHANGELOG.md index 2763d187..f7efc481 100644 --- a/state/CHANGELOG.md +++ b/state/CHANGELOG.md @@ -39,8 +39,8 @@ counts as an additive (minor) versus breaking (major) change. Use the - **`ServiceRunner.WithResultTransform`** rewrites every service outcome before it settles, whether `Tick`, `SettleDone` or `SettleError` settles it, so a host that records outcomes can give the live run and a replay the same value. The transform takes the - event that will carry the outcome, the invocation's onDone for a result and its onError - for an error: `func(event E, result any, err error) (out any, outErr error, abort error)`. + invocation's onDone event for an incoming result and its onError event for an incoming + error: `func(event E, result any, err error) (out any, outErr error, abort error)`. It runs before any event fires and before the service is dropped. A non-nil `abort` stops the settle: no event fires, the service stays in flight, `SettleDone` and `SettleError` return false with `abort` in `FireResult.Err`, and `Tick` returns that diff --git a/state/runner.go b/state/runner.go index e211db1c..9558b67c 100644 --- a/state/runner.go +++ b/state/runner.go @@ -260,15 +260,16 @@ func (r *ServiceRunner[S, E, C]) settleActivation(ctx context.Context, id string // WithResultTransform sets a function that rewrites every outcome before it settles, // whether Tick, SettleDone or SettleError settles it, and returns the runner. f gets -// the event that will carry the outcome: the invocation's onDone for a result, its -// onError for an error. A host that records outcomes uses it to give the live run and +// the invocation's onDone event for an incoming result, its onError event for an +// incoming error. A host that records outcomes uses it to give the live run and // a replay the same value, decoded for that event. // // f returns the outcome to settle with, out and outErr. A non-nil outErr settles // through onError, and a nil one through onDone with out, except for an // UnboundRefError: a nil outErr leaves the UnboundRefError, so an unbound service // still settles through onError. LastResult and LastError report the rewritten -// outcome. +// outcome. f sees the event for the outcome as it came in: an outErr f returns +// settles through onError even when f was handed the onDone event of a result. // // A non-nil abort stops the settle instead: no event fires, so no Assign, middleware // or inspector runs, and the service stays in flight, so it can be settled again. From 699c534387634c9d716dfd84ef1369a6cee6509b Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 20 Nov 2026 15:25:37 -0700 Subject: [PATCH 3/4] feat(durable): accept a renamed service result type with WithResultTypeAlias Every settle journals the result's full Go type name, and replay holds the decoder to it, so a pure refactor that moves or renames the type failed Recover and StateAt with ErrEventDataEncoding for every journal already settled under the old name. WithResultTypeAlias tells the Runner what a recorded name now means: a value of the renamed type settles results recorded under the old name, on every path that holds a result to its recorded name -- Recover from the journal or a checkpoint, StateAt, and a RunService settling a parked result read back from the journal or a checkpoint. Every other recorded name is checked strictly, exactly as before; a result parked by the Handle itself stays held to its own type, as live. A rename is one hop: an alias never chains through another. Bad input changes nothing, as the other Runner options, leaving the strict check standing. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 12 + durable/README.md | 2 + durable/doc.go | 11 +- durable/result_alias_test.go | 408 ++++++++++++++++++++++++ durable/runner.go | 2 +- durable/runner_options.go | 47 ++- durable/service.go | 25 +- durable/service_encode_internal_test.go | 4 +- durable/settle_absorb_internal_test.go | 2 +- durable/timetravel.go | 2 +- 10 files changed, 496 insertions(+), 19 deletions(-) create mode 100644 durable/result_alias_test.go diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index b59da216..908738c4 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -9,6 +9,18 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ### Added +- **`WithResultTypeAlias`** tells the Runner that a service result type the journal + recorded under one full Go type name now goes by another, so a result settled or + parked under the old name still replays after a pure refactor moves or renames the + type: `Recover`, `StateAt` and a `RunService` that settles a recorded result accept + the decoded value when its type is the one the alias names, and every other recorded + name is held to strictly, exactly as before. A parked result the Handle itself holds + is still held to its own type, as live. The option takes the recorded name and a + value of the type the name now means, can be repeated for several renames, and maps + one hop, never chaining through another alias. Bad input — an empty recorded name, a + nil value, a name aliased to the type's own current name, or one recorded name for + two different types — is ignored, like the other Runner options, leaving the strict + check in place. - **`Record.EndedActors` and `ActorSet`** record the declared child-machine actors that ran and have ended, settled or stopped, so `Recover` doesn't spawn them again. A Store must keep an empty set distinct from nil. diff --git a/durable/README.md b/durable/README.md index 70935bbe..127f6862 100644 --- a/durable/README.md +++ b/durable/README.md @@ -198,6 +198,8 @@ longer matches. Register the decoder before you record results: replay decodes t with the recovering Runner's decoder, so a decoder added or changed after results were recorded changes what replay hands the reducer, and one that can't decode a settled result fails `Recover` and `StateAt` with `ErrEventDataEncoding`; a parked one doesn't fail them. A +type moved or renamed after its results were recorded replays under its new name once +told to the Runner with `WithResultTypeAlias`. 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, chosen per event, for example `durable.DecodeAs[Order]`. Without one, a payload decodes as JSON's own diff --git a/durable/doc.go b/durable/doc.go index ad935121..ee87dfa5 100644 --- a/durable/doc.go +++ b/durable/doc.go @@ -51,14 +51,17 @@ // is part of the Runner's options, so the Handle that parked the result never sees a // fix: Recover with the fixed decoder, then call RunService, and it settles the parked // result. The decoder must return the type the service returned, by import path and -// name, or JSON's generic form, so settle parked results before moving or renaming that -// type; after a move, only a decoder that returns the generic form settles them. +// name, or JSON's generic form, so settle parked results before moving or renaming +// that type, or tell the Runner what the recorded name now means with +// WithResultTypeAlias; after a move without an alias, only a decoder that returns the +// generic form settles them. // A Fire or timer that leaves the state that declares the service stops it and // discards the parked result. A service error stays message-only. Register the decoder before recording results: replay decodes the // journal with the recovering Runner's decoder, held to the Go type the service // returned, which every settle records, so a decoder changed after results were -// recorded to return another type fails Recover, unless it returns JSON's generic form, -// and one added later for the service's type changes what replay produces. +// recorded to return another type fails Recover, unless it returns JSON's generic form +// or the recorded type's new name is aliased (WithResultTypeAlias), and one added later +// for the service's type changes what replay produces. // // 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- diff --git a/durable/result_alias_test.go b/durable/result_alias_test.go new file mode 100644 index 00000000..75496203 --- /dev/null +++ b/durable/result_alias_test.go @@ -0,0 +1,408 @@ +package durable_test + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync/atomic" + "testing" + + "github.com/stablekernel/crucible/durable" + alpha "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model" + beta "github.com/stablekernel/crucible/durable/internal/typefixture/beta/model" + "github.com/stablekernel/crucible/state" +) + +// These tests answer a review finding on the Go type every settle records: a settled +// result is pinned to its full type name, so a pure refactor that moves or renames the +// type makes Recover and StateAt fail with ErrEventDataEncoding for every journal +// already settled under the old name. WithResultTypeAlias tells the Runner what a +// recorded name now means, on every path that holds a result to its recorded name. + +// alphaAlias is the option mapping the type alpha.Result recorded before a rename, as +// rewriteServiceTypes stands in for one, to alpha.Result. +func alphaAlias() durable.Option[string, string, svcCtx] { + return durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}) +} + +// settledAlpha settles an alpha.Result for scn-1 live, under a decoder for it, and +// returns what Recover and StateAt need. +func settledAlpha(t *testing.T) (*state.Machine[string, string, svcCtx], *scnAssigns, durable.Option[string, string, svcCtx], *durable.MemStore) { + t.Helper() + fn := returning(alpha.Result{ID: 7, Name: "ann"}, nil) + a := &scnAssigns{} + m := scnMachine(fn, a) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + store := durable.NewMemStore() + h := scnStart(t, m, store, reg, decoderFor("done", durable.DecodeAs[alpha.Result])) + mustRunService(t, h, state.InvokeID(scnInvoke, "loading", 0)) + return m, a, reg, store +} + +// renamedSettled settles an alpha.Result live and returns the machine, its Assigns, the +// registry option and a journal whose settle records the type under the old name +// movedFromType, as if the settle ran before the rename. +func renamedSettled(t *testing.T) (*state.Machine[string, string, svcCtx], *scnAssigns, durable.Option[string, string, svcCtx], *durable.MemStore) { + t.Helper() + m, a, reg, src := settledAlpha(t) + return m, a, reg, rewriteServiceTypes(t, src, alphaResultType, movedFromType) +} + +// TestResultTypeAlias_RenamedSettledResult: a settle recorded under the type's old +// name fails Recover and StateAt with ErrEventDataEncoding under a decoder for the +// type's new name, naming the recorded type; WithResultTypeAlias admits the new type, +// on both paths, and the value onDone's Assign sees is the one the service returned. +func TestResultTypeAlias_RenamedSettledResult(t *testing.T) { + ctx := context.Background() + m, a, reg, store := renamedSettled(t) + steps, stepsErr := durable.Steps(ctx, store, "scn-1") + if stepsErr != nil || len(steps) != 1 { + t.Fatalf("Steps = %v, %v; want the settle", steps, stepsErr) + } + asAlpha := decoderFor("done", durable.DecodeAs[alpha.Result]) + for _, what := range []struct { + name string + call func() error + }{ + {"Recover", func() error { + _, err := durable.Recover(ctx, m, store, "scn-1", reg, asAlpha) + return err + }}, + {"StateAt", func() error { + _, err := durable.StateAt(ctx, m, store, "scn-1", steps[0], reg, asAlpha) + return err + }}, + } { + err := what.call() + if !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("%s without the alias: %v, want ErrEventDataEncoding", what.name, err) + } + if !strings.Contains(err.Error(), movedFromType) { + t.Fatalf("%s without the alias: %v, want it to name the recorded type %s", what.name, err, movedFromType) + } + } + if a.done != 1 || a.fails != 0 { + t.Fatalf("a failed replay ran an Assign: onDone %d, onError %d", a.done, a.fails) + } + + h, err := durable.Recover(ctx, m, store, "scn-1", reg, asAlpha, alphaAlias()) + if err != nil { + t.Fatalf("Recover with the alias: %v", err) + } + if got := h.Instance().Current(); got != "ready" { + t.Fatalf("Recover with the alias: in %q, want ready", got) + } + if a.done != 2 || describe(a.seen[1]) != describe(alpha.Result{ID: 7, Name: "ann"}) { + t.Fatalf("replay with the alias ran onDone %d times and saw %v, want the alpha.Result", a.done, a.seen) + } + v, err := durable.StateAt(ctx, m, store, "scn-1", steps[0], reg, asAlpha, alphaAlias()) + if err != nil { + t.Fatalf("StateAt with the alias: %v", err) + } + if got := v.Instance().Current(); got != "ready" { + t.Fatalf("StateAt with the alias: in %q, want ready", got) + } +} + +// threeSettlesMachine settles fn three times: "loading" invokes fetch, and each onDone +// enters the next state, which invokes fetch again, so a checkpoint after the second +// settle leaves the third one in the tail a Recover from that checkpoint replays. +func threeSettlesMachine(fn state.ServiceFn[svcCtx], a *scnAssigns) *state.Machine[string, string, svcCtx] { + return state.ForgeFor[svcCtx]("scn"). + Service("fetch", fn). + Reducer("noteDone", func(in state.AssignCtx[svcCtx]) svcCtx { + a.done++ + a.seen = append(a.seen, in.Event) + return in.Entity + }). + State("loading").Invoke("fetch", state.WithInvokeOnDone("done")). + State("second").Invoke("fetch", state.WithInvokeOnDone("done")). + State("third").Invoke("fetch", state.WithInvokeOnDone("done")). + State("ready").Final(). + Initial("loading"). + Transition("loading").On("done").GoTo("second").Assign("noteDone"). + Transition("second").On("done").GoTo("third").Assign("noteDone"). + Transition("third").On("done").GoTo("ready").Assign("noteDone"). + Quench() +} + +// TestResultTypeAlias_RenamedSettledResultThroughCheckpoint: a checkpoint that +// compacts the earlier settles leaves the last one in the tail, and a Recover from it +// replays that settle's recorded type: the old name fails it, and WithResultTypeAlias +// settles it, with the value the service returned. +func TestResultTypeAlias_RenamedSettledResultThroughCheckpoint(t *testing.T) { + ctx := context.Background() + fn := returning(alpha.Result{ID: 7, Name: "ann"}, nil) + a := &scnAssigns{} + m := threeSettlesMachine(fn, a) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + store := durable.NewMemStore() + asAlpha := decoderFor("done", durable.DecodeAs[alpha.Result]) + // A checkpoint lands after the second settle (steps 0 and 2 of three cross no + // boundary; step 1 crosses 2), compacting the first two and leaving the third. + every := durable.WithCheckpointEvery[string, string, svcCtx](2) + h := scnStart(t, m, store, reg, asAlpha, every) + for _, st := range []string{"loading", "second", "third"} { + mustRunService(t, h, state.InvokeID(scnInvoke, st, 0)) + } + // The first two settles checkpointed; the tail holds the third one. + _, recs, lerr := store.Load(ctx, "scn-1") + if lerr != nil || len(recs) != 1 || recs[0].Step != 2 { + t.Fatalf("the journal holds %v (err %v), want only the third settle at step 2", recs, lerr) + } + renamed := rewriteServiceTypes(t, store, alphaResultType, movedFromType) + if _, err := durable.Recover(ctx, m, renamed, "scn-1", reg, asAlpha, every); !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Recover from the checkpoint without the alias: %v, want ErrEventDataEncoding", err) + } + if a.done != 3 || a.fails != 0 { + t.Fatalf("a failed replay ran an Assign: onDone %d, onError %d", a.done, a.fails) + } + rh, err := durable.Recover(ctx, m, renamed, "scn-1", reg, asAlpha, alphaAlias(), every) + if err != nil { + t.Fatalf("Recover from the checkpoint with the alias: %v", err) + } + if got := rh.Instance().Current(); got != "ready" { + t.Fatalf("in %q, want ready", got) + } + if a.done != 4 || describe(a.seen[3]) != describe(alpha.Result{ID: 7, Name: "ann"}) { + t.Fatalf("replay with the alias ran onDone %d times and saw %v, want the alpha.Result", a.done, a.seen) + } +} + +// rewriteParkedCheckpoint copies scn-1's journal into a fresh MemStore with every +// parked result its checkpoint carries recorded under from replaced by to, as if the +// type had been renamed after the checkpoint that kept the result. +func rewriteParkedCheckpoint(t *testing.T, src *durable.MemStore, from, to string) *durable.MemStore { + t.Helper() + ctx := context.Background() + snap, recs, err := src.Load(ctx, "scn-1") + if err != nil { + t.Fatalf("Load: %v", err) + } + var env map[string]json.RawMessage + if err = json.Unmarshal(snap, &env); err != nil || len(env["snapshot"]) == 0 { + t.Fatalf("the checkpoint for scn-1 is not an envelope (err %v): %s", err, snap) + } + var parked []struct { + ID string `json:"id"` + Result json.RawMessage `json:"result"` + Type string `json:"type"` + } + if err = json.Unmarshal(env["parkedServices"], &parked); err != nil || len(parked) == 0 { + t.Fatalf("the checkpoint carries no parked result (err %v): %s", err, env["parkedServices"]) + } + rewrote := 0 + for i := range parked { + if parked[i].Type == from { + parked[i].Type = to + rewrote++ + } + } + if rewrote == 0 { + t.Fatalf("no parked result recorded the type %s", from) + } + if env["parkedServices"], err = json.Marshal(parked); err != nil { + t.Fatalf("encoding the parked results: %v", err) + } + if snap, err = json.Marshal(env); err != nil { + t.Fatalf("encoding the checkpoint envelope: %v", err) + } + dst := durable.NewMemStore() + if err = dst.Checkpoint(ctx, "scn-1", snap, -1); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + for _, rec := range recs { + if _, err = dst.Append(ctx, "scn-1", rec); err != nil { + t.Fatalf("Append: %v", err) + } + } + return dst +} + +// TestResultTypeAlias_RenamedParkedResultThroughCheckpoint: a checkpoint keeps a +// parked result with its recorded type, and a Recover from it settles that result +// through RunService. The old name keeps it parked, naming the recorded type; the +// alias settles it, with the value the service returned and the ServiceFn never run +// again. +func TestResultTypeAlias_RenamedParkedResultThroughCheckpoint(t *testing.T) { + ctx := context.Background() + runs := new(int64) + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + atomic.AddInt64(runs, 1) + return alpha.Result{ID: 7, Name: "ann"}, nil + } + a := &scnAssigns{} + m := scnMachine(fn, a) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + store := durable.NewMemStore() + every := durable.WithCheckpointEvery[string, string, svcCtx](1) + h := scnStart(t, m, store, reg, failingDecoder(), every) + id := state.InvokeID(scnInvoke, "loading", 0) + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + if _, recs, lerr := store.Load(ctx, "scn-1"); lerr != nil || len(recs) != 0 { + t.Fatalf("the tail holds %d Records (err %v), want none: the park step should checkpoint", len(recs), lerr) + } + renamed := rewriteParkedCheckpoint(t, store, alphaResultType, movedFromType) + asAlpha := decoderFor("done", durable.DecodeAs[alpha.Result]) + + rh, err := durable.Recover(ctx, m, renamed, "scn-1", reg, asAlpha, every) + if err != nil { + t.Fatalf("Recover without the alias: %v", err) + } + _, ran, err = rh.RunService(ctx, id) + mustPark(t, "RunService without the alias", ran, err) + if !strings.Contains(err.Error(), movedFromType) { + t.Fatalf("RunService without the alias: %v, want it to name the recorded type %s", err, movedFromType) + } + if got := atomic.LoadInt64(runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } + + rh, err = durable.Recover(ctx, m, renamed, "scn-1", reg, asAlpha, alphaAlias(), every) + if err != nil { + t.Fatalf("Recover with the alias: %v", err) + } + if _, _, err = rh.RunService(ctx, id); err != nil { + t.Fatalf("RunService with the alias: %v", err) + } + if got := rh.Instance().Current(); got != "ready" { + t.Fatalf("in %q, want ready", got) + } + if got := atomic.LoadInt64(runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } + if a.done != 1 || describe(a.seen[0]) != describe(alpha.Result{ID: 7, Name: "ann"}) { + t.Fatalf("onDone's Assign ran %d times and saw %v, want once with the alpha.Result", a.done, a.seen) + } +} + +// TestResultTypeAlias_OnlyTheAliasedName: an alias for one old name admits only the +// type it names. A decoder for another type, whose JSON is the result's, is refused; +// so is a decoder for the aliased type when the alias covers a different old name. +func TestResultTypeAlias_OnlyTheAliasedName(t *testing.T) { + ctx := context.Background() + m, a, reg, store := renamedSettled(t) + for _, wrong := range []struct { + name string + opts []durable.Option[string, string, svcCtx] + }{ + {"another type under the aliased name", []durable.Option[string, string, svcCtx]{ + decoderFor("done", durable.DecodeAs[beta.Result]), alphaAlias(), + }}, + {"the aliased type under an alias for another name", []durable.Option[string, string, svcCtx]{ + decoderFor("done", durable.DecodeAs[alpha.Result]), + durable.WithResultTypeAlias[string, string, svcCtx]("example.com/gone/model.Old", alpha.Result{}), + }}, + } { + done := a.done + _, err := durable.Recover(ctx, m, store, "scn-1", append([]durable.Option[string, string, svcCtx]{reg}, wrong.opts...)...) + if !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Recover with %s: %v, want ErrEventDataEncoding", wrong.name, err) + } + if a.done != done || a.fails != 0 { + t.Fatalf("Recover with %s ran an Assign: onDone %d (was %d), onError %d", wrong.name, a.done, done, a.fails) + } + } +} + +// TestResultTypeAlias_BadInputIgnored: bad input changes nothing, as the other Runner +// options: an empty recorded name, a nil current value, a name aliased to the type's +// own current name, and one recorded name given for two different types, where the +// first stands and the repeat is ignored. The strict check stands for each, exactly as +// with no option at all, and the same alias twice is the one alias. +func TestResultTypeAlias_BadInputIgnored(t *testing.T) { + ctx := context.Background() + for _, tc := range []struct { + name string + opts []durable.Option[string, string, svcCtx] + settles bool + }{ + {"an empty recorded name", []durable.Option[string, string, svcCtx]{ + durable.WithResultTypeAlias[string, string, svcCtx]("", alpha.Result{}), + }, false}, + {"a nil current value", []durable.Option[string, string, svcCtx]{ + durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, nil), + }, false}, + {"a name aliased to the type's own current name", []durable.Option[string, string, svcCtx]{ + durable.WithResultTypeAlias[string, string, svcCtx](alphaResultType, alpha.Result{}), + }, false}, + {"another type after the alias for a name", []durable.Option[string, string, svcCtx]{ + durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}), + durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, beta.Result{}), + }, true}, + {"the alias after another type for a name", []durable.Option[string, string, svcCtx]{ + durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, beta.Result{}), + durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}), + }, false}, + {"the same alias twice", []durable.Option[string, string, svcCtx]{ + durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}), + durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}), + }, true}, + } { + t.Run(tc.name, func(t *testing.T) { + m, a, reg, store := renamedSettled(t) + opts := append([]durable.Option[string, string, svcCtx]{reg, decoderFor("done", durable.DecodeAs[alpha.Result])}, tc.opts...) + _, err := durable.Recover(ctx, m, store, "scn-1", opts...) + if tc.settles { + if err != nil { + t.Fatalf("Recover: %v, want the first alias to stand", err) + } + if got := len(a.seen); got != 2 { + t.Fatalf("onDone's Assign ran %d times, want live and replay", got) + } + if describe(a.seen[1]) != describe(alpha.Result{ID: 7, Name: "ann"}) { + t.Fatalf("replay saw %v, want the alpha.Result", a.seen) + } + return + } + if !errors.Is(err, durable.ErrEventDataEncoding) { + t.Fatalf("Recover: %v, want the ignored input to leave the strict check standing", err) + } + if a.done != 1 || a.fails != 0 { + t.Fatalf("replay ran an Assign: onDone %d, onError %d", a.done, a.fails) + } + }) + } +} + +// TestResultTypeAlias_KeepsTheHandleParkedResultItsType: the alias applies to a +// recorded result's name, not to the type a result parked by the Handle itself is +// held to: a Handle whose alias claims the parked type's name for another type still +// refuses a decoder that returns it, as live, and the result stays parked. +func TestResultTypeAlias_KeepsTheHandleParkedResultItsType(t *testing.T) { + ctx := context.Background() + runs := new(int64) + fn := func(context.Context, state.ServiceCtx[svcCtx]) (any, error) { + atomic.AddInt64(runs, 1) + return alpha.Result{ID: 7, Name: "ann"}, nil + } + a := &scnAssigns{} + m := scnMachine(fn, a) + reg := durable.WithServiceRegistry[string, string, svcCtx](fetchRegistry(fn)) + store := durable.NewMemStore() + // The decoder refuses the result once, so it parks, then decodes it as + // beta.Result, whose JSON is alpha's: only the type the Handle holds with the + // park keeps that from settling through the alias. + var calls int64 + flip := decoderFor("done", func(data []byte) (any, error) { + if atomic.AddInt64(&calls, 1) == 1 { + return nil, errors.New("decoder refused") + } + return durable.DecodeAs[beta.Result](data) + }) + claim := durable.WithResultTypeAlias[string, string, svcCtx](alphaResultType, beta.Result{}) + h := scnStart(t, m, store, reg, flip, claim) + id := state.InvokeID(scnInvoke, "loading", 0) + _, ran, err := h.RunService(ctx, id) + mustPark(t, "RunService", ran, err) + _, ran, err = h.RunService(ctx, id) + mustPark(t, "RunService settling the parked result", ran, err) + if got := atomic.LoadInt64(runs); got != 1 { + t.Fatalf("the ServiceFn ran %d times, want 1", got) + } + if a.done != 0 || a.fails != 0 { + t.Fatalf("an Assign ran: onDone %d, onError %d", a.done, a.fails) + } +} diff --git a/durable/runner.go b/durable/runner.go index 99387387..0f8bb6c1 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -733,7 +733,7 @@ func (r *Runner[S, E, C]) newServiceRunner(inst *state.Instance[S, E, C]) (*stat return nil, nil } settled := &settledJSON{} - return state.NewServiceRunner(inst, r.cfg.serviceReg).WithResultTransform(replayableOutcome(r.cfg.eventDataDecoder, settled)), settled + return state.NewServiceRunner(inst, r.cfg.serviceReg).WithResultTransform(replayableOutcome(r.cfg.eventDataDecoder, r.cfg.resultAliases, settled)), settled } // newActorSystem builds the kernel host driver for child-machine actors bound to diff --git a/durable/runner_options.go b/durable/runner_options.go index 8ca3e835..f26610ab 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -28,6 +28,12 @@ type runnerConfig[S comparable, E comparable, C any] struct { // eventDataDecoder rebuilds a recorded WithEventData payload; it defaults to // DecodeAs[any]. eventDataDecoder EventDataDecoder[E] + // resultAliases maps a recorded service result's Go type name, as typeName gives + // it, to the full name of the type that name now means, so a result settled or + // parked under a name a refactor moved or renamed still replays. It is nil by + // default: every recorded name is held to strictly, exactly as recorded. + // WithResultTypeAlias fills it. + resultAliases map[string]string // clock is the real time seam wrapped by the recording clock on the live path // and replaced by the replay clock on recovery. It defaults to // state.SystemClock(); a test supplies a deterministic fake. @@ -197,8 +203,9 @@ func WithMaxEventDataBytes[S comparable, E comparable, C any](n int) Option[S, E // then call RunService, to settle the parked result without running the service again; // the Handle that parked it never sees the fix (see Handle.RunService). The settling // decoder must return the type the service returned, by import path and name, or JSON's -// generic form, so a type moved or renamed after the park settles only through a decoder -// that returns the generic form. A service error stays message-only and +// generic form, so a type moved or renamed after the park or a settle settles only +// through WithResultTypeAlias or a decoder that returns the generic form. A service +// error stays message-only and // doesn't reach the decoder. Register the decoder before results are recorded: replay // decodes the journal with the recovering Runner's decoder, so one added or changed // after results were recorded changes what replay produces, and one that can't decode @@ -211,6 +218,42 @@ func WithEventDataDecoder[S comparable, E comparable, C any](d EventDataDecoder[ } } +// WithResultTypeAlias tells the Runner that a service result type the journal recorded +// under the full Go type name recorded now goes by current's type, so a result settled +// or parked under the old name still replays after the rename: Recover, StateAt and a +// RunService that settles a recorded result accept the decoded value when its type is +// the one current is a value of, and every other recorded name is held to strictly, +// exactly as without the alias. recorded is the name as the journal records it — the +// same form the result's Go type gives, an import path and name, as +// "example.com/app/model.Result" — and current is a value of the type the name now +// means, matched by its own full name. A rename is one hop: the alias maps the recorded +// name directly to current's type and never chains through another alias. The option +// can be repeated, for several renames and for the same rename twice; a recorded name +// given for two different types is ignored, as are an empty recorded, a nil current and +// a name aliased to the type's own current name — as the other options, bad input +// changes nothing, and the strict check stands, so a result recorded under a name no +// alias covers still fails Recover and StateAt with ErrEventDataEncoding. The alias +// applies to a recorded result's name only: a result parked by this Handle stays held +// to its own type, exactly as live (see WithEventDataDecoder). +func WithResultTypeAlias[S comparable, E comparable, C any](recorded string, current any) Option[S, E, C] { + return func(c *runnerConfig[S, E, C]) { + var currentName string + if current != nil { + currentName = typeName(current) + } + if recorded == "" || current == nil || recorded == currentName { + return + } + if prev, ok := c.resultAliases[recorded]; ok && prev != currentName { + return + } + if c.resultAliases == nil { + c.resultAliases = map[string]string{} + } + c.resultAliases[recorded] = currentName + } +} + // 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 diff --git a/durable/service.go b/durable/service.go index 94d6f732..b83a615b 100644 --- a/durable/service.go +++ b/durable/service.go @@ -379,7 +379,12 @@ func (h *Handle[S, E, C]) markSettled(id string) { // An error becomes an error with its message as a Store keeps it (see // normalizedErrorMessage), live and on replay. An Error method that panics settles // with a message saying so, normalized the same way. -func replayableOutcome[E comparable](decode EventDataDecoder[E], settled *settledJSON) func(E, any, error) (any, error, error) { +// +// aliases carries the Runner's WithResultTypeAlias renames, which the recorded check +// honors: a result recorded under a name an alias maps to the type the decoded value +// has settles through the alias. Every other name is checked strictly, as without any +// alias. +func replayableOutcome[E comparable](decode EventDataDecoder[E], aliases map[string]string, settled *settledJSON) func(E, any, error) (any, error, error) { return func(event E, result any, err error) (any, error, error) { settled.set(recordedResult{}) if err != nil { @@ -410,7 +415,7 @@ func replayableOutcome[E comparable](decode EventDataDecoder[E], settled *settle } else if !replay { derr = decodedAsPassed(value, result, "service result", true) } else { - derr = decodedAsRecorded(value, recorded) + derr = decodedAsRecorded(value, recorded, aliases) } if derr != nil { rtype := recorded.rtype @@ -636,16 +641,20 @@ func qualifiedName(pkg, name string) string { // decodedAsRecorded is decodedAsPassed for a recorded result, which records its type's // name rather than a value: it reports, as an ErrEventDataEncoding error, a value the // decoder returned as another type than the recorded one. As live, nil and JSON's -// generic form are always accepted. A result this Handle parked keeps its type, and is -// held to it as live held it; one read from the journal or a checkpoint is held to its -// name, which a type of the same name and package, such as another function-local type, -// also has. An empty name, a result recorded with no type, accepts anything. -func decodedAsRecorded(value any, recorded recordedResult) error { +// generic form are always accepted. A name aliases maps, from WithResultTypeAlias, to +// the type the decoded value has is accepted too: the type was renamed or moved after +// the result was recorded, and the alias says what the recorded name now means; every +// other name is checked strictly, as without any alias. A result this Handle parked +// keeps its type, and is held to it as live held it; one read from the journal or a +// checkpoint is held to its name, which a type of the same name and package, such as +// another function-local type, also has. An empty name, a result recorded with no +// type, accepts anything. +func decodedAsRecorded(value any, recorded recordedResult, aliases map[string]string) error { typ := recorded.typ if typ == "" || value == nil || genericJSON(value) { return nil } - if got := typeName(value); got != typ { + if got := typeName(value); got != typ && got != aliases[typ] { return fmt.Errorf("%w: a %s service result decodes as %s; decode it as %s with WithEventDataDecoder", ErrEventDataEncoding, typ, got, typ) } diff --git a/durable/service_encode_internal_test.go b/durable/service_encode_internal_test.go index e433bbce..95116723 100644 --- a/durable/service_encode_internal_test.go +++ b/durable/service_encode_internal_test.go @@ -43,7 +43,7 @@ func TestServiceResult_JournalBytesAreWhatLiveDecoded(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { settled := &settledJSON{} - value, outErr, abort := replayableOutcome(tc.decode, settled)("done", tc.result, nil) + value, outErr, abort := replayableOutcome(tc.decode, nil, settled)("done", tc.result, nil) if outErr != nil || abort != nil { t.Fatalf("the transform returned %v, %v", outErr, abort) } @@ -66,7 +66,7 @@ func TestServiceResult_JournalBytesAreWhatLiveDecoded(t *testing.T) { t.Fatalf("decoded value's encoding %s, journal %s: same = %v, want %v", reencoded, sp.Result, same, tc.reencode) } // Replay decodes the journal to the value live saw. - replayed, _, rabort := replayableOutcome(tc.decode, nil)("done", recordedResult{raw: sp.Result}, nil) + replayed, _, rabort := replayableOutcome(tc.decode, nil, nil)("done", recordedResult{raw: sp.Result}, nil) if rabort != nil { t.Fatalf("replaying %s: %v", sp.Result, rabort) } diff --git a/durable/settle_absorb_internal_test.go b/durable/settle_absorb_internal_test.go index ab3ee44f..e1c9e528 100644 --- a/durable/settle_absorb_internal_test.go +++ b/durable/settle_absorb_internal_test.go @@ -170,7 +170,7 @@ func TestUndecodableResult_WrapsErrEventDataEncodingOnlyForADecodeFailure(t *tes {"won't encode", make(chan int), false, false}, } { t.Run(tc.name, func(t *testing.T) { - _, _, abort := replayableOutcome[string](refuse, &settledJSON{})("done", tc.result, nil) + _, _, abort := replayableOutcome[string](refuse, nil, &settledJSON{})("done", tc.result, nil) var derr *undecodableResult if !errors.As(abort, &derr) { t.Fatalf("abort = %v, want an *undecodableResult", abort) diff --git a/durable/timetravel.go b/durable/timetravel.go index 1c3b6a4b..6c6b9e67 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -305,5 +305,5 @@ func newReplayServiceRunner[S comparable, E comparable, C any]( if cfg.serviceReg == nil { return nil } - return state.NewServiceRunner(inst, cfg.serviceReg).WithResultTransform(replayableOutcome(cfg.eventDataDecoder, nil)) + return state.NewServiceRunner(inst, cfg.serviceReg).WithResultTransform(replayableOutcome(cfg.eventDataDecoder, cfg.resultAliases, nil)) } From 106d98dbe285380df0f85b070466e79ee19f2ee6 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Fri, 20 Nov 2026 16:50:24 -0700 Subject: [PATCH 4/4] fix(durable): drop a conflicting WithResultTypeAlias and name the alias in refusals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A recorded name WithResultTypeAlias claimed for two different types now drops that name's alias entirely, instead of the first registration standing: whichever order the two arrive in, and a later registration, for any type, can't bring it back, so the strict check stands for that name, as with no option at all. An empty recorded name, a nil current value, a name aliased to its own current type, and an idempotent repeat of one rename behave as before. A refusal now says which type to decode as. When an alias covers the recorded name, the message names the recorded type and the aliased type and says to decode as the aliased one; when the name agrees and the value could only be another type a parked result carries, the message says the result is held to the type this Handle parked, and says "another type of the same name" only when the names really are the same. The option's doc spells the recorded name the way the journal records it — a leading * for pointers, type arguments for generics — and points at the refusal, which prints the exact recorded name to copy. Signed-off-by: Ray Karnes --- durable/CHANGELOG.md | 11 ++++--- durable/result_alias_test.go | 64 ++++++++++++++++++++++++++++-------- durable/runner_options.go | 37 ++++++++++++++++----- durable/service.go | 31 ++++++++++++----- 4 files changed, 109 insertions(+), 34 deletions(-) diff --git a/durable/CHANGELOG.md b/durable/CHANGELOG.md index 908738c4..298a7b45 100644 --- a/durable/CHANGELOG.md +++ b/durable/CHANGELOG.md @@ -17,10 +17,13 @@ and this module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. name is held to strictly, exactly as before. A parked result the Handle itself holds is still held to its own type, as live. The option takes the recorded name and a value of the type the name now means, can be repeated for several renames, and maps - one hop, never chaining through another alias. Bad input — an empty recorded name, a - nil value, a name aliased to the type's own current name, or one recorded name for - two different types — is ignored, like the other Runner options, leaving the strict - check in place. + one hop, never chaining through another alias. One recorded name given for two + different types drops that name's alias entirely, whichever order the registrations + arrive in, and a later registration, for any type, can't revive it, so the strict + check stands for that name; an empty recorded name, a nil value or a name aliased to + the type's own current name is ignored, like the other Runner options, leaving the + strict check in place. A refusal names the recorded type and, when an alias covers + the name, the aliased type to decode as. - **`Record.EndedActors` and `ActorSet`** record the declared child-machine actors that ran and have ended, settled or stopped, so `Recover` doesn't spawn them again. A Store must keep an empty set distinct from nil. diff --git a/durable/result_alias_test.go b/durable/result_alias_test.go index 75496203..74417769 100644 --- a/durable/result_alias_test.go +++ b/durable/result_alias_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "reflect" "strings" "sync/atomic" "testing" @@ -26,6 +27,12 @@ func alphaAlias() durable.Option[string, string, svcCtx] { return durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}) } +// betaAlias is the option mapping the same recorded name to beta.Result, which with +// alphaAlias claims one name for two types. +func betaAlias() durable.Option[string, string, svcCtx] { + return durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, beta.Result{}) +} + // settledAlpha settles an alpha.Result for scn-1 live, under a decoder for it, and // returns what Recover and StateAt need. func settledAlpha(t *testing.T) (*state.Machine[string, string, svcCtx], *scnAssigns, durable.Option[string, string, svcCtx], *durable.MemStore) { @@ -279,28 +286,37 @@ func TestResultTypeAlias_RenamedParkedResultThroughCheckpoint(t *testing.T) { } // TestResultTypeAlias_OnlyTheAliasedName: an alias for one old name admits only the -// type it names. A decoder for another type, whose JSON is the result's, is refused; -// so is a decoder for the aliased type when the alias covers a different old name. +// type it names. A decoder for another type, whose JSON is the result's, is refused +// with a message naming both the recorded type and the aliased type, and saying to +// decode as the aliased one; so is a decoder for the aliased type when the alias +// covers a different old name. func TestResultTypeAlias_OnlyTheAliasedName(t *testing.T) { ctx := context.Background() m, a, reg, store := renamedSettled(t) + betaType := typeNameOf(t, beta.Result{}) for _, wrong := range []struct { name string opts []durable.Option[string, string, svcCtx] + want string }{ {"another type under the aliased name", []durable.Option[string, string, svcCtx]{ decoderFor("done", durable.DecodeAs[beta.Result]), alphaAlias(), - }}, + }, "a " + movedFromType + " service result, aliased to " + alphaResultType + + " by WithResultTypeAlias, decodes as " + betaType + "; decode it as " + alphaResultType + " with WithEventDataDecoder"}, {"the aliased type under an alias for another name", []durable.Option[string, string, svcCtx]{ decoderFor("done", durable.DecodeAs[alpha.Result]), durable.WithResultTypeAlias[string, string, svcCtx]("example.com/gone/model.Old", alpha.Result{}), - }}, + }, "a " + movedFromType + " service result decodes as " + alphaResultType + + "; decode it as " + movedFromType + " with WithEventDataDecoder"}, } { done := a.done _, err := durable.Recover(ctx, m, store, "scn-1", append([]durable.Option[string, string, svcCtx]{reg}, wrong.opts...)...) if !errors.Is(err, durable.ErrEventDataEncoding) { t.Fatalf("Recover with %s: %v, want ErrEventDataEncoding", wrong.name, err) } + if !strings.Contains(err.Error(), wrong.want) { + t.Fatalf("Recover with %s: %q, want it to contain %q", wrong.name, err, wrong.want) + } if a.done != done || a.fails != 0 { t.Fatalf("Recover with %s ran an Assign: onDone %d (was %d), onError %d", wrong.name, a.done, done, a.fails) } @@ -309,8 +325,9 @@ func TestResultTypeAlias_OnlyTheAliasedName(t *testing.T) { // TestResultTypeAlias_BadInputIgnored: bad input changes nothing, as the other Runner // options: an empty recorded name, a nil current value, a name aliased to the type's -// own current name, and one recorded name given for two different types, where the -// first stands and the repeat is ignored. The strict check stands for each, exactly as +// own current name, and one recorded name given for two different types, which drops +// the alias for that name, whichever order the two arrive in — a third registration, +// for any type, can't bring it back. The strict check stands for each, exactly as // with no option at all, and the same alias twice is the one alias. func TestResultTypeAlias_BadInputIgnored(t *testing.T) { ctx := context.Background() @@ -329,16 +346,16 @@ func TestResultTypeAlias_BadInputIgnored(t *testing.T) { durable.WithResultTypeAlias[string, string, svcCtx](alphaResultType, alpha.Result{}), }, false}, {"another type after the alias for a name", []durable.Option[string, string, svcCtx]{ - durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}), - durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, beta.Result{}), - }, true}, + alphaAlias(), betaAlias(), + }, false}, {"the alias after another type for a name", []durable.Option[string, string, svcCtx]{ - durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, beta.Result{}), - durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}), + betaAlias(), alphaAlias(), + }, false}, + {"a third registration after a conflict", []durable.Option[string, string, svcCtx]{ + alphaAlias(), betaAlias(), alphaAlias(), }, false}, {"the same alias twice", []durable.Option[string, string, svcCtx]{ - durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}), - durable.WithResultTypeAlias[string, string, svcCtx](movedFromType, alpha.Result{}), + alphaAlias(), alphaAlias(), }, true}, } { t.Run(tc.name, func(t *testing.T) { @@ -347,7 +364,7 @@ func TestResultTypeAlias_BadInputIgnored(t *testing.T) { _, err := durable.Recover(ctx, m, store, "scn-1", opts...) if tc.settles { if err != nil { - t.Fatalf("Recover: %v, want the first alias to stand", err) + t.Fatalf("Recover: %v, want the alias to stand", err) } if got := len(a.seen); got != 2 { t.Fatalf("onDone's Assign ran %d times, want live and replay", got) @@ -399,6 +416,13 @@ func TestResultTypeAlias_KeepsTheHandleParkedResultItsType(t *testing.T) { mustPark(t, "RunService", ran, err) _, ran, err = h.RunService(ctx, id) mustPark(t, "RunService settling the parked result", ran, err) + // The refusal names the recorded type and the type the decoder returned, and says + // the result is held to the type the Handle parked, not the alias. + want := "a " + alphaResultType + " service result decodes as " + typeNameOf(t, beta.Result{}) + + "; the result is held to the type this Handle parked, not the alias, so decode it as the service's own type with WithEventDataDecoder" + if !strings.Contains(err.Error(), want) { + t.Fatalf("RunService settling the parked result: %q, want it to contain %q", err, want) + } if got := atomic.LoadInt64(runs); got != 1 { t.Fatalf("the ServiceFn ran %d times, want 1", got) } @@ -406,3 +430,15 @@ func TestResultTypeAlias_KeepsTheHandleParkedResultItsType(t *testing.T) { t.Fatalf("an Assign ran: onDone %d, onError %d", a.done, a.fails) } } + +// typeNameOf spells v's type the way the journal records it, with the import path in +// place of the package name, as the refusal messages and the alias option do. +func typeNameOf(t *testing.T, v any) string { + t.Helper() + typ := reflect.TypeOf(v) + name := typ.Name() + if pkg := typ.PkgPath(); pkg != "" { + name = pkg + "." + name + } + return name +} diff --git a/durable/runner_options.go b/durable/runner_options.go index f26610ab..fa8abed2 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -34,6 +34,12 @@ type runnerConfig[S comparable, E comparable, C any] struct { // default: every recorded name is held to strictly, exactly as recorded. // WithResultTypeAlias fills it. resultAliases map[string]string + // resultAliasConflicts holds the recorded names WithResultTypeAlias has been + // given for two different types, which drop the alias for that name entirely: + // the strict check stands for them, and a later registration, for any type, + // can't bring the alias back. It is nil by default; WithResultTypeAlias fills + // it. + resultAliasConflicts map[string]bool // clock is the real time seam wrapped by the recording clock on the live path // and replaced by the replay clock on recovery. It defaults to // state.SystemClock(); a test supplies a deterministic fake. @@ -223,14 +229,19 @@ func WithEventDataDecoder[S comparable, E comparable, C any](d EventDataDecoder[ // or parked under the old name still replays after the rename: Recover, StateAt and a // RunService that settles a recorded result accept the decoded value when its type is // the one current is a value of, and every other recorded name is held to strictly, -// exactly as without the alias. recorded is the name as the journal records it — the -// same form the result's Go type gives, an import path and name, as -// "example.com/app/model.Result" — and current is a value of the type the name now -// means, matched by its own full name. A rename is one hop: the alias maps the recorded -// name directly to current's type and never chains through another alias. The option -// can be repeated, for several renames and for the same rename twice; a recorded name -// given for two different types is ignored, as are an empty recorded, a nil current and -// a name aliased to the type's own current name — as the other options, bad input +// exactly as without the alias. recorded is the name as the journal records it, spelled +// exactly as the result's Go type does: an import path and name, as +// "example.com/app/model.Result", a pointer with a leading *, as +// "*example.com/app/model.Result", and a generic instantiation with its type +// arguments, as "example.com/app/pair.Pair[int]"; a refusal under ErrEventDataEncoding +// prints the exact recorded name, to copy into recorded. current is a value of the +// type the name now means, matched by its own full name. A rename is one hop: the +// alias maps the recorded name directly to current's type and never chains through +// another alias. The option can be repeated, for several renames and for the same +// rename twice; a recorded name given for two different types drops the alias for +// that name, whichever order the two arrive in, and a later registration, for any +// type, can't bring it back. An empty recorded, a nil current and a name aliased to +// the type's own current name are ignored too — as the other options, bad input // changes nothing, and the strict check stands, so a result recorded under a name no // alias covers still fails Recover and StateAt with ErrEventDataEncoding. The alias // applies to a recorded result's name only: a result parked by this Handle stays held @@ -244,7 +255,17 @@ func WithResultTypeAlias[S comparable, E comparable, C any](recorded string, cur if recorded == "" || current == nil || recorded == currentName { return } + // A name two types have claimed is void: drop the alias, and keep the name + // conflicted so no later registration, for any type, brings it back. + if c.resultAliasConflicts[recorded] { + return + } if prev, ok := c.resultAliases[recorded]; ok && prev != currentName { + delete(c.resultAliases, recorded) + if c.resultAliasConflicts == nil { + c.resultAliasConflicts = map[string]bool{} + } + c.resultAliasConflicts[recorded] = true return } if c.resultAliases == nil { diff --git a/durable/service.go b/durable/service.go index b83a615b..ca48f8a3 100644 --- a/durable/service.go +++ b/durable/service.go @@ -644,8 +644,10 @@ func qualifiedName(pkg, name string) string { // generic form are always accepted. A name aliases maps, from WithResultTypeAlias, to // the type the decoded value has is accepted too: the type was renamed or moved after // the result was recorded, and the alias says what the recorded name now means; every -// other name is checked strictly, as without any alias. A result this Handle parked -// keeps its type, and is held to it as live held it; one read from the journal or a +// other name is checked strictly, as without any alias. A refusal names the recorded +// type, and, when an alias covers the name, the aliased type to decode as. A result +// this Handle parked keeps its type, and is held to it as live held it — through an +// alias too, which a parked result ignores — or as one read from the journal or a // checkpoint is held to its name, which a type of the same name and package, such as // another function-local type, also has. An empty name, a result recorded with no // type, accepts anything. @@ -654,16 +656,29 @@ func decodedAsRecorded(value any, recorded recordedResult, aliases map[string]st if typ == "" || value == nil || genericJSON(value) { return nil } - if got := typeName(value); got != typ && got != aliases[typ] { + got := typeName(value) + alias, aliased := aliases[typ] + if got != typ && (!aliased || got != alias) { + if aliased { + // The name is covered by an alias, so name the type it now means, which is + // the one to decode as, not the recorded name the type no longer has. + return fmt.Errorf("%w: a %s service result, aliased to %s by WithResultTypeAlias, decodes as %s; decode it as %s with WithEventDataDecoder", + ErrEventDataEncoding, typ, alias, got, alias) + } return fmt.Errorf("%w: a %s service result decodes as %s; decode it as %s with WithEventDataDecoder", ErrEventDataEncoding, typ, got, typ) } - // The names agree, so only a result this Handle parked, which carries its type - // itself, can be another type: one of the same name and package, such as another - // function-local type. + // The name agrees — the recorded one or the alias's — so only a result this Handle + // parked, which carries its type itself, can be another type: through the alias, + // one the Handle never parked, or one of the same name and package, such as + // another function-local type. if recorded.rtype != nil && reflect.TypeOf(value) != recorded.rtype { - return fmt.Errorf("%w: a %s service result decodes as another type of the same name; decode it as the service's own type with WithEventDataDecoder", - ErrEventDataEncoding, typ) + if got == typ { + return fmt.Errorf("%w: a %s service result decodes as another type of the same name; decode it as the service's own type with WithEventDataDecoder", + ErrEventDataEncoding, typ) + } + return fmt.Errorf("%w: a %s service result decodes as %s; the result is held to the type this Handle parked, not the alias, so decode it as the service's own type with WithEventDataDecoder", + ErrEventDataEncoding, typ, got) } return nil }