diff --git a/durable/actor.go b/durable/actor.go index 8a49fc0..8ee0ba6 100644 --- a/durable/actor.go +++ b/durable/actor.go @@ -353,8 +353,10 @@ func splitActorEntries(rec *Record) (before, rest []decodedActorEntry, err error // the recorded entry cannot be decoded or the re-fired transition fails (a corrupt or // mis-ordered journal), or the recorded done-data won't decode for its event, as the // live settle refused it. aliases carries the Runner's WithResultTypeAlias renames, -// which the recorded check honors, as a recorded service result's replay does. -func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], decode EventDataDecoder[E], aliases map[string]string, entry decodedActorEntry) ([]state.Effect, error) { +// which the recorded check honors, as a recorded service result's replay does. names +// is the Runner's cache the recorded type check spells through; the Runner-less +// StateAt passes nil and spells uncached (see typeNames). +func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *state.Instance[S, E, C], codec EventCodec[E], decode EventDataDecoder[E], aliases map[string]string, names *typeNames, entry decodedActorEntry) ([]state.Effect, error) { mp := entry.mp // A Fire refused before the kernel saw it (middleware that denied it) has no event // to re-fire; replay is refused the same way. @@ -367,7 +369,7 @@ func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *s } var res state.FireResult[S] if mp.HasData && !mp.Refused { - data, derr := replayActorData(mp, event, decode, aliases) + data, derr := replayActorData(mp, event, decode, aliases, names) if derr != nil { return nil, fmt.Errorf("durable: decoding recorded actor %q done-data: %w", entry.actorID, derr) } @@ -403,8 +405,9 @@ func replayActor[S comparable, E comparable, C any](ctx context.Context, inst *s // service result is; one that won't decode fails the replay, as the live settle // refused it. A payload that fails to decode is surfaced as an error rather than // silently dropped, so a corrupt journal fails replay loudly instead of re-firing the -// parent with nil data it never saw on the live path. -func replayActorData[E comparable](mp actorMessagePayload, event E, decode EventDataDecoder[E], aliases map[string]string) (any, error) { +// parent with nil data it never saw on the live path. names is the Runner's cache +// the recorded type check spells through; nil spells uncached (see typeNames). +func replayActorData[E comparable](mp actorMessagePayload, event E, decode EventDataDecoder[E], aliases map[string]string, names *typeNames) (any, error) { if mp.Error != nil { return errors.New(*mp.Error), nil } @@ -413,7 +416,7 @@ func replayActorData[E comparable](mp actorMessagePayload, event E, decode Event } // The transform decodes the recorded JSON for the onDone event, as it did live, // and holds the decoder to the recorded type. An abort is the decode's refusal. - out, _, abort := replayableOutcome(decode, aliases, nil, "actor done-data", "actor error")(event, recordedResult{raw: mp.Data, typ: mp.Type}, nil) + out, _, abort := replayableOutcome(decode, aliases, names, nil, "actor done-data", "actor error")(event, recordedResult{raw: mp.Data, typ: mp.Type}, nil) if abort != nil { return nil, abort } diff --git a/durable/actor_internal_test.go b/durable/actor_internal_test.go index 710033c..5993e71 100644 --- a/durable/actor_internal_test.go +++ b/durable/actor_internal_test.go @@ -14,7 +14,7 @@ func TestReplayActorData(t *testing.T) { errMsg := "boom" t.Run("error", func(t *testing.T) { - got, err := replayActorData(actorMessagePayload{Error: &errMsg}, "childDone", decodeAny[string], nil) + got, err := replayActorData(actorMessagePayload{Error: &errMsg}, "childDone", decodeAny[string], nil, cacheRunner().names) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -25,7 +25,7 @@ func TestReplayActorData(t *testing.T) { }) t.Run("valid data", func(t *testing.T) { - got, err := replayActorData(actorMessagePayload{Data: json.RawMessage(`{"k":1}`)}, "childDone", decodeAny[string], nil) + got, err := replayActorData(actorMessagePayload{Data: json.RawMessage(`{"k":1}`)}, "childDone", decodeAny[string], nil, cacheRunner().names) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -36,7 +36,7 @@ func TestReplayActorData(t *testing.T) { }) t.Run("no data", func(t *testing.T) { - got, err := replayActorData(actorMessagePayload{}, "childDone", decodeAny[string], nil) + got, err := replayActorData(actorMessagePayload{}, "childDone", decodeAny[string], nil, cacheRunner().names) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -46,7 +46,7 @@ func TestReplayActorData(t *testing.T) { }) t.Run("corrupt data surfaces error", func(t *testing.T) { - got, err := replayActorData(actorMessagePayload{Data: json.RawMessage(`{not json`), Type: "int"}, "childDone", decodeAny[string], nil) + got, err := replayActorData(actorMessagePayload{Data: json.RawMessage(`{not json`), Type: "int"}, "childDone", decodeAny[string], nil, cacheRunner().names) if err == nil { t.Fatal("want an error for undecodable done-data, got nil") } diff --git a/durable/runner.go b/durable/runner.go index cf6ac60..d115227 100644 --- a/durable/runner.go +++ b/durable/runner.go @@ -64,17 +64,25 @@ type Runner[S comparable, E comparable, C any] struct { machine *state.Machine[S, E, C] store Store cfg runnerConfig[S, E, C] + // names is this Runner's cache of each result type's full spelling (see + // typeNames): every settle, park and replay type check a Handle of this Runner + // asks — Start and Recover included — spells through it, and two Runners share + // no entry. It is unexported state, built by NewRunner. + names *typeNames } // NewRunner binds a machine and a Store into a durable Runner. Behavior is tuned // with functional options — the checkpoint policy (WithCheckpointEvery) and the // event codec (WithEventCodec) — each additive and defaulting to a working -// baseline (no periodic checkpoint, JSON event encoding). +// baseline (no periodic checkpoint, JSON event encoding). Each Runner owns its own +// cache of result types' full spellings (see typeNames), so no two Runners share +// state. func NewRunner[S comparable, E comparable, C any](m *state.Machine[S, E, C], st Store, opts ...Option[S, E, C]) *Runner[S, E, C] { return &Runner[S, E, C]{ machine: m, store: st, cfg: resolveRunner(opts...), + names: newTypeNames(), } } @@ -758,7 +766,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, r.cfg.resultAliases, settled, "service result", "service error")), settled + return state.NewServiceRunner(inst, r.cfg.serviceReg).WithResultTransform(replayableOutcome(r.cfg.eventDataDecoder, r.cfg.resultAliases, r.names, settled, "service result", "service error")), settled } // newActorSystem builds the kernel host driver for child-machine actors bound to @@ -792,7 +800,7 @@ func (r *Runner[S, E, C]) newActorSystem(inst *state.Instance[S, E, C]) (*state. // to the settle still in flight — notes no abort and fails no Handle. WithSettleAbortObserver(func(sa state.SettleAbort[E]) { fires.aborted(sa.Abort) }) settleJSON := &settledJSON{} - outcome := replayableOutcome(r.cfg.eventDataDecoder, r.cfg.resultAliases, settleJSON, "actor done-data", "actor error") + outcome := replayableOutcome(r.cfg.eventDataDecoder, r.cfg.resultAliases, r.names, settleJSON, "actor done-data", "actor error") sys.WithSettleTransform(func(event E, output any, err error) (any, error, error) { out, outErr, abort := outcome(event, output, err) if abort == nil { @@ -2020,7 +2028,7 @@ func (r *Runner[S, E, C]) recover(ctx context.Context, id InstanceID) (*Handle[S 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)) + stepEffects, err := replayRecord(ctx, inst, &r.cfg, r.names, sched, svc, rec, mirror, armsActorFires(rec)) if err != nil { return nil, fmt.Errorf("durable: recovering %q: %w", id, err) } @@ -2495,6 +2503,7 @@ func replayRecord[S comparable, E comparable, C any]( ctx context.Context, inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], + names *typeNames, sched *state.Scheduler[S, E, C], svc *state.ServiceRunner[S, E, C], rec *Record, @@ -2509,7 +2518,7 @@ func replayRecord[S comparable, E comparable, C any]( // Parent Fires a Start's or Recover's spawns drove ran before the step's own work. // Their effects aren't returned: no live path dispatches them (see the // Start-spawned note above). - if _, err := replayActors(ctx, inst, cfg, sched, svc, rec, before, mirror, actorArms); err != nil { + if _, err := replayActors(ctx, inst, cfg, names, sched, svc, rec, before, mirror, actorArms); err != nil { return stepEffects, err } switch { @@ -2586,7 +2595,7 @@ func replayRecord[S comparable, E comparable, C any]( // drove after it, such as a spawned actor's onError. Their effects follow the // step's own, in fire order, as the live step named them, so Recover re-dispatches // a driven Fire's domain effects under the ids live stamped. - driven, derr := replayActors(ctx, inst, cfg, sched, svc, rec, rest, mirror, actorArms) + driven, derr := replayActors(ctx, inst, cfg, names, sched, svc, rec, rest, mirror, actorArms) if derr != nil { return stepEffects, derr } @@ -2599,11 +2608,14 @@ func replayRecord[S comparable, E comparable, C any]( // When actorArms, the version that wrote rec armed the timers and services an // actor-driven Fire declares, so each one arms them, as the live run did. An older // version armed none, and took no -// clock read for them, so they're left alone, as that run left them. +// clock read for them, so they're left alone, as that run left them. names is the +// Runner's cache the re-fired transitions' recorded type checks spell through; the +// Runner-less StateAt passes nil and spells uncached (see typeNames). func replayActors[S comparable, E comparable, C any]( ctx context.Context, inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], + names *typeNames, sched *state.Scheduler[S, E, C], svc *state.ServiceRunner[S, E, C], rec *Record, @@ -2613,7 +2625,7 @@ func replayActors[S comparable, E comparable, C any]( ) ([]state.Effect, error) { var driven []state.Effect for _, entry := range entries { - effects, err := replayActor(ctx, inst, cfg.eventCodec, cfg.eventDataDecoder, cfg.resultAliases, entry) + effects, err := replayActor(ctx, inst, cfg.eventCodec, cfg.eventDataDecoder, cfg.resultAliases, names, entry) if err != nil { return nil, fmt.Errorf("at step %d: %w", rec.Step, err) } diff --git a/durable/runner_options.go b/durable/runner_options.go index 655c73d..97f63da 100644 --- a/durable/runner_options.go +++ b/durable/runner_options.go @@ -263,7 +263,10 @@ func WithResultTypeAlias[S comparable, E comparable, C any](recorded string, cur return func(c *runnerConfig[S, E, C]) { var currentName string if current != nil { - currentName = typeName(current) + // The option runs before any Runner exists to own a cache, so the type is + // spelled uncached (see typeNames): the spelling is pure in the type alone, + // so it is the one the Runner's cache will return once built. + currentName = (*typeNames)(nil).typeName(current) } if recorded == "" || current == nil || recorded == currentName { return diff --git a/durable/service.go b/durable/service.go index d9c73fb..dea34d0 100644 --- a/durable/service.go +++ b/durable/service.go @@ -8,6 +8,8 @@ import ( "reflect" "strconv" "strings" + "sync" + "sync/atomic" "github.com/stablekernel/crucible/state" ) @@ -420,7 +422,10 @@ func (h *Handle[S, E, C]) markSettled(id string) { // honors: an outcome 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, what, errWhat string) func(E, any, error) (any, error, error) { +// names is the Runner's cache every spelling the transform asks goes through (see +// typeNames): a Runner-less caller passes nil and spells uncached, which changes +// nothing the transform returns. +func replayableOutcome[E comparable](decode EventDataDecoder[E], aliases map[string]string, names *typeNames, settled *settledJSON, what, errWhat string) func(E, any, error) (any, error, error) { return func(event E, result any, err error) (any, error, error) { settled.set(recordedResult{}) if err != nil { @@ -440,7 +445,7 @@ func replayableOutcome[E comparable](decode EventDataDecoder[E], aliases map[str } var value any var derr error - if typedNil(b, recorded, replay, result) { + if typedNil(names, 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 { @@ -451,16 +456,16 @@ func replayableOutcome[E comparable](decode EventDataDecoder[E], aliases map[str } else if !replay { derr = decodedAsPassed(value, result, what, true) } else { - derr = decodedAsRecorded(value, recorded, aliases, what) + derr = decodedAsRecorded(names, value, recorded, aliases, what) } 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} + return nil, nil, &undecodableResult{raw: b, typ: resultType(names, recorded, replay, result), rtype: rtype, err: derr} } - settled.set(recordedResult{raw: b, typ: resultType(recorded, replay, result)}) + settled.set(recordedResult{raw: b, typ: resultType(names, recorded, replay, result)}) return value, nil, nil } } @@ -468,12 +473,13 @@ func replayableOutcome[E comparable](decode EventDataDecoder[E], aliases map[str // 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 { +// names is the Runner's cache the recorded type's name was spelled through. +func typedNil(names *typeNames, 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 recorded.typ != "" && recorded.typ != names.typeName(nil) } return result != nil } @@ -502,12 +508,13 @@ func (s *settledJSON) take() recordedResult { } // 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 { +// the recorded one on replay, else the ServiceFn's value's. names is the Runner's +// cache the name is spelled through. +func resultType(names *typeNames, recorded recordedResult, replay bool, result any) string { if replay { return recorded.typ } - return typeName(result) + return names.typeName(result) } // recordedResult is a journaled service result's JSON, which replayService settles so @@ -527,23 +534,87 @@ type recordedResult struct { rtype reflect.Type } +// typeNames is the cache of each type's full spelling that a Runner owns: the +// package admits no package-level mutable state (CONTRIBUTING.md), so NewRunner +// builds one, and every spelling its settles, parks and replay type checks ask — +// Start and Recover included, across every Handle it hands out — goes through it. +// A nil *typeNames spells uncached: a caller with no Runner in reach — an option +// applied before the Runner exists, or the Runner-less StateAt — passes nil rather +// than reaching for shared state. The cache never changes a spelling, only who +// computes it: the spelling is pure in the type alone. +type typeNames struct { + // cache holds each type's full spelling keyed by the reflect.Type itself: two + // reflect.Types compare equal exactly when the types are identical, so a cached + // spelling is always the one its own type spells. It is bounded: without a cap, + // runtime-minted types - reflect.StructOf mints a new reflect.Type for every + // shape a caller asks - would grow it without end, so past the cap a type is + // spelled and returned unstored, and the hit path is what the cache exists for. + cache sync.Map // map[reflect.Type]string + + // limit is the cap fullTypeName enforces: typeNameCacheCap, which a test hook + // lowers on a cache that has spelled nothing yet. It is never written once the + // cache serves one, so the plain read races nothing. + limit int64 + + // n counts the cache's entries, so a load can check the cap without ranging the + // map. It is incremented only when a LoadOrStore stores, so the same type never + // counts twice. + n atomic.Int64 +} + +// newTypeNames returns a Runner's type-name cache, at the production cap. +func newTypeNames() *typeNames { return &typeNames{limit: typeNameCacheCap} } + +// limitForTest lowers the cache's cap, for the tests that exercise the bound. It +// writes only a cache that has spelled nothing yet, so the field needs no +// synchronization of its own; production caches never lower it. +func (n *typeNames) limitForTest(limit int64) { n.limit = limit } + // 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 { +// unnamed type spelled from those (see fullTypeName). The Runner that owns this +// cache gets its spellings cached; a nil one spells uncached. +func (n *typeNames) typeName(v any) string { t := reflect.TypeOf(v) if t == nil { return "" } - return fullTypeName(t) + return n.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 { +// packages are part of the type too. Each type's spelling is cached under its +// reflect.Type on the Runner that owns this cache, since the same result types are +// spelled again and again: a settle, a park and a replay type check each ask, and an +// unnamed type's spelling walks its whole shape. A nil cache spells uncached, which +// changes only who computes the spelling, never what it is. +func (n *typeNames) fullTypeName(t reflect.Type) string { + if n == nil { + return n.spellTypeName(t) + } + if cached, ok := n.cache.Load(t); ok { + return cached.(string) + } + name := n.spellTypeName(t) + if n.n.Load() < n.limit { + if _, loaded := n.cache.LoadOrStore(t, name); !loaded { + n.n.Add(1) + } + } + return name +} + +// typeNameCacheCap is the most entries a typeNames cache holds. It is far more than +// the handful of result types that settle again and again, and far less than the +// types a StructOf-driven run can mint. The bound is approximate: a check-then- +// store race lets a few racing spellings past it, never the steady growth it stops. +const typeNameCacheCap = 4096 + +// spellTypeName computes t's full name, the spelling fullTypeName caches. +func (n *typeNames) spellTypeName(t reflect.Type) string { if name := t.Name(); name != "" { if pkg := t.PkgPath(); pkg != "" { return pkg + "." + name @@ -552,29 +623,29 @@ func fullTypeName(t reflect.Type) string { } switch t.Kind() { case reflect.Pointer: - return "*" + fullTypeName(t.Elem()) + return "*" + n.fullTypeName(t.Elem()) case reflect.Slice: - return "[]" + fullTypeName(t.Elem()) + return "[]" + n.fullTypeName(t.Elem()) case reflect.Array: - return fmt.Sprintf("[%d]%s", t.Len(), fullTypeName(t.Elem())) + return fmt.Sprintf("[%d]%s", t.Len(), n.fullTypeName(t.Elem())) case reflect.Map: - return "map[" + fullTypeName(t.Key()) + "]" + fullTypeName(t.Elem()) + return "map[" + n.fullTypeName(t.Key()) + "]" + n.fullTypeName(t.Elem()) case reflect.Chan: - return chanTypeName(t) + return n.chanTypeName(t) case reflect.Func: - return "func" + signatureName(t) + return "func" + n.signatureName(t) case reflect.Struct: - return structTypeName(t) + return n.structTypeName(t) case reflect.Interface: - return interfaceTypeName(t) + return n.interfaceTypeName(t) } 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()) +func (n *typeNames) chanTypeName(t reflect.Type) string { + elem := n.fullTypeName(t.Elem()) switch t.ChanDir() { case reflect.RecvDir: return "<-chan " + elem @@ -588,7 +659,7 @@ func chanTypeName(t reflect.Type) string { } // signatureName spells a func type t's parameters and results, without "func". -func signatureName(t reflect.Type) string { +func (n *typeNames) signatureName(t reflect.Type) string { var b strings.Builder b.WriteByte('(') for i := range t.NumIn() { @@ -596,23 +667,23 @@ func signatureName(t reflect.Type) string { b.WriteString(", ") } if t.IsVariadic() && i == t.NumIn()-1 { - b.WriteString("..." + fullTypeName(t.In(i).Elem())) + b.WriteString("..." + n.fullTypeName(t.In(i).Elem())) continue } - b.WriteString(fullTypeName(t.In(i))) + b.WriteString(n.fullTypeName(t.In(i))) } b.WriteByte(')') - switch n := t.NumOut(); n { + switch out := t.NumOut(); out { case 0: case 1: - b.WriteString(" " + fullTypeName(t.Out(0))) + b.WriteString(" " + n.fullTypeName(t.Out(0))) default: b.WriteString(" (") - for i := range n { + for i := range out { if i > 0 { b.WriteString(", ") } - b.WriteString(fullTypeName(t.Out(i))) + b.WriteString(n.fullTypeName(t.Out(i))) } b.WriteByte(')') } @@ -622,7 +693,7 @@ func signatureName(t reflect.Type) 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 { +func (n *typeNames) structTypeName(t reflect.Type) string { if t.NumField() == 0 { return "struct {}" } @@ -637,7 +708,7 @@ func structTypeName(t reflect.Type) string { if !f.Anonymous { b.WriteString(qualifiedName(f.PkgPath, f.Name) + " ") } - b.WriteString(fullTypeName(f.Type)) + b.WriteString(n.fullTypeName(f.Type)) if f.Tag != "" { b.WriteString(" " + strconv.Quote(string(f.Tag))) } @@ -648,7 +719,7 @@ func structTypeName(t reflect.Type) 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 { +func (n *typeNames) interfaceTypeName(t reflect.Type) string { if t.NumMethod() == 0 { return "interface {}" } @@ -659,7 +730,7 @@ func interfaceTypeName(t reflect.Type) string { b.WriteByte(';') } m := t.Method(i) - b.WriteString(" " + qualifiedName(m.PkgPath, m.Name) + signatureName(m.Type)) + b.WriteString(" " + qualifiedName(m.PkgPath, m.Name) + n.signatureName(m.Type)) } b.WriteString(" }") return b.String() @@ -689,13 +760,14 @@ func qualifiedName(pkg, name string) string { // another function-local type, also has. An empty name, a result recorded with no // type, accepts anything. Only a parked service result carries its own type, so the // parked check below names a service result whatever what is; an actor outcome is -// never parked. -func decodedAsRecorded(value any, recorded recordedResult, aliases map[string]string, what string) error { +// never parked. names is the Runner's cache the decoded value's type is spelled +// through. +func decodedAsRecorded(names *typeNames, value any, recorded recordedResult, aliases map[string]string, what string) error { typ := recorded.typ if typ == "" || value == nil || genericJSON(value) { return nil } - got := typeName(value) + got := names.typeName(value) alias, aliased := aliases[typ] if got != typ && (!aliased || got != alias) { if aliased { diff --git a/durable/service_encode_internal_test.go b/durable/service_encode_internal_test.go index eec3249..9ed8525 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, nil, settled, "service result", "service error")("done", tc.result, nil) + value, outErr, abort := replayableOutcome(tc.decode, nil, cacheRunner().names, settled, "service result", "service error")("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, nil, "service result", "service error")("done", recordedResult{raw: sp.Result}, nil) + replayed, _, rabort := replayableOutcome(tc.decode, nil, cacheRunner().names, nil, "service result", "service error")("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 b16e3c9..6b0b8f2 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, nil, &settledJSON{}, "service result", "service error")("done", tc.result, nil) + _, _, abort := replayableOutcome[string](refuse, nil, cacheRunner().names, &settledJSON{}, "service result", "service error")("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 3327f44..bb68ae8 100644 --- a/durable/timetravel.go +++ b/durable/timetravel.go @@ -142,7 +142,10 @@ func StateAt[S comparable, E comparable, C any]( return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } - if err := replayThrough(ctx, inst, &cfg, bounded, env, repClock); err != nil { + // StateAt builds no Runner, so its replays spell every type uncached (see + // typeNames): the spelling is pure in the type alone, so an uncached one is the + // one a Runner's cache would return. + if err := replayThrough(ctx, inst, &cfg, nil, bounded, env, repClock); err != nil { return nil, fmt.Errorf("durable: reconstructing %q at step %d: %w", id, step, err) } return &TimeTravelView[S, E, C]{inst: inst, step: step}, nil @@ -231,6 +234,7 @@ func replayThrough[S comparable, E comparable, C any]( ctx context.Context, inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], + names *typeNames, bounded []Record, env checkpointEnvelope, repClock *replayClock, @@ -251,7 +255,7 @@ func replayThrough[S comparable, E comparable, C any]( repClock.release() } - svc := newReplayServiceRunner(inst, cfg) + svc := newReplayServiceRunner(inst, cfg, names) if svc != nil { svc.Absorb(ctx, inst.StartEffects()) } @@ -269,7 +273,7 @@ func replayThrough[S comparable, E comparable, C any]( return err } reads += clockReadCount(&bounded[i]) - if _, err := replayRecord(ctx, inst, cfg, sched, svc, &bounded[i], nil, armsActorFires(&bounded[i])); err != nil { + if _, err := replayRecord(ctx, inst, cfg, names, sched, svc, &bounded[i], nil, armsActorFires(&bounded[i])); err != nil { return err } // Leave none of the Record's readings for the next one, as Recover does. @@ -298,12 +302,15 @@ func boundRecords(records []Record, target int) []Record { // newReplayServiceRunner builds the kernel service host driver for the read-only // replay, or nil when no registry was wired. It is the reader's analog of the // Runner's newServiceRunner, kept separate so the reader pulls in no live-path state. +// names is the Runner's cache the recorded type checks spell through, nil from the +// Runner-less StateAt (see typeNames). func newReplayServiceRunner[S comparable, E comparable, C any]( inst *state.Instance[S, E, C], cfg *runnerConfig[S, E, C], + names *typeNames, ) *state.ServiceRunner[S, E, C] { if cfg.serviceReg == nil { return nil } - return state.NewServiceRunner(inst, cfg.serviceReg).WithResultTransform(replayableOutcome(cfg.eventDataDecoder, cfg.resultAliases, nil, "service result", "service error")) + return state.NewServiceRunner(inst, cfg.serviceReg).WithResultTransform(replayableOutcome(cfg.eventDataDecoder, cfg.resultAliases, names, nil, "service result", "service error")) } diff --git a/durable/typename_internal_test.go b/durable/typename_internal_test.go index f3513c3..05d2dec 100644 --- a/durable/typename_internal_test.go +++ b/durable/typename_internal_test.go @@ -1,18 +1,35 @@ package durable import ( + "fmt" + "reflect" + "strconv" + "sync" "testing" + "github.com/stablekernel/crucible/state" + alpha "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model" beta "github.com/stablekernel/crucible/durable/internal/typefixture/beta/model" ) +// cacheRunner builds a Runner over the least machine there is, for the type-name +// cache its constructor builds. The tests that use it drive no step, so the machine +// never runs and the nil Store is never written. +func cacheRunner() *Runner[string, string, int] { + return NewRunner[string, string, int]( + state.ForgeFor[int]("typename").State("idle").Initial("idle").Quench(), + nil, + ) +} + // 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. +// are part of the name too. Each spelling is asked twice of one Runner's cache — the +// miss that stores it, then the hit the cache serves — and both must agree. func TestTypeName_UnnamedTypesKeepTheImportPath(t *testing.T) { type tagged struct { R alpha.Result `json:"r"` @@ -39,10 +56,12 @@ func TestTypeName_UnnamedTypesKeepTheImportPath(t *testing.T) { {"chan", make(chan alpha.Result), make(chan beta.Result)}, {"chan direction", make(<-chan alpha.Result), make(chan<- alpha.Result)}, } + names := cacheRunner().names 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) + a, b := names.typeName(tc.a), names.typeName(tc.b) + if hit, hitB := names.typeName(tc.a), names.typeName(tc.b); hit != a || hitB != b || a == b { + t.Fatalf("typeName gives %q for both %T and %T (hit: %q, %q)", a, tc.a, tc.b, hit, hitB) } }) } @@ -50,7 +69,9 @@ func TestTypeName_UnnamedTypesKeepTheImportPath(t *testing.T) { // 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. +// named parts reads as reflect gives it. Every case is spelled twice through one +// Runner's cache — the miss that stores it, then the hit the cache serves — and once +// uncached, and all three must be the same spelling. func TestTypeName_SpellsUnnamedTypesAsGoDoes(t *testing.T) { const a = "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model.Result" cases := []struct { @@ -74,22 +95,180 @@ func TestTypeName_SpellsUnnamedTypesAsGoDoes(t *testing.T) { {make(chan (<-chan int)), "chan (<-chan int)"}, {map[string][]struct{ N int }{}, "map[string][]struct { N int }"}, } + names := cacheRunner().names for _, tc := range cases { - if got := typeName(tc.v); got != tc.want { + names.typeName(tc.v) // the miss that stores this type's spelling + if got := names.typeName(tc.v); got != tc.want { // the hit the cache serves t.Errorf("typeName(%T) = %q, want %q", tc.v, got, tc.want) } + if uncached := (*typeNames)(nil).typeName(tc.v); uncached != tc.want { + t.Errorf("uncached typeName(%T) = %q, want %q", tc.v, uncached, 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 } }{}) + names := cacheRunner().names + a := names.typeName(struct{ X interface{ M() alpha.Result } }{}) + b := names.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 { + if hitA, hitB := names.typeName(struct{ X interface{ M() alpha.Result } }{}), names.typeName(struct{ X interface{ M() beta.Result } }{}); hitA != a || hitB != b { + t.Fatalf("the cache serves %q and %q on hits, want the %q and %q it stored", hitA, hitB, a, b) + } + if got, want := names.typeName(struct{ X any }{}), "struct { X interface {} }"; got != want { t.Fatalf("typeName = %q, want %q", got, want) } } + +// TestFullTypeName_CacheIsBounded answers whether runtime-minted types can grow a +// Runner's cache without end: reflect.StructOf mints a new reflect.Type for every +// shape a caller asks, so spelling more distinct structs than the cap must leave the +// cache at the cap, with every spelling still the one its own type spells. +func TestFullTypeName_CacheIsBounded(t *testing.T) { + const cap = 4 + names := cacheRunner().names + names.limitForTest(cap) + + // The miss that races the cap: more distinct minted structs per goroutine than the + // cap admits, so fills run while the cap is being crossed and past it. + fields := []reflect.StructField{{Name: "A", Type: reflect.TypeOf(0)}} + for i := 0; i < 3*cap; i++ { + fields = append(fields, reflect.StructField{ + Name: "F" + strconv.Itoa(i), + Type: reflect.TypeOf(0), + }) + minted := reflect.StructOf(fields) + if got, want := names.fullTypeName(minted), names.spellTypeName(minted); got != want { + t.Fatalf("fullTypeName(%s) = %q, want the uncached %q", minted, got, want) + } + } + + entries := 0 + names.cache.Range(func(_, _ any) bool { entries++; return true }) + if entries > cap { + t.Fatalf("the cache holds %d entries, want at most the cap of %d", entries, cap) + } +} + +// TestFullTypeName_ConcurrentSpellingsShareTheCache answers the interleavings the +// shared cache exists for: settles on different Handles of one Runner spell the same +// result types at once — simultaneous first misses on one type, and hits under load — +// and a fill races the cap. Whatever the interleaving, every spelling must be its +// type's own, the counter must count each stored entry exactly once, and the fill can +// pass the cap only by as many spellings as raced it: a goroutine's store follows its +// own check of the counter, so at most one store per goroutine can be in flight past +// a check that saw the cap not yet crossed. +func TestFullTypeName_ConcurrentSpellingsShareTheCache(t *testing.T) { + const goroutines = 8 + const cap = 4 + names := cacheRunner().names + names.limitForTest(cap) + + // The handful of result types every Handle of the Runner settles: all goroutines + // spell these, so their first misses overlap and their later spellings are hits + // under load. + shared := []reflect.Type{ + reflect.TypeOf(alpha.Result{}), + reflect.TypeOf(beta.Result{}), + reflect.TypeOf(map[string][]*alpha.Result{}), + } + + var wg sync.WaitGroup + errs := make(chan string, goroutines) + for g := 0; g < goroutines; g++ { + wg.Add(1) + go func(g int) { + defer wg.Done() + // More distinct minted structs than the cap admits, each spelled from the + // shared types, so this goroutine's fills race the others' and the cap. + fields := []reflect.StructField{{Name: "A", Type: shared[0]}} + for i := 0; i < 3*cap; i++ { + fields = append(fields, reflect.StructField{ + Name: "G" + strconv.Itoa(g) + "F" + strconv.Itoa(i), + Type: shared[i%len(shared)], + }) + minted := reflect.StructOf(fields) + if got, want := names.fullTypeName(minted), names.spellTypeName(minted); got != want { + errs <- fmt.Sprintf("goroutine %d: fullTypeName(%s) = %q, want the uncached %q", g, minted, got, want) + return + } + } + for _, s := range shared { + if got, want := names.fullTypeName(s), names.spellTypeName(s); got != want { + errs <- fmt.Sprintf("goroutine %d: fullTypeName(%s) = %q, want the uncached %q", g, s, got, want) + return + } + } + }(g) + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + + // The counter counts each stored entry once, however the LoadOrStores interleaved. + entries := 0 + names.cache.Range(func(_, _ any) bool { entries++; return true }) + if got := names.n.Load(); got != int64(entries) { + t.Fatalf("the counter counts %d, want the %d entries the cache holds", got, entries) + } + // The fill can pass the cap only by the spellings that raced it: at most one + // in-flight store per goroutine past a check that saw the cap not yet crossed. + if entries > cap-1+goroutines { + t.Fatalf("the cache holds %d entries, want at most the cap of %d plus the %d spellings that can race it", entries, cap, goroutines) + } +} + +// TestTypeNames_TwoRunnersShareNoEntries answers whether two Runners' caches are +// separate: a type spelled through one Runner's cache must be absent from another +// Runner's, so no two Runners anywhere share state. Against a cache shared behind the +// Runners — the package-level cache this replaced — the second Runner finds the +// first's entry, and this test fails. +func TestTypeNames_TwoRunnersShareNoEntries(t *testing.T) { + r1 := cacheRunner() + r2 := cacheRunner() + values := []any{alpha.Result{}, beta.Result{}, struct{ R *alpha.Result }{}} + for _, v := range values { + v := v + first := r1.names.typeName(v) // stores in r1's cache alone + if _, ok := r2.names.cache.Load(reflect.TypeOf(v)); ok { + t.Fatalf("Runner 2's cache holds %v, spelled only through Runner 1: the Runners share a cache", reflect.TypeOf(v)) + } + if second := r2.names.typeName(v); second != first { + t.Fatalf("the Runners spell %v differently: %q and %q", reflect.TypeOf(v), first, second) + } + } + // Each Runner's counter counts only its own stores: the same spellings, stored + // by each Runner separately, so the two counters agree and are nonzero — never + // one Runner's stores counted for both. + if first, second := r1.names.n.Load(), r2.names.n.Load(); first == 0 || second != first { + t.Fatalf("the Runners' counters count %d and %d, want the same nonzero stores each", first, second) + } +} + +// BenchmarkFullTypeName_DeepUnnamedType measures a deeply unnamed type's spelling +// on a Runner's cache hit path: a struct literal of a map of slices of funcs and +// chans built over two packages' named types, the shape a settle's result type is +// spelled from for every result of that type. The first iteration spells it and +// stores it; every one after — the steady state for a settling run — is a hit, so +// what this reports is the hit, not the first spelling. +func BenchmarkFullTypeName_DeepUnnamedType(b *testing.B) { + names := cacheRunner().names + t := reflect.TypeOf(struct { + Roster map[string][]func(alpha.Result) (*beta.Result, error) + Feeds []chan struct{ Head *alpha.Result } + }{}) + b.ReportAllocs() + var sink string + for i := 0; i < b.N; i++ { + sink = names.fullTypeName(t) + } + if sink == "" { + b.Fatal("fullTypeName spelled nothing") + } +}