Repository navigation
Modernise the codebase for Go 1.27 - #284
Merged
Merged
Conversation
…e and gate packages
…over report to the modernise spec
…percentile_tracker_bench_test.go, proxy/core/retry_classify_bench_test.go, proxy/core/common_xff_bench_test.go, handlers/handler_stats_sort_bench_test.go, balancer/priority_tied_fixture_test.go)
…ll branch, and the handler sort maps are built once
…iming the sort's best case
…sort diluted by formatting
…the chain parsing
…nstead of overclaiming
…seline measurements (B = b3b1bfc)
…ains 19 sites become slices.Contains and one, isSystemMessageWithCodeKeywords in internal/adapter/inspector/body_inspector.go, becomes slices.ContainsFunc with the method value bound once. Audit: every range expression is a slice value or field (no call, no side effect) and every comparison operand is a variable or a constant, so nothing is evaluated a different number of times except the comparison itself. Formatter delta (FR-18): profile_config.go and routing.go each had a single-line import declaration; go fix added a standalone import "slices" beside it, and goimports merged the two into one parenthesised group. The other 15 files gained "slices" inside an existing group, which goimports leaves alone. Test assertions unchanged.
…der w.Header() loops are kept Audit: the tool produced no maps.Clone, so nothing turns a nil map into an empty one. Every destination is a fresh make or a make-initialised field (merged.Metadata in default_unifier.go, fields in unknown_keys.go), so a nil source was already a no-op and maps.Copy is exact. Reviewed edits (FR-17, AC-3): the seven w.Header()[k]=v loops in internal/app/handlers/handler_translation_passthrough_test.go and the upstream echo in internal/adapter/proxy/benchmark_refactor_test.go keep the per-header loop, with dst := w.Header() inside the body, so w.Header() keeps its call count of one per entry and none for an empty map. The recorders those tests write through return a stored map, so the count is not observable, but AC-3 names w.Header() and requires the count unchanged; the benchmark row also measures its upstream echo. Neither go fix -diff -mapsloop nor the modernize linter flags a call inside the loop, so there is no recorded exception and no nolint. The passthrough test file no longer imports maps. No formatter delta, test assertions unchanged.
Audit: no floats anywhere (the tool skips them); the one reordered pair, len(EndpointIDs) against len(Endpoints) in handler_status_models.go, is commutative. No formatter delta, test assertions unchanged.
…e strings.Cut Each index was used only for the prefix, so the before value Cut returns is the same string. No formatter delta, test assertions unchanged.
…tPrefix and CutSuffix Each HasPrefix plus TrimPrefix pair (or HasSuffix plus TrimSuffix) tested and stripped the same prefix or suffix on the same string, so CutPrefix and CutSuffix do both in one call. Five of the six operands are literals; the provider-prefix strip in internal/app/handlers/handler_provider_test.go uses the providerPrefix variable for both. No formatter delta, test assertions unchanged.
Each loop only ranges the result: same order, same elements, no index written and the slice never escapes, so SplitSeq changes the allocation and nothing else. No formatter delta, test assertions unchanged.
Audit: every converted target is either used only inside its if (the tool scopes it there) or never read (the tool drops it to _), so compilation proves none was used after the if. The syscall.Errno check in internal/adapter/proxy/core/retry.go (IsConnectionError) is rewritten exactly as the tool produces it: that branch is unreachable for any error that does not customise As, because syscall.Errno implements net.Error and the net.Error check above it returns first. Left in place, not restructured. Two sites with five errors.As calls in total remain, findings of neither tool and untouched: the x509 chain in internal/adapter/discovery/service.go (four calls on one line) and the PermanentError check in internal/adapter/unifier/retry.go (one). No formatter delta, test assertions unchanged.
…ect.TypeFor Same types in internal/config/unknown_keys.go: yaml.Unmarshaler (the unexported package variable) and Config. The pkg/ public API is unchanged. No formatter delta, test assertions unchanged.
In structKeys in internal/config/unknown_keys.go. The tool also emits f := f after the loop header; range-over-func values are already per iteration, so the forvar analyzer flags it as unneeded and the forvar commit removes it. No formatter delta, test assertions unchanged.
GetPercentiles in internal/adapter/stats/percentile_tracker.go sorts a copy of the samples with a less-than comparator. slices.Sort yields the same sorted values; both sorts are unstable, which a sorted multiset of int64 cannot show. No formatter delta, test assertions unchanged.
…ctly Seven hunks in two test files: five literals in internal/adapter/proxy/olla/service_preserve_path_test.go (one inside a benchmark) and one in internal/app/handlers/handler_status_models_test.go, plus the config import the first file no longer needs. Same value: olla.Configuration embeds only config.OllaConfig, which embeds only BaseProxyConfig, so ProxyPrefix is the single field at depth three, and the handlers mock has one endpointModels. Test setup literals only, assertions unchanged. No formatter delta.
The copies are the f := f that go fix -stditerators emitted in internal/config/unknown_keys.go (range-over-func, already per iteration) and the tc := tc in the parallel subtests of internal/adapter/converter/docker_model_runner_converter_test.go and internal/adapter/registry/profile/docker_model_runner_parser_test.go (Go 1.22 per-iteration semantics). Assertions unchanged. Note: both docker files match the lint config's path exclusion regex `doc`, so the lint count of 0 rests on unknown_keys.go alone; go fix -diff -forvar is what confirms the docker files. The two packages also pass under -race.
…s tests keep their cancel
Defer-order audit. TestHealthCheckLoop_SurvivesPanic takes the mechanical
rewrite: the loop is stopped by StopChecking closing stopCh, it returns on
stopCh or ctx.Done() alike, and nothing after its assertions depends on
when the context is cancelled.
Kept site (FR-17, FR-19): TestEventBus_BasicPubSub and
TestEventBus_CleanupInactiveSubscribers in pkg/eventbus/eventbus_test.go keep
context.WithCancel with its deferred cancel. Subscribe starts a watcher
goroutine on ctx.Done(); t.Context() is cancelled only after the deferred
bus.Shutdown, which would leave the watcher to call unsubscribe on a
shut-down bus.
FR-17 test edits, all in pkg/eventbus/eventbus_test.go: at each of the two
tests the parent of context.WithCancel changes from context.Background()
to t.Context(), and an explanatory comment ("Not bare t.Context():") is
added above it. No assertion changes. The health test edit in
internal/adapter/health/checker_test.go is the tool's own rewrite.
Expected residual for the kept sites: none. Neither go fix
-diff -testingcontext nor the modernize linter reports
context.WithCancel(t.Context()), so the commit leaves both tools at 0 and
no nolint is added. No formatter delta. Both packages pass under -race.
sync.WaitGroup.Go replaces the wg.Add(1) plus go func(){ defer wg.Done() }
idiom at every waitgroupgo site, applied with go fix -waitgroupgo ./... on a
clean tree. golangci-lint fmt over the 26 changed files produced no delta,
so the commit is the tool's output verbatim.
Counts: 35 sites in 26 files (50 diff hunks, git splits long goroutine
bodies across two hunks), 33 in tests and 2 in production code:
internal/adapter/registry/unified_memory_registry.go (unifyWG) and
internal/app/handlers/handler_provider_ollama_ps.go (per-endpoint /api/ps
fan-out). The lint count for waitgroupgo goes from 35 to 0; go fix -diff
-waitgroupgo ./... is empty.
Diff review (AC-3): every one of the 35 sites had defer wg.Done() as the
goroutine's first statement, so wg.Go's deferred Done still runs last and
the ordering relative to every other deferred call is unchanged. Two
rewritten goroutines carry their own inner defer, the recover handler in
handler_provider_ollama_ps.go and defer done.Store(true) in
internal/adapter/unifier/concurrent_readers_test.go; both still run before
Done, as before. Loop variables captured by the rewritten closures (i, ep
in handler_provider_ollama_ps.go; w in rejection_log_test.go and
throttle_test.go; i in request_rate_limit_test.go; path, h in
handler_unified_models_race_test.go) are Go 1.22 per-iteration variables
under go 1.27, so each goroutine keeps its own copy; eventbus_test.go also
retains its explicit idx := i copy. No wg.Add(1) remains next to a
rewritten go statement.
Left as they are, not findings of either tool: 43 WaitGroup .Add(1) sites
in total, none paired with a rewritten go statement. 33 are parameterised
go func(args) launches the analyzer does not match (the health checker's
two among them), two are go x.method() launches whose method defers its own
Done (the lifecycle unifier's cleanup routine and the eventbus worker
pool's worker), seven are start-gate WaitGroups in circuit breaker tests
(five under proxy/olla and health, two under resilience), and one is
wp.pending in the eventbus worker pool, an in-flight counter with no go
statement.
No test assertion, expectation or fixture changed (FR-17). No recorded
exception under FR-19.
…of sort WP-3d, FR-8. The five sites outside the handlers, the stats collectors and the priority balancer. Line numbers are at the parent commit. internal/adapter/translator/registry.go:102 sort.Strings(names) -> slices.Sort. FR-8: sort.Strings to slices.Sort. Map keys: total order, no ties. internal/adapter/registry/profile/factory.go:89 sort.Strings(names) -> slices.Sort. FR-8: sort.Strings to slices.Sort. Map keys: total order, no ties. internal/adapter/inspector/path_inspector.go:233 sort.Strings(out) -> slices.Sort. FR-8: sort.Strings to slices.Sort. Map keys: total order, no ties. The file already imported slices, so only the sort import goes. internal/router/registry.go:114 sort.Slice(entries) -> slices.SortFunc. FR-8: unstable to unstable, comparator carried over unchanged (Order ascending via cmp.Compare). Strict weak order: total order on int. The input is map-derived (the routes map), so tie order was already undefined: no stable variant. Order is assigned successively in normal registration (orderSeq in registerWithMethod), so a tie is possible only through an explicitly set or duplicate Order. This is the startup route table log. internal/adapter/health/checker.go:525 sort.Slice(entries) -> slices.SortFunc. FR-8: unstable to unstable, comparator carried over unchanged (priority descending via cmp.Compare). Strict weak order: total order on int. The input is not deterministic: RunHealthCheck passes repository.GetAll straight to the table builder, and the static repository builds that slice by ranging the endpoint map (internal/adapter/discovery/repository.go). Tied priorities therefore already had an undefined tie order: no stable variant (FR-8 map-iteration rule). This is the startup endpoint table log. FR-17 test edits: none. The sort import is dropped from all five files. Recorded exceptions: none in this commit. Targeted checks: go build ./..., go vet, golangci-lint run and go test -count=1 on ./internal/router/, ./internal/adapter/translator/, ./internal/adapter/registry/..., ./internal/adapter/inspector/ and ./internal/adapter/health/ all exit 0.
…d order WP-3d, FR-8 and FR-9 (b). Line numbers are at the parent commit. internal/adapter/balancer/priority.go:49 sort.Slice(routable) -> slices.SortFunc. FR-8: unstable to unstable, comparator carried over as the three-way byPriorityDesc shape (Priority descending). Strict weak order: total order on int, so a total preorder; equal priorities compare 0. Unstable rather than SortStableFunc on purpose (see FR-9 (b)). FR-9 (b) holds. Evidence at the base commit 6c9cbd0 on the WP-0 fixture (internal/adapter/balancer/priority_tied_fixture_test.go, 24 routable endpoints, tied tiers of 10, 8 and 6, mixed health inside each tier, interleaved insertion order), from TestPrioritySelector_TiedPriorityFixture_UnstableSortReorders with -v, run before and after the change: sort.Slice order: p100-healthy-5, p100-healthy-1, p100-busy-10, p100-busy-2, p100-healthy-9, p100-warming-8, p100-healthy-7, p100-busy-6, p100-healthy-3, p100-warming-4, p50-healthy-7, p50-warming-4, p50-busy-6, p50-healthy-5, p50-healthy-3, p50-healthy-1, p50-warming-8, p50-busy-2, p10-healthy-5, p10-healthy-3, p10-busy-2, p10-warming-4, p10-busy-6, p10-healthy-1 SortFunc order: identical, all 24 elements (compared mechanically) SortStableFunc order: p100-healthy-1, p100-busy-2, p100-healthy-3, p100-warming-4, ... (insertion order inside each tier; different) Evidence files: .verify/orchestrate-go-1.27-modernise/wp-3d/logs/fr9b-fixture-at-base.log, fr9b-compare-at-base.txt, c5-fixture-converted.log and fr9b-compare-converted.txt. Both implementations are pdqsort with the same decision tree, which is the likely reason the orders agree. That match was observed on go1.27.4 and is undocumented (it could change with a toolchain bump). The argument that holds regardless is the one in the priority.go comment: order inside a tied tier is not observable through the weighted selection. The stable variant is the one that changes the order. FR-9 (a), the NFR-1 benchmark threshold, is pending WP-7 (B against H). If it fails there, this site reverts to sort.Slice and becomes a recorded exception under FR-19. Its expected residual is the grep hit only: no modernize slicessort finding, because that analyzer matches only a less function of the bare form s[i] < s[j] and the old comparator compares the .Priority fields with >, and no go fix hunk. It is not an exception while it stays converted. No test pins the production order directly: Select never reveals it, because weightedSelect gives every endpoint in the top tier weight/total whatever its position, so the order is unobservable through the public surface without seeding the global rand source. The fixture test already covers the comparator comparison with the comparator copied verbatim (byPriorityDesc, and the production closure keeps that shape), so no stdlib-only assertion was added. FR-17 test edits: comment-only in priority_tied_fixture_test.go. Three comments called sort.Slice "the current" or "the production" sort in Select and now name it as the pre-WP-3d reference and slices.SortFunc as the production sort. No assertion, fixture or setup changed. Recorded exceptions in this commit: none. Targeted checks: go build ./..., go vet and golangci-lint run on ./internal/adapter/balancer/..., go test -count=1 and go test -race -count=1 on ./internal/adapter/balancer/ all exit 0.
Every context.Background() in the package's tests becomes t.Context(), and in its benchmarks b.Context(), so each context is cancelled when its test or benchmark pass ends instead of leaking goroutines past it. Applied with golangci-lint --fix limited to usetesting; each changed line differs from the old one only by that spelling. The goimports formatter then dropped the context import where nothing else used it. Per file: internal/adapter/balancer/balancer_benchmark_test.go: 8 b.Context internal/adapter/balancer/least_connection_test.go: 14 t.Context, 1 context import dropped internal/adapter/balancer/priority_test.go: 14 t.Context, 1 context import dropped internal/adapter/balancer/priority_tied_fixture_test.go: 1 t.Context, 1 b.Context, 1 context import dropped internal/adapter/balancer/round_robin_test.go: 13 t.Context, 1 context import dropped internal/adapter/balancer/sticky_metrics_test.go: 4 t.Context, 1 context import dropped internal/adapter/balancer/sticky_test.go: 19 t.Context total: 7 files, 65 t.Context, 9 b.Context conversions, 6 context imports dropped Review repair, context ownership: the three benchmark parents no longer hold the context their b.Run closures capture. Each sub-benchmark takes its own b.Context(), which runN renews per b.N pass, so the parallel bodies never run on a context that an earlier pass already cancelled. internal/adapter/balancer/balancer_benchmark_test.go:169 BenchmarkConcurrentSelection internal/adapter/balancer/balancer_benchmark_test.go:212 BenchmarkLargeEndpointSet (selector sub-benchmarks) internal/adapter/balancer/balancer_benchmark_test.go:256 BenchmarkFilteringRoutableEndpoints The file still holds 8 b.Context() occurrences: 3 parent lines removed, 3 sub-benchmark lines added. Audited per site: no t.Cleanup uses the context; the goroutines started with the context (TestRoundRobinSelector_ConcurrentAccess, TestStickySessionWrapper_Race) are joined on a WaitGroup before the test returns. Assertions and table entries are unchanged.
Every context.Background() in the package's tests becomes t.Context(), and in its benchmark b.Context(), so each context is cancelled when its test or benchmark pass ends instead of leaking goroutines past it. Applied with golangci-lint --fix limited to usetesting; each changed line differs from the old one only by that spelling. The goimports formatter then dropped the context import where nothing else used it. Per file: internal/adapter/discovery/auth_test.go: 23 t.Context, 1 context import dropped internal/adapter/discovery/auto_detect_static_test.go: 3 t.Context, 1 context import dropped internal/adapter/discovery/duplicate_url_test.go: 4 t.Context, 1 context import dropped internal/adapter/discovery/endpoint_filter_test.go: 2 t.Context internal/adapter/discovery/hardening_test.go: 13 t.Context internal/adapter/discovery/http_client_test.go: 11 t.Context internal/adapter/discovery/integration_test.go: 4 t.Context, 1 context import dropped internal/adapter/discovery/repository_benchmark_test.go: 4 b.Context, 1 context import dropped internal/adapter/discovery/repository_test.go: 19 t.Context, 1 context import dropped internal/adapter/discovery/repository_userinfo_test.go: 2 t.Context, 1 context import dropped internal/adapter/discovery/retry_test.go: 23 t.Context internal/adapter/discovery/service_test.go: 7 t.Context total: 12 files, 111 t.Context, 4 b.Context, 7 context imports dropped Audited per site: no t.Cleanup uses the context; the goroutines that capture it in retry_test.go (the cancellation-during-backoff cases) derive their own cancellable context from it and are joined on a done channel. Assertions and table entries are unchanged.
…ter tests Every context.Background() in these four packages' tests becomes t.Context(), and in their benchmarks b.Context(), so each context is cancelled when its test or benchmark pass ends instead of leaking goroutines past it. Applied with golangci-lint --fix limited to usetesting; each changed line differs from the old one only by that spelling. The goimports formatter then dropped the context import where nothing else used it. Per file: internal/adapter/filter/glob_filter_test.go: 2 t.Context, 1 context import dropped internal/adapter/filter/integration_test.go: 2 t.Context, 1 b.Context internal/adapter/health/checker_test.go: 16 t.Context internal/adapter/health/client_auth_test.go: 3 t.Context, 1 context import dropped internal/adapter/health/client_classify_test.go: 3 t.Context, 1 context import dropped internal/adapter/health/client_ratelimit_test.go: 4 t.Context, 1 context import dropped internal/adapter/health/client_transport_test.go: 1 t.Context, 1 context import dropped internal/adapter/health/recovery_callback_test.go: 3 t.Context internal/adapter/inspector/body_inspector_test.go: 15 t.Context, 2 b.Context, 1 context import dropped internal/adapter/inspector/chain_benchmark_test.go: 3 b.Context internal/adapter/inspector/chain_test.go: 6 t.Context internal/adapter/inspector/factory_test.go: 8 t.Context, 1 context import dropped internal/adapter/inspector/path_inspector_test.go: 11 t.Context, 1 context import dropped internal/adapter/metrics/benchmark_test.go: 1 b.Context, 1 context import dropped internal/adapter/metrics/extractor_test.go: 4 t.Context, 1 context import dropped internal/adapter/metrics/integration_test.go: 3 t.Context, 1 context import dropped total: 16 files, 81 t.Context occurrences, 7 b.Context occurrences (6 context.Background conversions plus one sub-benchmark line the repair adds), 13 context imports dropped Review repair, context ownership: the benchmark parents no longer hold the context their b.Run closures capture; each sub-benchmark takes its own b.Context(), renewed per b.N pass by runN. internal/adapter/filter/integration_test.go:324 BenchmarkFilterOperations (filter_1000_models) internal/adapter/inspector/chain_benchmark_test.go:15 BenchmarkChain_WithAndWithoutBodyInspector (both closures) internal/adapter/inspector/chain_benchmark_test.go:79 BenchmarkBodyInspector_Overhead (all three body sizes) chain_benchmark_test.go now holds 3 b.Context() occurrences (was 2). Goroutine lifetime in TestHealthCheckLoop_SurvivesPanic, stated exactly: StopChecking closes stopCh and stops the ticker but does not join the loop (checker.go:110-123), and the loop's only exits are ctx.Done() and stopCh (checker.go:141-146). The test stops the checker before it returns, so the loop may observe cancellation after the test body either way; the production API offers no join and none is added here. The context that test passes the loop (checker_test.go:718) already read t.Context() at the branch base e7a9409, from WP-2's testingcontext pass; this commit did not change that line, so the loop's bound is inherited, not introduced here. The context.Background() inside the commented-out body of TestPathInspector_Inspect_LMStudioModels (path_inspector_test.go) is left as it is: it is not live code and the linter does not see it. Assertions and table entries are unchanged.
Every context.Background() in the proxy package and its common, core, olla and sherpa sub-packages becomes t.Context(), and in the benchmarks b.Context(), so each context is cancelled when its test or benchmark pass ends instead of leaking goroutines past it. Applied with golangci-lint --fix limited to usetesting; each changed line differs from the old one only by that spelling. The goimports formatter then dropped the context import where nothing else used it. Per file: internal/adapter/proxy/benchmark_comparison_test.go: 2 b.Context, 1 context import dropped internal/adapter/proxy/benchmark_refactor_test.go: 6 b.Context, 1 context import dropped internal/adapter/proxy/common/url_builder_test.go: 1 t.Context internal/adapter/proxy/core/base_test.go: 2 t.Context, 1 context import dropped internal/adapter/proxy/core/cbopen_test.go: 3 t.Context internal/adapter/proxy/core/conn_reuse_test.go: 1 t.Context, 1 context import dropped internal/adapter/proxy/core/model_rewrite_test.go: 13 t.Context internal/adapter/proxy/core/retry_client_abort_test.go: 1 t.Context internal/adapter/proxy/core/retry_policy_test.go: 4 t.Context internal/adapter/proxy/core/retry_safety_test.go: 11 t.Context internal/adapter/proxy/core/retry_test.go: 2 t.Context internal/adapter/proxy/core/streaming_test.go: 1 t.Context internal/adapter/proxy/olla/client_cancel_breaker_test.go: 3 t.Context internal/adapter/proxy/olla/client_cancel_stats_test.go: 4 t.Context internal/adapter/proxy/olla/service_stall_test.go: 1 t.Context, 1 context import dropped internal/adapter/proxy/proxy_benchmark_test.go: 2 b.Context internal/adapter/proxy/proxy_integration_test.go: 4 t.Context internal/adapter/proxy/proxy_olla_test.go: 2 t.Context, 1 context import dropped internal/adapter/proxy/proxy_sherpa_test.go: 4 t.Context internal/adapter/proxy/proxy_test.go: 3 t.Context internal/adapter/proxy/sherpa/client_cancel_stats_test.go: 2 t.Context internal/adapter/proxy/sherpa/service_leak_stress_test.go: 3 t.Context internal/adapter/proxy/sherpa/service_leak_test.go: 6 t.Context internal/adapter/proxy/sherpa/service_preserve_path_test.go: 4 t.Context internal/adapter/proxy/sherpa/service_retry_test.go: 3 t.Context total: 25 files, 78 t.Context, 10 b.Context conversions, 6 context imports dropped Audited per site: no t.Cleanup uses the context; every goroutine that captures it (the client-disconnect and stalled-stream cases in both engines) derives a cancellable context and is joined before the test returns. Goroutine lifetime in BenchmarkEventBusPublish, stated exactly: each Subscribe(b.Context()) starts a watcher goroutine that blocks on ctx.Done() and then unsubscribes (eventbus.go:97-101). Those watchers are released when the pass's context is cancelled, which is why the conversion to b.Context() is an improvement here: with context.Background() they never returned. The drain goroutines that range over the subscriber channels are not released: nobody closes those channels (Shutdown clears the subscriber map without closing, eventbus.go:182-184, and unsubscribe leaves the channel open, eventbus.go:241-242), and a goroutine blocked in a receive keeps its channel reachable, so neither is ever collected; they block until the process exits. That leak predates this change and is out of scope. One recorded exception: createTestRequestWithStats in proxy_sherpa_test.go keeps context.Background(). It is a request factory with no testing.T in scope, called from 25 sites, and the context it builds only carries the request ID and request time the stats path reads; a comment now says so. The linter does not flag it. Assertions and table entries are unchanged.
Every context.Background() in the registry (with its routing sub-package) and unifier tests becomes t.Context(), and in the benchmarks b.Context(), so each context is cancelled when its test or benchmark pass ends instead of leaking goroutines past it. Applied with golangci-lint --fix limited to usetesting; each changed line differs from the old one only by that spelling. The goimports formatter then dropped the context import where nothing else used it. Per file (context.Background conversions): internal/adapter/registry/alias_test.go: 4 t.Context, 1 context import dropped internal/adapter/registry/capability_tools_test.go: 1 t.Context, 1 context import dropped internal/adapter/registry/discovery_adapter_test.go: 4 t.Context internal/adapter/registry/memory_registry_test.go: 18 t.Context, 3 b.Context internal/adapter/registry/ollama_default_tag_test.go: 7 t.Context, 1 context import dropped internal/adapter/registry/routing/fallback_test.go: 2 t.Context internal/adapter/registry/routing/strict_strategy_test.go: 1 t.Context, 1 context import dropped internal/adapter/registry/unified_memory_registry_benchmark_test.go: 4 b.Context internal/adapter/registry/unified_memory_registry_race_test.go: 9 t.Context internal/adapter/registry/unified_memory_registry_remove_test.go: 6 t.Context internal/adapter/registry/unified_memory_registry_test.go: 6 t.Context internal/adapter/unifier/catalog_store_benchmark_test.go: 1 b.Context, 1 context import dropped internal/adapter/unifier/catalog_store_ollama_tag_test.go: 2 t.Context, 1 context import dropped internal/adapter/unifier/concurrent_readers_test.go: 4 t.Context internal/adapter/unifier/default_unifier_test.go: 8 t.Context, 1 context import dropped internal/adapter/unifier/integration_test.go: 3 t.Context, 1 context import dropped internal/adapter/unifier/lifecycle_unifier_discovery_test.go: 3 t.Context internal/adapter/unifier/lifecycle_unifier_test.go: 8 t.Context internal/adapter/unifier/metadata_integration_test.go: 3 t.Context, 1 context import dropped internal/adapter/unifier/retry_test.go: 7 t.Context total: 20 files, 96 t.Context and 8 b.Context conversions, 10 context imports dropped. One cleanup site follows the rule for t.Cleanup: seedLifecycleRegistry in unified_memory_registry_remove_test.go starts the lifecycle registry with the context and stops it from t.Cleanup, which runs after t.Context() is cancelled, so that helper builds its context with context.WithoutCancel(t.Context()) and a comment says why. This is the one hand edit; the fixer had written t.Context() there. Review repair, context ownership: a parent test or benchmark no longer holds the context that parallel subtests or b.Run closures capture. unified_memory_registry_remove_test.go:17 TestUnifiedRegistry_RemoveEndpointForgetsItInAliasResolution, both subtests now take their own t.Context() unified_memory_registry_race_test.go:104,126,146 TestUnifiedRegistry_ReadersDuring* : the table loop enumerates readers(t.Context(), probe) on the parent context and each subtest takes its own t.Context() internal/adapter/unifier/concurrent_readers_test.go:232 TestUnifiers_ClearDuringUse, the subtest takes its own t.Context() unified_memory_registry_benchmark_test.go:12,90,149,200 all four benchmarks: each b.Run closure takes its own b.Context(); the parent of BenchmarkGetHealthyEndpointsForModel seeds with b.Context() inline internal/adapter/unifier/catalog_store_benchmark_test.go:289 BenchmarkDefaultUnifier_UnifyModels, both closures take their own b.Context() A parallel subtest's parent returns before it runs, and runN renews the benchmark context per b.N pass, so the owning scope is the subtest or sub-benchmark, not the parent. After the repair the files hold 100 t.Context() and 14 b.Context() occurrences (conversions unchanged). Audited per site: no other t.Cleanup uses the context; every goroutine that captures it is joined on a WaitGroup, a done channel or a done flag before the test returns. Assertions and table entries are unchanged.
…tests Every context.Background() in the security package and the anthropic translator's tests becomes t.Context(), and in the benchmarks b.Context(), so each context is cancelled when its test or benchmark pass ends instead of leaking goroutines past it. Applied with golangci-lint --fix limited to usetesting; each changed line differs from the old one only by that spelling. The goimports formatter then dropped the context import where nothing else used it. Per file (context.Background conversions): internal/adapter/security/factory_test.go: 5 t.Context, 1 context import dropped internal/adapter/security/metrics_test.go: 10 t.Context, 1 context import dropped internal/adapter/security/request_rate_limit_test.go: 11 t.Context, 1 context import dropped internal/adapter/security/request_size_limit_test.go: 13 t.Context, 1 context import dropped internal/adapter/translator/anthropic/extended_features_test.go: 7 t.Context, 1 context import dropped internal/adapter/translator/anthropic/integration_test.go: 5 t.Context, 2 b.Context internal/adapter/translator/anthropic/path_translation_test.go: 3 t.Context, 1 context import dropped internal/adapter/translator/anthropic/reasoning_test.go: 9 t.Context, 1 context import dropped internal/adapter/translator/anthropic/request_test.go: 21 t.Context, 1 context import dropped internal/adapter/translator/anthropic/response_test.go: 26 t.Context, 1 b.Context, 1 context import dropped internal/adapter/translator/anthropic/security_test.go: 6 t.Context, 1 context import dropped internal/adapter/translator/anthropic/streaming_bench_test.go: 1 t.Context, 3 b.Context, 1 context import dropped internal/adapter/translator/anthropic/streaming_parse_test.go: 12 t.Context, 1 context import dropped internal/adapter/translator/anthropic/streaming_test.go: 16 t.Context internal/adapter/translator/anthropic/streaming_test_helpers.go: 1 t.Context internal/adapter/translator/anthropic/token_count_test.go: 5 t.Context, 2 b.Context, 1 context import dropped total: 16 files, 151 t.Context and 8 b.Context conversions, 14 context imports dropped. Review repair, context ownership: BenchmarkTransformRequest (integration_test.go:1165, five closures) and BenchmarkTransformResponse (integration_test.go:1356, six closures) no longer take a parent context; each b.Run closure takes its own b.Context(), which runN renews per b.N pass. integration_test.go now holds 11 b.Context() occurrences (was 2). streaming_test_helpers.go is not a _test.go file but holds only test helpers; its executeTransform takes t, so the fixer applied there too. Audited per site: no t.Cleanup uses the context; every goroutine that captures it is joined on a WaitGroup before the test returns. The context.Background() inside the commented-out body of TestSecurityMetricsAdapter_RecordViolation_SizeLimitA (metrics_test.go) is left as it is: it is not live code and the linter does not see it. Assertions and table entries are unchanged.
Every context.Background() under internal/app becomes t.Context(), so each context is cancelled when its test ends instead of leaking goroutines past it. Applied with golangci-lint --fix limited to usetesting; each changed line differs from the old one only by that spelling. The goimports formatter then dropped the context import where nothing else used it. Per file: internal/app/handlers/handler_midstream_death_test.go: 1 t.Context internal/app/handlers/handler_provider_models_test.go: 3 t.Context, 1 context import dropped internal/app/handlers/handler_provider_ollama_ps_test.go: 16 t.Context internal/app/handlers/handler_proxy_body_content_type_test.go: 1 t.Context internal/app/handlers/handler_proxy_embeddings_mixed_fleet_test.go: 1 t.Context internal/app/handlers/handler_proxy_model_test.go: 1 t.Context internal/app/handlers/handler_proxy_ollama_default_tag_test.go: 1 t.Context internal/app/handlers/handler_status_models_test.go: 2 t.Context internal/app/handlers/handler_translation_alias_test.go: 3 t.Context, 1 context import dropped internal/app/handlers/handler_translation_test.go: 3 t.Context internal/app/handlers/handler_unified_models_race_test.go: 1 t.Context, 1 context import dropped internal/app/handlers/handler_unified_models_test.go: 4 t.Context internal/app/handlers/server_routes_tei_test.go: 1 t.Context internal/app/middleware/logging_test.go: 2 t.Context, 1 context import dropped internal/app/model_routing_integration_test.go: 1 t.Context internal/app/services/discovery_client_test.go: 2 t.Context internal/app/services/http_bind_test.go: 2 t.Context, 1 context import dropped internal/app/services/manager_test.go: 7 t.Context internal/app/services/proxy_cleanup_test.go: 3 t.Context total: 19 files, 55 t.Context, 0 b.Context, 5 context imports dropped Audited per site: no t.Cleanup uses the context. The cleanups that share a test with it only close httptest servers, whose handlers wait on their own request contexts; the streaming handler tests that capture it in a goroutine are joined on a done channel. One comment in TestOllamaRunningModels_NoGoroutineLeak called the context "one that never ends"; it now says the context outlives the request, which is what the test relies on. Assertions and table entries are unchanged.
The nine os.Setenv sites in the config tests become t.Setenv, and the manual os.Unsetenv cleanup each one carried goes with it, since t.Setenv restores the previous value when the test or subtest ends. That is the only behaviour difference: a variable that was already set in the environment is restored rather than unset, which is what a clean run assumed anyway. None of the nine tests or their subtests call t.Parallel, which t.Setenv forbids. Sites, all in internal/config/config_test.go (9 Setenv): TestLoadConfig_WithEnvironmentVariables (map loop, cleanup removed) TestEnvironmentVariableParsing (subtest per variable, deferred unset removed) TestLoadConfig_WithRequestLimits (map loop, cleanup removed) TestLoadConfig_WithRateLimits (map loop, cleanup removed) TestLoadConfig_WithTrustedProxyCIDRs (map loop, cleanup removed) TestLoadConfig_WithTranslatorConfig (map loop, cleanup removed) TestLoadConfig_WithPassthroughEnabledEnvVar (subtest per case, deferred unset removed) TestCorsConfig_EnvOverrides (map loop per subtest, cleanup removed) TestEnvOverrides_NewTunables (subtest per variable, deferred unset removed) Assertions and table entries are unchanged.
Every context.Background() in the ports, eventbus and test/integration packages becomes t.Context(), and in the eventbus benchmarks b.Context(), so each context is cancelled when its test or benchmark pass ends instead of leaking goroutines past it. Applied with golangci-lint --fix limited to usetesting; each changed line differs from the old one only by that spelling. The goimports formatter then dropped the context import where nothing else used it. Per file: internal/core/ports/security_test.go: 6 t.Context pkg/eventbus/eventbus_stress_test.go: 3 t.Context, 1 context import dropped pkg/eventbus/eventbus_test.go: 9 t.Context, 3 b.Context pkg/eventbus/eventbus_worker_test.go: 4 t.Context test/integration/filter_profile_break_test.go: 5 t.Context, 1 context import dropped total: 5 files, 27 t.Context, 3 b.Context conversions, 2 context imports dropped Goroutine lifetime, stated exactly: every Subscribe(ctx) starts a watcher goroutine that blocks on ctx.Done() and then unsubscribes (eventbus.go:97-101). With context.Background() those watchers blocked forever in these tests; with t.Context() or b.Context() they are released when the test or benchmark pass ends, so the conversion removes that leak. The drain goroutines that range over the subscriber channels are not released and not joined: nobody closes those channels (Shutdown clears the subscriber map without closing, eventbus.go:182-184, and unsubscribe leaves the channel open, eventbus.go:241-242), and a goroutine blocked in a receive keeps its channel reachable, so neither is ever collected; they block until the process exits. That leak predates this change and is out of scope here. What these tests do join are the publisher goroutines they start directly, on a WaitGroup or a done channel, before the test returns. No t.Cleanup uses the context. Assertions and table entries are unchanged, and the pkg/ public API is untouched.
The lint config excluded usetesting from _test.go and _test_helpers.go files. It no longer does, and the two context checks that are off by default in golangci-lint v2.15.0 are switched on: context-background and context-todo. With the test sweep landed, the linter now reports 0 findings for usetesting across the module and keeps new tests on t.Context(), b.Context() and t.Setenv. The other linters in the test-file exclusion rule stay as they were. No other setting changes.
…Setenv, usetesting enforces it
…retype TestCollector_ConnectionOnlyLastUsed pins three behaviours the atomictypes retype must preserve: a first connection-only update creates the endpoint with a non-zero lastUsed (a zero value would let TTL cleanup evict an endpoint with live connections), a subsequent connection-only update does not refresh it, and a recorded request does. TestCollector_MinLatencySentinel pins the -1 sentinel at both scopes so an implementation that treats 0 as unset fails: the raw global and per-endpoint values are -1 before any successful sample (checked directly on the unexported fields, including after a failure-only first request), and a 0ms first sample followed by a positive one keeps the reported minimum at 0 for both the endpoint and the global bounds. The existing suite would pass either way: TestCollector_ZeroLatencyHandling records a single 0ms sample, which a zero-as-unset implementation also reports as 0. Test-only, lands green on the unmodified pre-retype base: go test -race -count=1 ./internal/adapter/stats/ ok (1.052s).
go fix -atomictypes converted maxLatency, lastIPCleanup, activeConnections and endpoint maxLatency; minLatency, lastCleanup, endpoint minLatency and lastUsed were converted by hand. Fields and types: Collector.minLatency int64 -> atomic.Int64, Collector.maxLatency int64 -> atomic.Int64, Collector.lastCleanup int64 -> atomic.Int64, Collector.lastIPCleanup int64 -> atomic.Int64, endpointData. activeConnections/minLatency/maxLatency/lastUsed int64 -> atomic.Int64. Sampling point preserved: the two map allocations are hoisted into locals so the lastCleanup timestamp is sampled exactly where the base's composite literal sampled it, after the map allocations and before the sub-collector constructors, keeping the first cleanup deadline in place; the store happens after the literal, before publication. Sentinels: the -1 minimum-latency sentinel moves to c.minLatency.Store(-1) in the constructor and d.minLatency.Store(-1) inside the LoadOrCompute creation callback, both before publication and never stored afterwards. lastUsed is stored inside the creation callback so a first connection-only update gets a non-zero timestamp and later connection changes do not refresh it. The CAS loops keep the same semantics: a -1 sentinel means no sample yet, a new sample replaces it and afterwards only lowers. Snapshot copy sites read .Load() into the plain ports.ProxyStats and ports.EndpointStats fields (GetProxyStats, GetEndpointStats, GetConnectionStats, GetConnectionCount, cleanup ages); the exported structs and their JSON tags are unchanged. FR-17 test edits, assertions unchanged: go fix rewrote TestRecordRateLimitedIP_AgeEviction's forced-cleanup reset from atomic.StoreInt64 to collector.lastIPCleanup.Store(0), and the new TestCollector_MinLatencySentinel raw-field reads move from atomic.LoadInt64(&c.minLatency) to c.minLatency.Load() with the field's retype. Verified with go test -race -count=1 ./internal/adapter/stats/ (ok 1.053s), go vet and make align-check.
modelEndpointData.consecutiveErrors int32 -> atomic.Int32 (go fix -atomictypes) and modelEndpointData.lastUsed int64 -> atomic.Int64 (hand). lastUsed is stored inside the LoadOrCompute creation callback before the entry is published; the store after creation in updateModelEndpointStats stays because that path is request-driven and requests do refresh it. Snapshot copy site calculateEndpointModelStats reads .Load() into the plain ports.EndpointModelStats fields; the exported struct and its JSON tags are unchanged. Per D7, modelData.lastRequested and the ModelCollector's own lastCleanup keep atomic function calls: not a modernize finding, deferred. Verified with go test -race -count=1 ./internal/adapter/stats/ (ok 1.046s).
Characterisation commit for WP-6 (docs/specs/go-1.27-modernise.md, section 6 key inventory). Test files only; every assertion is on observable behaviour (paths, bodies, headers, log output, events), so the key retype lands green. internal/app/handlers/contextkeys_route_table_test.go, over the real route table (proxy registration, provider routes from the shipped profiles, translator registration) with a real Olla engine and recording backends: - TestRouteTable_ProxyRouteStripsRegisteredPrefix pins route_prefix supplied by proxy registration (producer router/registry.go:55, consumer handler_proxy.go:764 via util.StripRoutePrefix): /olla/proxy/ is stripped. - TestRouteTable_ProviderRoutesStripTheirRegisteredPrefix loops the registry's actual registered route table (GetRoutes, the same table the status endpoints read) rather than naming one route. Presence is guarded for EVERY proxy prefix every shipped profile registers (built from the same profile YAML the registration read): dmr, lemonade, litellm, llamacpp, lmdeploy, lmstudio/lm-studio/lm_studio, ollama, omlx, openai and openai-compatible, rapid-mlx, sglang, tei and text-embeddings-inference, vllm-mlx, vllm, so a registration or prefix regression on any shipped profile fails the suite. Strip behaviour is driven for every profile the fleet serves, one recording backend per profile: ollama, lm-studio and the whole OpenAI-compatible family (vllm, vllm-mlx, sglang, lmdeploy, llamacpp, litellm, openai-compatible, rapid-mlx, omlx, docker-model-runner whose chat path is /engines/v1/chat/completions), so a strip regression fails on every served profile. lemonade and the two text-embeddings-inference prefixes are registration-only: their wire formats need protocol-specific requests the recording backends cannot serve (deferral recorded in the work-package report). Each served subtest also carries a cross-hit guard: no other profile's backend may receive the request. The provider handler's override with the raw alias (producer handler_provider_common.go:93) is what makes each spelling strip. - TestRouteTable_TranslatorRegistrationInjectsNoRoutePrefix pins the absence case through a probe handler registered each way: the probe applies the same stripping the proxy path applies and records what it saw. The proxy-registered probe's path comes back stripped, the translator-registered probe's whole, so translator registration injects no route prefix. This is the outside-observable discriminator the end-to-end translator test cannot provide. - TestRouteTable_TranslatorRoutePathComesFromBackendProfile pins translator registration supplying no route prefix: the path comes from the backend profile's native Anthropic path, /olla/anthropic never reaches the backend. - TestRouteTable_StreamingWithoutStreamContextKeyWriter pins the stream key's no-production-writer path: streaming is decided by content type alone (reader core/streaming.go:32). - TestRouteTable_AliasRewritesForwardedBodyModel pins model_alias_map end to end (writer handler_proxy.go:933 to InspectionMeta, reader handler_translation.go:717 into the context, rewriter core/model_rewrite.go:68): the forwarded body carries the backend-specific model name, on both the proxy route and a translated Anthropic request, with every served backend counted so only the alias's targets ever see a hit. - TestRouteTable_RequestIDFlowsFromAccessLogMiddleware pins which request ID wins (Q3): the handler reuses the middleware-assigned ID (reader handler_proxy.go:195, middleware typed key) and the completion and access log lines all name it under the request_id slog key (constants.ContextRequestIdKey as slog key, styled_*.go:117/128). internal/app/handlers/handler_provider_test.go: - TestProviderProxyHandler_RawAliasPrefixOverridesRegistration drives providerProxyHandler directly and pins the override discriminator: a request arriving with a stale registration-shaped route prefix (/olla/proxy/) leaves with the raw alias prefix instead, observed through the path the proxy stage receives (captureProxyService records it), for all three lm-studio spellings. internal/adapter/proxy/core/context_keys_test.go: - TestAutoDetectStreamingMode_StreamKeyNoProductionWriter pins the no-writer rows and the branch a test-side writer of the stream key gates. - TestRecordFailure_EventRequestIDComesFromProxyContextSlot pins the proxy event's RequestID coming from the untyped request_id slot (core/base.go:143, writer handler_proxy.go:222) and the middleware's typed request_id key being a separate slot that does not satisfy it (duplicate keys not merged, Q3). internal/adapter/proxy/proxy_prefix_default_test.go: - TestGetProxyPrefix_DefaultAndExplicit pins the path-prefix default staying the literal route_prefix (proxy/config.go:56) and an explicit prefix passing through. - TestBuildTargetURL_DefaultPrefixNeverStripsRealPaths and TestFactoryBuiltEngine_UnsetProxyPrefixLeavesPathUnchanged pin that the sentinel default never strips a real request path, through URL building (common/url_builder.go:22) and both engines built via the factory. internal/logger/context_keys_test.go: - TestStyledLoggers_RequestIDUsesTheRequestIDSlogKey pins WithRequestID emitting the request_id slog key in both styled loggers. - TestDetailedContextFlag_TerminalFiltersFileKeeps pins the detailed cookie key (logger.go:31, reader logger.go:241, writers styled_plain.go:175, styled_pretty.go:190, middleware/logging.go:376): terminal output drops the detailed record while the file keeps both records, for BOTH styled loggers (plain and pretty). internal/util/strip_route_prefix_test.go: - TestStripRoutePrefix_PresentAbsentAndNoMatch pins StripRoutePrefix (util/request.go:77) for the value present, absent and non-matching cases. request_time, provider_type and original_path are written (or declared) and never read; there is no observable surface to pin, so they are recorded in the work-package report instead of carrying vacuous tests. Verified on this commit: go test -count=1 green on every touched package, golangci-lint --uniq-by-line=false ./... at 0 issues, go vet ./... clean, and the new tests green on the touched packages.
Every untyped string used for context storage becomes the typed contextKey the sticky keys already use; the other roles each spelling serves keep separate untyped string constants (FR-13/FR-14). The characterisation commit underneath pins every behaviour this preserves, including the provider-override discriminator and the translator registration's no-prefix case (probe-pinned). Key table (old form -> new form; roles kept as strings): - route_prefix: constants.ContextRoutePrefixKey untyped -> contextKey; the GetProxyPrefix sentinel default stays the plain string "route_prefix" (proxy.defaultProxyPrefix, never a context key). util.StripRoutePrefix now takes (ctx, path) and looks the typed key up itself; writers use constants.WithRoutePrefix (router registry, provider handler, tests). - request_id: constants.ContextRequestIdKey untyped -> contextKey, still a separate slot from middleware.RequestIDKey (Q3, not merged); the slog role is the new untyped constants.SlogRequestIdKey (logging middleware base logger, both styled loggers' WithRequestID). - request_time, original_path, stream, provider_type: untyped -> contextKey; no other role, no behaviour change (request_time/original_path/provider_type are written or declared and never read). - model_alias_map: context role constants.ContextModelAliasMapKey untyped -> contextKey; the profile InspectionMeta role is the new untyped constants.InspectionMetaModelAliasMapKey (alias handler write, translation handler load). - "detailed": the context-storage role becomes the logger package's typed detailedContextKey with accessor logger.WithDetailed (logging middleware and both styled loggers); DefaultDetailedCookie stays the plain cookie-name string. Accessors added or extended: - constants.WithRoutePrefix; constants.WithStickyOutcome/GetStickyOutcome (*domain.StickyOutcome) plus GetStickyKey/GetStickyKeySource, WithModelAliasMap/GetModelAliasMap, GetModel, GetEndpointPathMap and GetInputTokens (acyclic: domain imports nothing internal, verified with go list). - core.WithCanonicalModel/GetCanonicalModel beside the type in proxy core (constants cannot import core without a cycle). - middleware.GetRequestID now used by the proxy handler, which bypassed it. - logger.WithDetailed. - Accessor adoption beyond the retype's compile/behaviour-forced minimum (review round 1): every reader and writer of a key that has an accessor uses it, production and test. Writers that remain on raw typed keys have no write accessor: the middleware package's own RequestIDKey/LoggerKey writes, the proxy handler's constants request-id/request-time slots (Q3), sticky key/source and model/input-tokens/endpoint-path-map writes (getter only, single production writer each), the never-read provider_type, the stream-key test writers (no accessor; no production writer exists), and the path-stripping tests' unrelatedPrefixKey (deliberately not the real route-prefix key so the ignored-key rows still exercise ignoring). Test-side edits (FR-17; assertions and table rows unchanged throughout): - Forced by the retype (compile errors or the typed key no longer matching the raw string): internal/util/strip_route_prefix_test.go (writer moves to constants.WithRoutePrefix, call follows the new StripRoutePrefix signature); internal/adapter/proxy/core/streaming_test.go (literal "stream" becomes constants.ContextKeyStream); the InspectionMeta loads/stores in handler_proxy_alias_test.go and handler_translation_alias_test.go move to constants.InspectionMetaModelAliasMapKey; the one table value in proxy_path_stripping_test.go using the retyped constant converts with string(...); the provider-override test moved into the characterisation commit has its writer converted to constants.WithRoutePrefix; the characterisation commit's translator probe follows the new StripRoutePrefix signature; the provider-override test's docstring keeps the characterisation commit's wording (the translator-absence surface is pinned separately by the route-table probe test), since the retype changes nothing about what is pinned. - Required by AC-2/AC-3 rather than the compiler (review round 1): the variable-key writes in proxy_path_stripping_test.go get their own defined type unrelatedPrefixKey; test writers with an accessor available move to it (constants.WithRoutePrefix in proxy_routing_test.go, handler_alias_unification_test.go, handler_auth_routes_test.go, handler_midstream_death_test.go, handler_proxy_alias_strict_test.go, handler_proxy_body_content_type_test.go, handler_proxy_completed_status_test.go, handler_proxy_embeddings_mixed_fleet_test.go, handler_proxy_ollama_default_tag_test.go, handler_proxy_path_test.go; constants.WithStickyOutcome in balancer/sticky_test.go and proxy/core/common_test.go; core.WithCanonicalModel and constants.WithModelAliasMap in proxy/core/model_rewrite_test.go and proxy/proxy_model_stats_test.go). - Test readers that use the getters: constants.GetStickyOutcome/ GetStickyKeySource/GetStickyKey in handler_provider_test.go, and core.GetCanonicalModel, constants.GetStickyKey and constants.GetModelAliasMap in handler_proxy_ollama_default_tag_test.go. The remaining raw test reads feed assertions directly and stay raw per FR-17, since converting them would rewrite the assertions: the alias-map, model-key and sticky-key reads in handler_alias_unification_test.go (ctx.Value on ContextModelAliasMapKey, ContextModelKey and ContextStickyKeyKey inside require/assert) and handler_translation_alias_test.go (r.Context().Value on ContextModelAliasMapKey and ContextModelKey inside assert). Lint config: the -SA1029 staticcheck exclusion and its comment are removed in this commit because the stated reason (the constants double as slog, InspectionMeta and lookup keys) is obsolete exactly here; staticcheck reports 0 SA1029 findings without it. Verified on this commit: go build ./..., go vet ./..., staticcheck --enable-only with the uncapped flags at 0 findings, the full default lint at 0 issues, go fix -diff ./... showing only the disable-list residuals (stringsbuilder 4, omitzero 1), and go test -count=1 green on every touched package including the characterisation suites and the full suite.
WP-7 (NFR-1, on regression). The full-pass interleaved bisect put two benchmark regressions on the WP-3d merge e7a9409, at the two handler sort sites: BuildModelStats_Sort/models-5000 and BuildTranslatorStats_Sort/translators-1000. models-500 moved at the same sites by less than the threshold. Restoring each site recovered its row. Both go back to the exact pre-WP-3d code from 6c9cbd0, with a comment saying why they stay. Every median below is the median of the four paired deltas, the second side against the first within each pair. internal/app/handlers/handler_stats_models.go, buildModelStats: the buildModelStats sort. Boundary 6c9cbd0 -> e7a9409, four interleaved pairs on models-5000: +10.41%, +5.83%, +8.42%, +8.13% (paired median +8.28%); models-500: +5.66%, +4.26%, +5.04%, +4.70% (paired median +4.87%). With sort.Slice restored at H, unmodified H against reverted H: models-5000 -5.30%, -5.74%, -6.72%, -8.19% (paired median -6.23%, about 78% of the gap to B); models-500 -4.84%, -5.71%, -3.62%, -4.56% (paired median -4.70%, the whole gap). internal/app/handlers/handler_stats_translators.go, buildTranslatorStats: the buildTranslatorStats sort. Same boundary, four pairs on translators-1000: +10.47%, +7.39%, +10.68%, +8.93% (paired median +9.70%). Restored at H: -8.43%, -8.47%, -10.47%, -8.61% (paired median -8.54%, the whole gap). translators-3 returns to 4 allocs and its B cost (about 275ns), which the generic sort had cut to 1 alloc and about 198ns: that is B's own cost, not a regression. slices.SortFunc hands both elements to its comparator by value, so each comparison copies a whole ModelStats (176 bytes) or TranslatorStatsEntry (144 bytes). That is the visible difference between the two sorts. The mechanism was not measured: the index-sort experiment changed the swaps and the comparator calls together. Alternative considered, not taken: slices.SortFunc on a []int index with the output rebuilt from it. It was faster than the revert on translators-1000 (435 and 429µ against about 442µ) and slower on models-5000 (6.27 to 6.29m against about 6.08 to 6.17m). It also uses more memory (B/op up 35% on the model rows and 80% on translators-1000, allocs/op up 2 to 3) and is more code. FR-17 test edits: none to assertions, benchmark code, setup or fixtures. Two comments in internal/app/handlers/handler_stats_sort_bench_test.go are reworded: they named the slices.SortFunc these benchmarks cover and now name sort.Slice again with the reason it stays, and one sentence that claimed swapping costs more than the comparator calls, which no measurement separates, is replaced by the baseline's profile note. RECORDED EXCEPTION (FR-19, WP-3d AC-1). These two sites are deliberate sort.Slice keepers. Expected residual: none in go fix -diff (no analyzer covers the sort sweep) and none in the linter (sort.Slice is not a modernize finding); the residual is the WP-3d AC-1 grep hit only.
|
Important Review skippedToo many files! This PR contains 281 files, which is 181 over the limit of 100. To get a review, reduce the PR to 100 files or fewer by splitting it into smaller PRs or changing its base branch. Upgrade to a paid plan to raise the limit. CodeRabbit couldn't verify your organization's usage billing state, so no usage-priced review was started. Retry after the billing service recovers.
|
4 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Brings the codebase up to Go 1.27 idioms now that we build on it. The
modernizelinter is now on, andusetestingand SA1029 are enforced. There should be no behaviour change. The plan and acceptance criteria are indocs/specs/go-1.27-modernise.md.Type of change
What changed
Each step is its own
--no-ffmerge, so you can review them one at a time:interface{}toanythroughout (go fix -any).go fixanalyzers, one commit each (errors.AsType,strings.Cut,maps.Copy,slices.Contains,min/maxand so on).sync.WaitGroup.Goinstead ofAdd(1)withdefer Done().new(expr)replaces theptrInt64-style pointer helpers in tests.sort.Slicetoslices.SortFunc/slices.Sort, keeping each comparator's direction and tie-breaks.t.Context()/b.Context()andt.Setenv. Cleanup that needs a live context usescontext.WithoutCancel.stats.CollectorandModelCollectoruseatomic.Int64/atomic.Int32fields. The-1min-latency sentinel andlastUsedare still set before the entry is published.route_prefix,request_id,request_time,original_path,stream,provider_type,model_alias_mapand the logger'sdetailedflag move to typed keys.constants,core(WithCanonicalModel) andlogger(WithDetailed).util.StripRoutePrefixdrops its key argument.request_idand InspectionMetamodel_alias_mapstrings stay untyped on purpose..golangci.yml:modernizeis enabled, withomitzeroandstringsbuilderdisabled.usetestingcheckscontext.Background/TODO.Decisions
buildModelStatsandbuildTranslatorStatsstay onsort.Slice.slices.SortFuncpasses these wide structs by value and benchmarked 8 to 10% slower.omitzerois held back because it changes what ends up in the JSON.stringsbuilderwould touch one site, which isn't worth the churn.ProxyStats, round-robin and discovery already use atomics correctly and are left alone.Compatibility
None for users or config.
util.StripRoutePrefix(ctx, path)loses its key parameter, but it's internal.Performance
Benchmarks were run against main, alternating between the two builds, over four pairs:
IsConnectionError/wrapped-eof, is 5.5% slower (about 5ns).errors.Is(err, io.EOF), before any line this PR touches.Under
heyload: no errors, identical throughput and p50/p95. Binary is 1.3% larger.How was this tested?
make readypasses at 4910ffc, with a clean tree afterwards.make testandmake test-racepass at 4910ffc, with no races./olla-validate --nightlyat 4910ffc: 131 pass, 0 fail.golangci-lintreports 0 issues.go fix -diff ./...leaves only theomitzero/stringsbuilderhunks.Checklist
make readypasses (test-short + test-race + fmt + vet + lint + align)Follow-ups
.golangci.yml'sdocexclusion is an unanchored regex, so it also skips thedocker_model_runner*files. That predates this PR.context_keys_test.goshould shut down its event bus.