diff --git a/docs/languages/go.md b/docs/languages/go.md index 69a2a699..e0bbce50 100644 --- a/docs/languages/go.md +++ b/docs/languages/go.md @@ -60,6 +60,22 @@ and `errors.As` for native error handling. `FallbackTimeoutError` reports a source deadline; callback panics become `CallbackPanicError`. `Invalidate` returns maintenance errors, including `ErrNoRemote` without an adapter. +A Go source often returns an error for a normal outcome, such as not found, and +DialCache records each source error as a `fallback` error. Set +`Operation.ExpectedError` to mark the errors that are not failures. The caller +still gets the error unchanged and nothing is cached; only the `fallback` error +is skipped, and the fallback duration is still recorded. `FallbackTimeoutError` +and `CallbackPanicError` always count, and so does an error when the predicate +panics. To cache a not-found answer, return it as a value instead. The other +languages have no such option yet. Excerpt: + +```go +op := dialcache.Operation[Profile]{ + Identity: dialcache.Identity{KeyType: "user", UseCase: "profile"}, + ExpectedError: func(err error) bool { return errors.Is(err, ErrNotFound) }, +} +``` + ## Identity and values `Identity` holds normalized strings and ordered argument pairs. Use diff --git a/docs/observability.md b/docs/observability.md index 2d98eb57..03e7d41e 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -681,6 +681,15 @@ native error type or message: DialCache defines these values itself, so they are identical for every adapter. + + +A source error that `Operation.ExpectedError` accepts, such as not found, records +no `fallback` error, even when stale recovery serves a value. The fallback timer +still records the wait. A source deadline or panic always records `fallback`. +The other languages have no such option yet. + + + A valid explicit invalidation without a configured remote adapter is still an invalidation attempt: it emits the invalidation count and `error="invalidation"` then returns the native missing-remote error. Invalid buffer inputs fail before diff --git a/formal/catalogs/feature-coverage.json b/formal/catalogs/feature-coverage.json index 26363907..7a486f91 100644 --- a/formal/catalogs/feature-coverage.json +++ b/formal/catalogs/feature-coverage.json @@ -17,6 +17,7 @@ "B01.static-policy-validation", "B01.policy-leaf-omission", "B01.capacity-validation", + "B01.expected-source-errors", "B01.renamed-and-removed-options" ], "assumptions": [] @@ -562,7 +563,8 @@ "X01.datadog-schema-mode", "X01.datadog-validation-privacy", "X01.shadow-log-resource-bounds", - "X01.coalescing-inspection" + "X01.coalescing-inspection", + "B01.expected-source-errors" ], "assumptions": [ "E03" @@ -906,6 +908,43 @@ "adaptation": "Both bindings reject an explicit zero shadow capacity; in Go WithShadowCapacity(0) returns ErrInvalidOption. Go distinguishes an omitted local capacity, which keeps the default of 10,000, from WithLocalCapacity(0), which disables storage while retaining coalescing.", "gaps": [] }, + { + "id": "B01.expected-source-errors", + "rule": "Operation.ExpectedError marks errors a source returns for normal outcomes: an accepted error reaches the caller unchanged, is cached in no layer and records no fallback error event, while the fallback timer, stale recovery and coalescing are unchanged; the source deadline and panic errors always count.", + "contracts": [ + "B01" + ], + "relatedContracts": [ + "C27", + "C58" + ], + "typescript": [], + "go": [ + { + "test": "TestExpectedErrorRecordsNoFallbackError", + "path": "go/expected_error_test.go", + "scope": "Accepting, rejecting, nil and panicking predicates over request, local and remote layers: the source error reaches the caller and the predicate unchanged, nothing is cached or written, the fallback timer records every call and only an accepted error skips the fallback error event; a panicking predicate logs a warning.", + "sha256": "413453de509fc916ff6d370040dc84d2d4c7158efb7df9369cf7e9f181b20602" + }, + { + "test": "TestExpectedErrorAlwaysCountsDeadlinesAndPanics", + "path": "go/expected_error_test.go", + "scope": "A source deadline and a source panic return FallbackTimeoutError and CallbackPanicError, record one fallback error and never call a predicate that accepts every error.", + "sha256": "413453de509fc916ff6d370040dc84d2d4c7158efb7df9369cf7e9f181b20602" + }, + { + "test": "TestExpectedErrorReachesCoalescedFollowers", + "path": "go/expected_error_test.go", + "scope": "A leader and two coalesced followers get the same source error from one source call; the predicate runs once, and the flight records one fallback error only when the predicate rejects the error.", + "sha256": "413453de509fc916ff6d370040dc84d2d4c7158efb7df9369cf7e9f181b20602" + } + ], + "adaptation": "Go sources return errors for normal outcomes such as not found, where TypeScript sources usually return null, which DialCache stores; the predicate keeps those errors out of the fallback error count without caching them.", + "gaps": [], + "notApplicable": { + "typescript": "TypeScript has no expected-error option yet (#287); its sources usually return null for a normal miss, which DialCache stores as a value." + } + }, { "id": "B02.native-context-propagation", "rule": "Enable/disable nesting restores the prior scope after return and failure, and concurrent native flows do not leak enablement.", diff --git a/formal/catalogs/go-parity.json b/formal/catalogs/go-parity.json index 80ef31d5..dd769079 100644 --- a/formal/catalogs/go-parity.json +++ b/formal/catalogs/go-parity.json @@ -11,7 +11,7 @@ "semanticCasesSha256": "380273598e1d956a3f9fce270cc84424b342e456139b279bd56576bd3b837f65", "executionSha256": "eaf117c3e8630013cc8df0524f84af440c470f42e8711ab4dd07b931161c784f", "sourceAuditDispositionsSha256": "942eab018ae0d8fa189ff16c322f6d9b3301aadc7c46d00b311018728c62f34e", - "featureCoverageSha256": "7bfe01e9ed074fc4661e6db2d3397341f7f691f476e2358e4af082c8117570de", + "featureCoverageSha256": "3ad445174431b89164b9a9bbfef0adbeb7ff7e0ca6675b7c8b904392da02084a", "coverageWitnessesSha256": "745cebececddbfa97912621ada94072d648e8e60e8b3eb013b91eefd16f352a1", "profilesSha256": "888a522f8ad97862ebcb0b5fe363ec7bec60367fa42c60e1623141814b1991b3" }, @@ -3328,13 +3328,14 @@ "nativeBindingAdaptations": [ { "id": "B01", - "rationale": "One Go package exposes one non-generic Cache with generic Cached[T]/GetOrLoad[T] functions, a typed Operation[T] with a typed Codec and comparator, a time.Duration Policy with a typed or JSON-shaped runtime overlay, functional options and sentinel errors. Enable returns a scoped context and its close function, with callback helpers for the TypeScript shape; New returns ErrInvalidOption instead of panicking, operation validation returns errors, and functional options distinguish an omitted setting from an explicit zero or empty value. TypeScript entry-point/typechecking tests remain language-specific; observable validation and failure consequences still require Go tests.", + "rationale": "One Go package exposes one non-generic Cache with generic Cached[T]/GetOrLoad[T] functions, a typed Operation[T] with a typed Codec and comparator, a time.Duration Policy with a typed or JSON-shaped runtime overlay, functional options and sentinel errors. Enable returns a scoped context and its close function, with callback helpers for the TypeScript shape; New returns ErrInvalidOption instead of panicking, operation validation returns errors, and functional options distinguish an omitted setting from an explicit zero or empty value. TypeScript entry-point/typechecking tests remain language-specific; observable validation and failure consequences still require Go tests. Operation.ExpectedError is a Go-only option that keeps errors a source returns for normal outcomes out of the fallback error event.", "references": [ "go/README.md", "go/api.go", "go/bindings.go", "go/internal/testsuite/bindings_test.go", - "go/api_boundary_test.go" + "go/api_boundary_test.go", + "go/expected_error_test.go" ] }, { @@ -3396,7 +3397,7 @@ ], "mappingReview": { "status": "reviewed-mapping-not-execution", - "rationale": "Static configuration and callback contracts map to typed time.Duration Policy, functional Option constructors and Operation[T]. ParsePolicy exposes the seconds-based JSON input; pointer leaves and functional options preserve omission versus explicit false/zero. ResolvePolicy applies the sparse overlay and validated feature defaults. The shadow.mismatchLogging leaves map to ShadowPolicy.MismatchLogging with a typed MismatchDiffLevel, and the logMismatches shorthand stays a *bool that expands to them.", + "rationale": "Static configuration and callback contracts map to typed time.Duration Policy, functional Option constructors and Operation[T]. ParsePolicy exposes the seconds-based JSON input; pointer leaves and functional options preserve omission versus explicit false/zero. ResolvePolicy applies the sparse overlay and validated feature defaults. The shadow.mismatchLogging leaves map to ShadowPolicy.MismatchLogging with a typed MismatchDiffLevel, and the logMismatches shorthand stays a *bool that expands to them. Operation.ExpectedError is a Go-only field: Go sources return errors for normal outcomes such as not found, where TypeScript sources return a null that DialCache stores.", "nativeAdaptations": [ "B01", "B02" @@ -3425,7 +3426,7 @@ "RecoveryPredicate", "MismatchEntry" ], - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d" + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d" } ] } @@ -3511,7 +3512,7 @@ ], "mappingReview": { "status": "reviewed-mapping-not-execution", - "rationale": "The public orchestration is divided into Cache lifecycle, Cached registration, GetOrLoad execution, source/read deadlines and detached shadow work. GetOrLoad snapshots inputs before awaiting policy; singleFlight owns leaders/followers. Go contexts, generics, returned errors and recovered callback panics replace TypeScript overloads, promises and exceptions; default diagnostic logging lives in an internal package, while public logger callbacks and inspection remain root-package bindings. The warning's leaves come from the invocation's ResolvedShadow, Operation.MismatchDiff replaces the built-in walk, and warnShadowMismatch emits one shadowMismatchLogging event; a Warn panic is the Go logger_error. Each caller waits on its own context: a leader runs the shared flight on a context its own cancellation does not end, followers stop waiting when their own context ends, the source context carries the source deadline, and detached shadow work runs on a context that ends with its job.", + "rationale": "The public orchestration is divided into Cache lifecycle, Cached registration, GetOrLoad execution, source/read deadlines and detached shadow work. GetOrLoad snapshots inputs before awaiting policy; singleFlight owns leaders/followers. Go contexts, generics, returned errors and recovered callback panics replace TypeScript overloads, promises and exceptions; default diagnostic logging lives in an internal package, while public logger callbacks and inspection remain root-package bindings. The warning's leaves come from the invocation's ResolvedShadow, Operation.MismatchDiff replaces the built-in walk, and warnShadowMismatch emits one shadowMismatchLogging event; a Warn panic is the Go logger_error. Each caller waits on its own context: a leader runs the shared flight on a context its own cancellation does not end, followers stop waiting when their own context ends, the source context carries the source deadline, and detached shadow work runs on a context that ends with its job. source records no fallback error event for an error that Operation.ExpectedError accepts; the caller still gets the error and nothing is cached, and the deadline and panic errors never reach the predicate.", "nativeAdaptations": [ "B01", "B02", @@ -3547,11 +3548,12 @@ "singleFlight", "shared", "source", + "expected", "readServing", "putRemote", "recover" ], - "sha256": "7872cc5aa3eada704c89f1e11ddd5ee619ebb5533f5aed95cf74f228bea0f3f9" + "sha256": "cbb35e38195a6506e766f27695127e7de1c0e8b446f8086f9322df3911015548" }, { "path": "go/deadline.go", @@ -3578,7 +3580,7 @@ "Operation", "Event" ], - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d" + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d" }, { "path": "go/internal/logging/logging.go", @@ -3613,7 +3615,7 @@ "CallbackPanicError", "ErrNoRemote" ], - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d" + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d" }, { "path": "go/redis_adapter.go", @@ -3652,7 +3654,7 @@ "Codec", "Remote" ], - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d" + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d" }, { "path": "go/bindings.go", @@ -3722,7 +3724,7 @@ "remoteValue", "localResult" ], - "sha256": "7872cc5aa3eada704c89f1e11ddd5ee619ebb5533f5aed95cf74f228bea0f3f9" + "sha256": "cbb35e38195a6506e766f27695127e7de1c0e8b446f8086f9322df3911015548" } ] } @@ -3790,7 +3792,7 @@ "TimerClock", "DeferredExecutor" ], - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d" + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d" } ] } @@ -3874,11 +3876,11 @@ "putLocal", "shared" ], - "sha256": "7872cc5aa3eada704c89f1e11ddd5ee619ebb5533f5aed95cf74f228bea0f3f9" + "sha256": "cbb35e38195a6506e766f27695127e7de1c0e8b446f8086f9322df3911015548" }, { "path": "go/api.go", - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d", + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d", "symbols": [ "systemClock", "newSystemClock" @@ -3944,7 +3946,7 @@ "canRecover", "recover" ], - "sha256": "7872cc5aa3eada704c89f1e11ddd5ee619ebb5533f5aed95cf74f228bea0f3f9" + "sha256": "cbb35e38195a6506e766f27695127e7de1c0e8b446f8086f9322df3911015548" }, { "path": "go/shadow.go", @@ -4241,7 +4243,7 @@ "Option", "Logger" ], - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d" + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d" }, { "path": "go/metrics.go", @@ -4260,7 +4262,7 @@ "errorEvent", "duration" ], - "sha256": "7872cc5aa3eada704c89f1e11ddd5ee619ebb5533f5aed95cf74f228bea0f3f9" + "sha256": "cbb35e38195a6506e766f27695127e7de1c0e8b446f8086f9322df3911015548" }, { "path": "go/shadow.go", @@ -4354,7 +4356,7 @@ "Remote", "ReadBudget" ], - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d" + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d" }, { "path": "go/protocol.go", @@ -4430,7 +4432,7 @@ "Codec", "ContextCodec" ], - "sha256": "45ae467fbcef94cb47ebb9e9912f06c81ee03529ad63a108e91db017cd3a1f7d" + "sha256": "bb3080c11fbdff95e379bdca68484ed4bd755fe7d8e080e1394026bfda4f028d" }, { "path": "go/codec.go", diff --git a/formal/catalogs/source-audit.json b/formal/catalogs/source-audit.json index 6ca2b244..bf5c6d76 100644 --- a/formal/catalogs/source-audit.json +++ b/formal/catalogs/source-audit.json @@ -185,7 +185,7 @@ }, { "path": "docs/languages/go.md", - "sha256": "68b3b6822ee4aa51bdc8b39bd81ae8d5ffd3193fbcad7bac8b46e72cb6be3dda", + "sha256": "0a3c089446b3ed433db2b6c72a969b3b3147a963c77d67380d161d67e2609761", "entries": [ {"title":"Go integration","contracts":["B01"]}, {"title":"Installation and runtime","contracts":["B01","B02"]}, @@ -235,7 +235,7 @@ }, { "path": "docs/observability.md", - "sha256": "230f8597110bad4d6327f03d31cb4e045bd26a5b7036cfbc6314add50eae18d2", + "sha256": "2ecbb37cd8f7d4631a778ecc7ffe61e26e6c128fe97f83a4bf48429950a032d0", "entries": [ {"title":"Observability","contracts":["C30","X01"]}, {"title":"Reading the signals","contracts":["C58"]}, @@ -1507,7 +1507,7 @@ }, { "path": "formal/guides/GO-PARITY.md", - "sha256": "c245fd24071f3503447c0f5a43a984a36a447672a261d741a1af83b8c1f17771", + "sha256": "5fe0d41296892a60a4501a7f56533d388dbaf981cf37dc9a484c48dd2d67b1c9", "entries": [ {"title":"Go parity acceptance"}, {"title":"Required evidence"}, @@ -1800,7 +1800,7 @@ }, { "path": "go/README.md", - "sha256": "01224a60c2a05dabdf150351e03115445b69d936f538d17014c94a562e734a86", + "sha256": "8b505722059780c040604bdf73a776747df1d3a463ad27b74f6d9ba6fe3dc457", "entries": [ {"title":"DialCache for Go"}, {"title":"Use"}, diff --git a/formal/guides/GO-PARITY.md b/formal/guides/GO-PARITY.md index b59a55dc..8b2dbc09 100644 --- a/formal/guides/GO-PARITY.md +++ b/formal/guides/GO-PARITY.md @@ -210,6 +210,17 @@ bindings have focused native tests and share the generated policy and shadow replay evidence above. The ledger and feature inventory distinguish each portable case's Quint evidence from its additional native binding requirements. +`Operation.ExpectedError` is a Go-only binding option. Go sources return errors +for normal outcomes such as not found, where TypeScript and Python sources +usually return a value that DialCache stores. An error the predicate accepts +still reaches the caller unchanged and is not stored, but it records no +`fallback` error event, even when stale recovery serves; C58's rule that a +recovered failure still counts applies to the errors it does not accept. The +fallback duration, stale recovery and coalescing are unchanged, and the source +deadline and panic errors never reach the predicate. With the field unset the +shared replay evidence applies unchanged; native tests in +[`expected_error_test.go`](../../go/expected_error_test.go) cover the option. + `MetricsAdapter.ObserveEvent` accepts backend-neutral diagnostics. `FailureIsolatedObserver` and `FailureIsolatedLogger` prevent exporter errors or panics from replacing cache/source results. Confirmed-mismatch warning fields diff --git a/go/README.md b/go/README.md index c8e9f323..02acf6f8 100644 --- a/go/README.md +++ b/go/README.md @@ -129,6 +129,12 @@ Source/codec/provider/comparator panics become `CallbackPanicError`; telemetry panics are ignored. Cache plumbing fails open while explicit maintenance errors are returned. Applications still own cancellation of the source context. +DialCache records every source error as a `fallback` error, including one that +reports a normal outcome such as not found. Set `Operation.ExpectedError` to +mark those errors: the caller still gets the error and nothing is cached, but no +`fallback` error is recorded. A source deadline or panic always counts. Only Go +has this option for now. + `WithClock` separates wall time from elapsed time. The default clock preserves fractional milliseconds through `PreciseClock.ElapsedTime`. Custom clocks can implement that optional interface; existing `ElapsedMS`-only clocks retain their diff --git a/go/api.go b/go/api.go index cf58d6f6..052e65d7 100644 --- a/go/api.go +++ b/go/api.go @@ -116,6 +116,13 @@ type Operation[T any] struct { SourceTimeout time.Duration // ShouldRecover replaces the instance recovery predicate for this operation. ShouldRecover RecoveryPredicate + // ExpectedError reports whether an error that the source returned is a + // normal outcome, such as not found, rather than a source failure. The + // caller still gets the error and nothing is cached, but no fallback error + // event is recorded. This operation's FallbackTimeoutError and + // CallbackPanicError always count, and so does an error when the + // predicate panics. + ExpectedError func(error) bool // Comparator decides shadow matches; nil compares with SemanticEqual. Comparator func(cached, source T) (bool, error) // MismatchDiff replaces the built-in JSON difference computation behind diff --git a/go/engine.go b/go/engine.go index 25568c7c..f13e98a9 100644 --- a/go/engine.go +++ b/go/engine.go @@ -521,8 +521,9 @@ func (x *execution[T]) source(layer string) (T, error) { // Once the wait ends the result is settled; cancel before observers run so a // slow observer cannot keep a timed-out or abandoned source going. cancel() - // Work that no caller waits for any more is not a source failure. - if err != nil && !x.abandoned() { + // Work that no caller waits for any more is not a source failure, and an + // error that the operation expects is a normal outcome. + if err != nil && !x.abandoned() && !x.expected(err) { x.errorEvent(layer, "fallback", true) } x.duration("fallback", layer, start, nil) @@ -746,6 +747,25 @@ func (x *execution[T]) canRecover(err error) bool { } return e == nil && ok } + +// expected reports whether the operation's ExpectedError accepts an error that +// the source returned. The deadline and panic errors come from DialCache +// itself, unwrapped, so they never reach the predicate. +func (x *execution[T]) expected(err error) bool { + predicate := x.op.ExpectedError + if predicate == nil { + return false + } + switch err.(type) { + case *FallbackTimeoutError, *CallbackPanicError: + return false + } + ok, e := callSafely(func() (bool, error) { return predicate(err), nil }) + if e != nil { + x.cache.settings.logger.Warn("DialCache expected error predicate panicked; the error counts as a source failure", e) + } + return e == nil && ok +} func (x *execution[T]) recoveryEvent(outcome string, age *int64) { d := x.labels("") d["outcome"] = outcome diff --git a/go/expected_error_test.go b/go/expected_error_test.go new file mode 100644 index 00000000..86cd9b8b --- /dev/null +++ b/go/expected_error_test.go @@ -0,0 +1,162 @@ +package dialcache + +import ( + "context" + "errors" + "fmt" + "sync/atomic" + "testing" + "testing/synctest" + "time" +) + +// notFoundError stands in for a "not found" error that a Go source returns +// for a normal outcome. +type notFoundError struct{ id string } + +func (e *notFoundError) Error() string { return "not found: " + e.id } + +// expectedErrorFixture caches in every layer over a remote miss. It counts +// source calls, predicate calls, remote writes and the fallback error and +// timer events. +type expectedErrorFixture struct { + cache *Cache + op Operation[int] + logger *boundaryLogger + sourceCalls, predicateCalls, writes, fallbackErrors, fallbackTimer atomic.Int64 + seen error +} + +func newExpectedErrorFixture(policy Policy, predicate func(error) bool) *expectedErrorFixture { + f := &expectedErrorFixture{logger: &boundaryLogger{}} + remote := boundaryRemote{ + read: func(context.Context) (ReadResult, error) { + return ReadResult{Kind: "miss", Reason: "value_absent"}, nil + }, + write: func(Frame) error { f.writes.Add(1); return nil }, + } + f.cache = MustNew(WithRemote(remote), WithoutCompression(), WithLogger(f.logger), WithObserver(func(e Event) { + if e.Kind == "error" && e.Data["error"] == "fallback" && e.Data["inFallback"] == true { + f.fallbackErrors.Add(1) + } + if e.Kind == "fallback" { + f.fallbackTimer.Add(1) + } + })) + f.op = Operation[int]{Identity: Identity{Namespace: "expected", KeyType: "user", ID: "1", UseCase: "profile"}, Policy: policy} + if predicate != nil { + f.op.ExpectedError = func(err error) bool { + f.predicateCalls.Add(1) + f.seen = err + return predicate(err) + } + } + return f +} + +func (f *expectedErrorFixture) get(ctx context.Context, load func(context.Context) (int, error)) (int, error) { + return GetOrLoad(ctx, f.cache, f.op, func(ctx context.Context) (int, error) { + f.sourceCalls.Add(1) + return load(ctx) + }) +} + +func TestExpectedErrorRecordsNoFallbackError(t *testing.T) { + isNotFound := func(err error) bool { var nf *notFoundError; return errors.As(err, &nf) } + for _, c := range []struct { + name string + predicate func(error) bool + fallbackErrors int64 + warnings int64 + }{ + {"expected", isNotFound, 0, 0}, + {"not expected", func(error) bool { return false }, 2, 0}, + {"nil", nil, 2, 0}, + {"panicking", func(error) bool { panic("predicate failure") }, 2, 2}, + } { + t.Run(c.name, func(t *testing.T) { + f := newExpectedErrorFixture(Policy{RequestLocal: true, LocalTTL: time.Second, RemoteTTL: time.Minute}, c.predicate) + returned := fmt.Errorf("profile: %w", ¬FoundError{id: "1"}) + ctx, done := f.cache.Enable(context.Background()) + defer done() + for range 2 { + _, err := f.get(ctx, func(context.Context) (int, error) { return 0, returned }) + var nf *notFoundError + if err != returned || !errors.As(err, &nf) { + t.Fatalf("err = %v; want the source's error unchanged", err) + } + } + if f.sourceCalls.Load() != 2 || f.writes.Load() != 0 { + t.Fatalf("source calls = %d, remote writes = %d; want 2 and 0: the error is cached in no layer", f.sourceCalls.Load(), f.writes.Load()) + } + if f.fallbackErrors.Load() != c.fallbackErrors || f.fallbackTimer.Load() != 2 { + t.Fatalf("fallback errors = %d, fallback timer = %d; want %d and 2", f.fallbackErrors.Load(), f.fallbackTimer.Load(), c.fallbackErrors) + } + if f.logger.warnings.Load() != c.warnings { + t.Fatalf("warnings = %d; want %d", f.logger.warnings.Load(), c.warnings) + } + if c.predicate != nil && f.seen != error(returned) { + t.Fatalf("predicate saw %v; want the source's error unchanged", f.seen) + } + }) + } +} + +func TestExpectedErrorAlwaysCountsDeadlinesAndPanics(t *testing.T) { + for _, c := range []struct { + name string + load func(context.Context) (int, error) + target any + }{ + {"deadline", func(ctx context.Context) (int, error) { <-ctx.Done(); return 0, ctx.Err() }, new(*FallbackTimeoutError)}, + {"panic", func(context.Context) (int, error) { panic("source failure") }, new(*CallbackPanicError)}, + } { + t.Run(c.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newExpectedErrorFixture(Policy{LocalTTL: time.Second, RemoteTTL: time.Minute}, func(error) bool { return true }) + f.op.SourceTimeout = 10 * time.Millisecond + ctx, done := f.cache.Enable(context.Background()) + defer done() + if _, err := f.get(ctx, c.load); !errors.As(err, c.target) { + t.Fatalf("err = %v; want %T", err, c.target) + } + if f.fallbackErrors.Load() != 1 || f.predicateCalls.Load() != 0 { + t.Fatalf("fallback errors = %d, predicate calls = %d; want 1 and 0", f.fallbackErrors.Load(), f.predicateCalls.Load()) + } + }) + }) + } +} + +func TestExpectedErrorReachesCoalescedFollowers(t *testing.T) { + for _, c := range []struct { + expected bool + fallbackErrors int64 + }{{true, 0}, {false, 1}} { + t.Run(fmt.Sprint(c.expected), func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newExpectedErrorFixture(Policy{LocalTTL: time.Second, RemoteTTL: time.Minute}, func(error) bool { return c.expected }) + ctx, done := f.cache.Enable(context.Background()) + defer done() + returned := ¬FoundError{id: "1"} + gate := make(chan struct{}) + load := func(context.Context) (int, error) { <-gate; return 0, returned } + results := make(chan error, 3) + for range 3 { + go func() { _, err := f.get(ctx, load); results <- err }() + synctest.Wait() + } + close(gate) + for range 3 { + if err := <-results; err != error(returned) { + t.Fatalf("err = %v; want the leader's error for every caller", err) + } + } + if f.sourceCalls.Load() != 1 || f.predicateCalls.Load() != 1 || f.fallbackErrors.Load() != c.fallbackErrors || f.fallbackTimer.Load() != 1 { + t.Fatalf("source calls = %d, predicate calls = %d, fallback errors = %d, fallback timer = %d; want 1, 1, %d and 1", + f.sourceCalls.Load(), f.predicateCalls.Load(), f.fallbackErrors.Load(), f.fallbackTimer.Load(), c.fallbackErrors) + } + }) + }) + } +}