From 6287b5c3fc032df1206714fffce80e7bcda57f67 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 18 Nov 2026 16:40:40 -0700 Subject: [PATCH 1/3] perf(durable): cache each type's full spelling Every settle, park and replay type check asks a result's type name, and an unnamed type's spelling walks its whole shape, but the same handful of result types settle again and again. fullTypeName now caches each type's spelling on its reflect.Type - two reflect.Types compare equal exactly when the types are identical, so a cached spelling is always the one its own type spells - and the spelling itself doesn't change. The cache is capped at 4096 entries: past the cap a type is spelled and returned unstored, so runtime-minted reflect.StructOf types can't grow it without end. Item 1, the settledJSON holder, moved to #271 for Temple's ruling, since Option B would put a recording concern in state's public signatures. Item 3 stays as it is: the full spelling keeps the replay type check strict. Closes #255. Signed-off-by: Ray Karnes --- durable/service.go | 45 +++++++++++++++++++++++++- durable/typename_internal_test.go | 52 +++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/durable/service.go b/durable/service.go index d9c73fb5..412527d2 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" ) @@ -542,8 +544,49 @@ func typeName(v any) string { // 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. +// packages are part of the type too. Each type's spelling is cached on its +// reflect.Type, 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. The cache never changes the spelling, only who computes it. func fullTypeName(t reflect.Type) string { + if cached, ok := typeNameCache.Load(t); ok { + return cached.(string) + } + name := spellTypeName(t) + if typeNameCacheLen.Load() < typeNameCacheLimit { + if _, loaded := typeNameCache.LoadOrStore(t, name); !loaded { + typeNameCacheLen.Add(1) + } + } + return name +} + +// typeNameCache 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. +var typeNameCache sync.Map // map[reflect.Type]string + +// typeNameCacheCap is the most entries typeNameCache 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 + +// typeNameCacheLimit is the cap fullTypeName enforces, an int64 so it loads whole +// beside the counter. A test lowers it to exercise the bound; production runs at +// typeNameCacheCap. +var typeNameCacheLimit = int64(typeNameCacheCap) + +// typeNameCacheLen counts typeNameCache'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. +var typeNameCacheLen atomic.Int64 + +// spellTypeName computes t's full name, the spelling fullTypeName caches. +func spellTypeName(t reflect.Type) string { if name := t.Name(); name != "" { if pkg := t.PkgPath(); pkg != "" { return pkg + "." + name diff --git a/durable/typename_internal_test.go b/durable/typename_internal_test.go index f3513c36..b2215aee 100644 --- a/durable/typename_internal_test.go +++ b/durable/typename_internal_test.go @@ -1,6 +1,8 @@ package durable import ( + "reflect" + "strconv" "testing" alpha "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model" @@ -93,3 +95,53 @@ func TestTypeName_InterfaceFieldKeepsTheImportPath(t *testing.T) { t.Fatalf("typeName = %q, want %q", got, want) } } + +// TestFullTypeName_CacheIsBounded answers whether runtime-minted types can grow +// typeNameCache 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 + oldLimit := typeNameCacheLimit + typeNameCacheLimit = cap + defer func() { typeNameCacheLimit = oldLimit }() + typeNameCache.Range(func(k, _ any) bool { typeNameCache.Delete(k); return true }) + typeNameCacheLen.Store(0) + + 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 := fullTypeName(minted), spellTypeName(minted); got != want { + t.Fatalf("fullTypeName(%s) = %q, want the uncached %q", minted, got, want) + } + } + + entries := 0 + typeNameCache.Range(func(_, _ any) bool { entries++; return true }) + if entries > cap { + t.Fatalf("typeNameCache holds %d entries, want at most the cap of %d", entries, cap) + } +} + +// BenchmarkFullTypeName_DeepUnnamedType measures spelling a deeply unnamed type: 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. +func BenchmarkFullTypeName_DeepUnnamedType(b *testing.B) { + 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 = fullTypeName(t) + } + if sink == "" { + b.Fatal("fullTypeName spelled nothing") + } +} From 062e78fd5a1e7d55c2caa1a9e1fb6b7b53540fc8 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 25 Nov 2026 14:19:55 -0700 Subject: [PATCH 2/3] test(durable): pin the shared type-name cache's interleavings The cache's own concurrency had no test: no test spells types from two goroutines at once, so simultaneous first misses on one type, hits under load and a fill racing the cap were unpinned - a regression in the counter or the cap check would ship unnoticed through the -race gate. A new probe runs every spelling concurrently: each goroutine spells more distinct StructOf-minted structs than a lowered cap admits, all built from the same shared types, then the shared types themselves. 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 one in-flight store per goroutine that raced it. The benchmark's comment now says what it measures: the first iteration spells and stores, every one after - the steady state for a settling run - is a hit, so the reported number is the hit, not the first spelling. Signed-off-by: Ray Karnes --- durable/typename_internal_test.go | 86 +++++++++++++++++++++++++++++-- 1 file changed, 82 insertions(+), 4 deletions(-) diff --git a/durable/typename_internal_test.go b/durable/typename_internal_test.go index b2215aee..3365a1d4 100644 --- a/durable/typename_internal_test.go +++ b/durable/typename_internal_test.go @@ -1,8 +1,10 @@ package durable import ( + "fmt" "reflect" "strconv" + "sync" "testing" alpha "github.com/stablekernel/crucible/durable/internal/typefixture/alpha/model" @@ -108,6 +110,8 @@ func TestFullTypeName_CacheIsBounded(t *testing.T) { typeNameCache.Range(func(k, _ any) bool { typeNameCache.Delete(k); return true }) typeNameCacheLen.Store(0) + // 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{ @@ -127,10 +131,84 @@ func TestFullTypeName_CacheIsBounded(t *testing.T) { } } -// BenchmarkFullTypeName_DeepUnnamedType measures spelling a deeply unnamed type: 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. +// TestFullTypeName_ConcurrentSpellingsShareTheCache answers the interleavings the +// shared cache exists for: settles on different Handles 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 + oldLimit := typeNameCacheLimit + typeNameCacheLimit = cap + defer func() { typeNameCacheLimit = oldLimit }() + typeNameCache.Range(func(k, _ any) bool { typeNameCache.Delete(k); return true }) + typeNameCacheLen.Store(0) + + // The handful of result types every Handle 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 := fullTypeName(minted), 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 := fullTypeName(s), 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 + typeNameCache.Range(func(_, _ any) bool { entries++; return true }) + if got := typeNameCacheLen.Load(); got != int64(entries) { + t.Fatalf("typeNameCacheLen 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("typeNameCache holds %d entries, want at most the cap of %d plus the %d spellings that can race it", entries, cap, goroutines) + } +} + +// BenchmarkFullTypeName_DeepUnnamedType measures a deeply unnamed type's spelling +// on the cache's 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) { t := reflect.TypeOf(struct { Roster map[string][]func(alpha.Result) (*beta.Result, error) From 774cc37e16ef85fa4bb6df639fd9c97d5620c550 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 25 Nov 2026 15:56:08 -0700 Subject: [PATCH 3/3] refactor(durable): keep the type-name cache on the Runner Signed-off-by: Ray Karnes --- durable/actor.go | 15 ++- durable/actor_internal_test.go | 8 +- durable/runner.go | 28 ++-- durable/runner_options.go | 5 +- durable/service.go | 163 ++++++++++++++---------- durable/service_encode_internal_test.go | 4 +- durable/settle_absorb_internal_test.go | 2 +- durable/timetravel.go | 15 ++- durable/typename_internal_test.go | 143 ++++++++++++++------- 9 files changed, 243 insertions(+), 140 deletions(-) diff --git a/durable/actor.go b/durable/actor.go index 8a49fc00..8ee0ba69 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 710033c1..5993e713 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 cf6ac608..d1152270 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 655c73dc..97f63dae 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 412527d2..dea34d06 100644 --- a/durable/service.go +++ b/durable/service.go @@ -422,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 { @@ -442,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 { @@ -453,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 } } @@ -470,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 } @@ -504,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 @@ -529,64 +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. Each type's spelling is cached on its -// reflect.Type, 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. The cache never changes the spelling, only who computes it. -func fullTypeName(t reflect.Type) string { - if cached, ok := typeNameCache.Load(t); ok { +// 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 := spellTypeName(t) - if typeNameCacheLen.Load() < typeNameCacheLimit { - if _, loaded := typeNameCache.LoadOrStore(t, name); !loaded { - typeNameCacheLen.Add(1) + name := n.spellTypeName(t) + if n.n.Load() < n.limit { + if _, loaded := n.cache.LoadOrStore(t, name); !loaded { + n.n.Add(1) } } return name } -// typeNameCache 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. -var typeNameCache sync.Map // map[reflect.Type]string - -// typeNameCacheCap is the most entries typeNameCache holds. It is far more than +// 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 -// typeNameCacheLimit is the cap fullTypeName enforces, an int64 so it loads whole -// beside the counter. A test lowers it to exercise the bound; production runs at -// typeNameCacheCap. -var typeNameCacheLimit = int64(typeNameCacheCap) - -// typeNameCacheLen counts typeNameCache'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. -var typeNameCacheLen atomic.Int64 - // spellTypeName computes t's full name, the spelling fullTypeName caches. -func spellTypeName(t reflect.Type) string { +func (n *typeNames) spellTypeName(t reflect.Type) string { if name := t.Name(); name != "" { if pkg := t.PkgPath(); pkg != "" { return pkg + "." + name @@ -595,29 +623,29 @@ func spellTypeName(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 @@ -631,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() { @@ -639,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(')') } @@ -665,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 {}" } @@ -680,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))) } @@ -691,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 {}" } @@ -702,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() @@ -732,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 eec3249f..9ed85259 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 b16e3c9d..6b0b8f21 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 3327f44d..bb68ae89 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 3365a1d4..05d2dec0 100644 --- a/durable/typename_internal_test.go +++ b/durable/typename_internal_test.go @@ -7,16 +7,29 @@ import ( "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"` @@ -43,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) } }) } @@ -54,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 { @@ -78,37 +95,43 @@ 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 -// typeNameCache 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. +// 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 - oldLimit := typeNameCacheLimit - typeNameCacheLimit = cap - defer func() { typeNameCacheLimit = oldLimit }() - typeNameCache.Range(func(k, _ any) bool { typeNameCache.Delete(k); return true }) - typeNameCacheLen.Store(0) + 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. @@ -119,37 +142,35 @@ func TestFullTypeName_CacheIsBounded(t *testing.T) { Type: reflect.TypeOf(0), }) minted := reflect.StructOf(fields) - if got, want := fullTypeName(minted), spellTypeName(minted); got != want { + 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 - typeNameCache.Range(func(_, _ any) bool { entries++; return true }) + names.cache.Range(func(_, _ any) bool { entries++; return true }) if entries > cap { - t.Fatalf("typeNameCache holds %d entries, want at most the cap of %d", 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 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. +// 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 - oldLimit := typeNameCacheLimit - typeNameCacheLimit = cap - defer func() { typeNameCacheLimit = oldLimit }() - typeNameCache.Range(func(k, _ any) bool { typeNameCache.Delete(k); return true }) - typeNameCacheLen.Store(0) - - // The handful of result types every Handle settles: all goroutines spell these, - // so their first misses overlap and their later spellings are hits under load. + 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{}), @@ -171,13 +192,13 @@ func TestFullTypeName_ConcurrentSpellingsShareTheCache(t *testing.T) { Type: shared[i%len(shared)], }) minted := reflect.StructOf(fields) - if got, want := fullTypeName(minted), spellTypeName(minted); got != want { + 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 := fullTypeName(s), spellTypeName(s); got != want { + 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 } @@ -192,24 +213,52 @@ func TestFullTypeName_ConcurrentSpellingsShareTheCache(t *testing.T) { // The counter counts each stored entry once, however the LoadOrStores interleaved. entries := 0 - typeNameCache.Range(func(_, _ any) bool { entries++; return true }) - if got := typeNameCacheLen.Load(); got != int64(entries) { - t.Fatalf("typeNameCacheLen counts %d, want the %d entries the cache holds", got, entries) + 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("typeNameCache holds %d entries, want at most the cap of %d plus the %d spellings that can race it", entries, cap, 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 the cache's 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. +// 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 } @@ -217,7 +266,7 @@ func BenchmarkFullTypeName_DeepUnnamedType(b *testing.B) { b.ReportAllocs() var sink string for i := 0; i < b.N; i++ { - sink = fullTypeName(t) + sink = names.fullTypeName(t) } if sink == "" { b.Fatal("fullTypeName spelled nothing")