Repository navigation
lint: range over integers, and stop linting a dependency's Go files - #375
Conversation
`intrange` 37 → 0 and `modernize` 2 → 0, taking the lint total from 570 to 531. Applied with `golangci-lint --fix` rather than a hand-written transform, because the fixer knows which loops it cannot safely rewrite and a regex over `for i := 0;` does not. Eight of the 39 findings were never ours. The `flatted` npm package ships a Go port under its own package directory, so once anything runs `npm install` in docs-platform or sdks/javascript, `./...` picks up two copies of it — six `intrange` and both `modernize` findings, in a file nobody here can edit. `.golangci.yml` now excludes `/node_modules/` by path, the same exclusion scripts/coverage-gate.sh grew for the same two directories; that one is what made these visible, since the copies showed up as unfloored packages at 0.0% first. Verified in the way that distinguishes the exclusion from the fixer: both vendored files still contain their three old-style loops each afterwards, so the findings went away without `--fix` rewriting a dependency's source. Twenty-nine of the 31 in-repo sites are `for i := 0; i < b.N; i++` in benchmarks, and not writing `for b.Loop()` instead was settled by probe rather than preference. `b.Loop` is the Go 1.24+ form and would make the adjacent `b.ResetTimer()` calls redundant, but that is a semantic change to what each benchmark measures, and the concern that would have forced it does not apply: `modernize`'s `bloop` analyzer is present in the bundled binary and does not fire on `range b.N` even when explicitly enabled, so this trades no finding for another. The benchmarks were run rather than assumed to still iterate — `-benchtime=10x` reports 10 iterations and real per-op timings. The two non-benchmark sites are where a transform can change behaviour, and both are the outer loop of an adjacent-comparison sort over `len(x)-1`: `range` evaluates its bound once where the three-clause form re-evaluated it every iteration. Equivalent here because the bodies swap elements without changing length, and `range` over a negative int does zero iterations exactly as `i < -1` would — measured, since an empty slice makes that bound -1. Both mutation-verified: neutering the LoadBalancer sort fails TestLoadBalancer_LeastLoad with `got [n1], want [n2]`, and inverting the alert-ordering assertion fails TestAlertManager_GetRecentAlerts. The second needed a probe first, because a mutation that deletes an assertion loop passes by construction — the useful check was that the loop runs at all, and it makes two comparisons over three alerts rather than being vacuous. Part of #179.
… names `predeclared` 5 → 0 and `govet` 2 → 0. TestDegradedState built a DegradedState literal and read two of its own fields back, so its subject was its own fixture — it would have passed against any implementation of this package. Verified rather than claimed: with markDegraded replaced by an empty function body, the old test still passes. govet's unusedwrite surfaced it by noticing two of the four fields the literal set were never read. The gap behind that symptom is larger than the finding: markDegraded sets Component, Reason, Since, AttemptCount, LastAttempt, NextAttempt and OriginalError, and nothing in the suite asserted any of them. Three tests call it and all three then ask only isComponentDegraded or a count, leaving the Reason format string, the attempt counter's behaviour on a second failure, and the *errors.ObjectFSError type assertion uncovered. The replacement drives the real producer and checks five properties, each mutation-verified against markDegraded: dropping the operation prefix from Reason, pinning AttemptCount to 1, resetting Since on the second call, disabling the OriginalError type assertion, and removing the RecoveryBackoff gap between LastAttempt and NextAttempt each fail it. The second-call assertions are the ones the old shape made impossible to write — updating an existing record while preserving Since is a property of two calls, not of one literal. Separately, five variables shadowed predeclared identifiers. Operation.Copy and Progress.Copy in pkg/status each named their result `copy`; both are now `dup`. Neither needed the builtin, since the map copy goes through the package-qualified maps.Copy, so this is a readability fix and not a bug fix — worth saying, because a shadow that had forced a workaround would be a different commit. internal/cache/predictive.go's gradient-descent loop named its error term `error`, now `residual`, which is both unshadowed and the accurate name; checked first that the shadow concealed no dropped failure, and there is no `err` anywhere in that function's scope. Part of #179.
|
Second commit pushed: The Verified rather than asserted: with The gap behind the lint finding is larger than the finding. The replacement drives the real producer. Five mutations against
The second-call assertions are the ones the old shape made impossible to write: updating an existing record while preserving The five |
staticcheck ST1020/ST1021 6 → 0. Each finding was a heading like
`// Enums for health check categorization` sitting above an exported type, which
reads as organisation and renders as documentation.
Prepending the symbol's name would have satisfied the linter and documented
nothing, so each now says what the thing does — and three had a fact worth
stating:
- ClusterManager.UpdateNodeInfo merges selectively. An existing member keeps
its ID, Address and Version, so a gossip message claiming a new address for a
known ID updates liveness and nothing else, and Metadata merges key-by-key
rather than replacing. The Metadata clone on insert matters because
handleJoinMessage stores the same *NodeInfo pointer in gp.memberlist before
passing it here — aliasing would leave two maps shared under two locks.
- internal/health's Category is a label, not a switch. Nothing branches on it,
so a check filed under the wrong category still runs identically.
- filesystem.FilesystemError's sentinels carry an empty Op and Path, so they
are values to compare against rather than errors to return:
ErrNotExist.Error() renders as " : file does not exist".
All three were verified by throwaway probe rather than by reading, and two of the
claims first written were wrong. GetProtocol's comment said its callers are
logging and metrics sites; it has no callers outside this package's own test, and
nothing sets ContextKeyProtocol either. And ErrTierNotSupported is not
indistinguishable from ErrInvalid as first written — both wrap os.ErrInvalid, so
errors.Is against os.ErrInvalid cannot separate them, but
errors.Is(ErrTierNotSupported, ErrInvalid) is false, since each is its own
pointer and neither wraps the other.
Part of #179.
…anic testifylint 33 -> 0, nolintlint 1 -> 0. Two batches that pull in opposite directions, which is the reason this is not a mechanical --fix run. require-error (18 sites). Every one is an error assertion whose following lines depend on it having held: backend_test.go asserts assert.Error(t, err) and then reads err.Error() two lines down. With a nil error that is a nil-pointer panic, which kills the test binary and every other test in the package rather than failing one test with a name. Measured both ways in a scratch test rather than assumed: assert panics with "invalid memory address or nil pointer dereference", require reports "An error is expected but got nil" and stops there. The count is 18 and not 20 because the two assertions that end their block are correctly not flagged. float-compare (15 sites). Here the fixer's suggestion is a downgrade. It says "use assert.InEpsilon (or InDelta)", but 14 of the 15 compare against exactly 0.0, where exact equality is the stronger claim -- a cost model returning a tiny non-zero for a zero-duration store is wrong, not approximately right. Mutating internal/cost/calculator.go's math.Max(0, d) to math.Max(1e-300, d): assert.Zero fails with "Should be zero, but was 2.4696061952e-302"; the suggested assert.InDelta(t, 0.0, cost, 1e-9) passes. So: assert.Zero, which the linter accepts and which keeps exact comparison. The fifteenth is suppressed with its reason in the source. reporter_test.go asserts two identical RecordOp calls price bit-identically -- determinism, not approximation -- and the line below it already uses InDelta, where a tolerance is right because it compares a sum against a doubled value. The nolintlint finding is one character with two consequences, both measured. golangci-lint does honour "// nolint:paralleltest" with the space (paralleltest goes 0 -> 2 on that file without it, so the test was never silently unguarded), but gofmt does not recognize the spaced form -- so taking the space off made gofmt relocate the directive above the declaration and strand the four lines explaining it. Restructured so the prose is prose and the suppression is one self-contained line. paralleltest still reports 384, which is what confirms the directive survived. Verified: go build ./..., go vet ./... and go vet -tags=integration clean; go test -race ./... 36 packages ok; the integration-tagged files compile and run; gofmt clean; golangci-lint 517 -> 484; CHANGELOG markdownlint count unchanged at 362 and zero lines deleted. Refs #179
exhaustive 8 -> 0. Six of the eight were deliberate subset switches and now say so in a default arm; two were a real defect, and the defect is not the one the linter was describing. NodeStatus is a string, and UpdateNodeInfo assigns it straight from a json.Unmarshal of a gossip message -- so the value does not have to be one of the five declared constants. Measured on a two-node manager with a peer at status "from-the-wire": calculateClusterStats reported total=2 alive=1 suspect=0 dead=0, losing a node from a breakdown that is supposed to partition the total, and performHealthChecks left that status in place at any staleness because the switch fell through. Reaping is the half that matters beyond the tally. Quorum in consensus.go tests == NodeStatusAlive in three places, so a node stuck at an unrecognized status can neither vote nor be counted while staying in the membership map, and nothing ever removes it. Both switches now treat it as suspect: the node has been heard from, so what is unknown is its state and not its existence, and the existing suspect arm reaps it next pass. Cache size and hit rate stay excluded from the aggregates for the reason a dead node's are. What the linter called two missing cases was mostly dead enum values. NodeStatusJoining and NodeStatusLeaving are declared in cluster.go and assigned nowhere in the repository; EntryTypeSnapshot in consensus.go is appended by nothing, and #151, which would have added snapshotting, was closed for that reason. Every arm of applyLogEntry is empty, which is the honest state of an engine that commits entries and applies none -- #169 decided coordination moves to S3 conditional writes, with #284 the live follow-up, so those arms are not a to-do list. The other subset switches: circuit breaker's onFailure cannot see StateOpen (beforeRequest returns ErrOpenState without calling fn) and currentState has nothing to advance for half-open (it ends on the first result, not a timer); pkg/api names StateHealthy so the status mapping is complete in one place; connection.Wait's three transient states are what it exists to wait through; and pkg/health's isWriteError would need 49 names to say what its documented default direction already says. Verified: TestUnrecognizedNodeStatus_IsCountedAndReaped fails on each arm separately -- removing the stats default fails the partition assertion, removing the health-check default fails the reap assertion, neither fails the other's. go build, go vet clean; go test -race 36 packages ok; gofmt clean; golangci-lint 484 -> 476; CHANGELOG markdownlint 362 unchanged, zero lines deleted. Refs #179
errcheck 11 -> 0. Not one of them was a discarded error: every finding was a single-value type assertion, which panics rather than returning a second result. In a test that means a crashed binary taking the package's other tests with it, reported as a stack trace instead of as this test failing on this field. The production one is pkg/api's /info handler, which built its endpoint list as append(info["endpoints"].([]string), "/metrics") -- asserting through a map[string]any it had populated fifteen lines earlier. Correct today, and only for as long as nobody edits the literal above it. The slice is built before the map now, so there is nothing to assert. pkg/api's four test sites read int(response["count"].(float64)) out of a decoded JSON body and now go through a jsonInt helper that tells a missing field from a wrongly-typed one. Verified by mutating the handler both ways: emitting count as a string gives `response["count"] = "2" (string), want a JSON number`, removing the field gives `response has no "count" field; got fields [history limit timestamp]`. internal/metrics's four were the inconsistent minority in their own file -- the same assertion appears twice more in collector_test.go already using the checked form -- so this aligns them rather than introducing a convention. pkg/recovery's discarded two things on one line, GetConnection's error and the concrete type it returned, in a test whose subject is a field on that concrete type. Verified: go build, go vet clean; go test -race 36 packages ok; gofmt clean; golangci-lint 476 -> 465; CHANGELOG markdownlint 362 unchanged, zero lines deleted. Refs #179
gosec 14 -> 0 (517 -> 450 total on #179). Four of the fourteen were noise suppressed with the reason; the rest were real, and three of them were defects rather than lint. The election timer's jitter mixed units: base + rand.Intn(int(base.Milliseconds())) uses a millisecond count as a nanosecond Duration, so a 5s timeout got 690ns to 4.69us of spread — the split vote randomized timeouts exist to prevent. Below 1ms it panicked outright on the consensus goroutine. Extracted to electionTimeout() so the arithmetic is observable at all, with a distribution test rather than a formula restatement. The persistent cache checked its index path with strings.HasPrefix on the joined path, which is not path containment: ../objectfs-cache-evil and /etc/passwd both passed. Validated once at construction with filepath.IsLocal; the test grew from the one case that happened to work to a table of eight. Log files were 0644 and their directory 0755, and object keys are the paths of a user's files. Now 0640/0750, pinned by a test. health.Checker.Start discarded its ctx and built each round from context.Background(); it now uses context.WithoutCancel, matching serveHealth twenty lines below. Every fix verified by mutation in both directions. 36 packages pass -race.
noctx 31 -> 0 (450 -> 419 on #179). Thirty were httptest.NewRequest in pkg/api, which attaches context.Background(): a nil Done channel, nothing to cancel, nothing carried. Now NewRequestWithContext with t.Context() — b.Context() in the two benchmarks. Pinned by a test that compares req.Context() against the test's own, so a rewrite that compiled and changed nothing observable would not pass as "noctx: 0". The last one was net.Listen in internal/network's echo-server test, which would hang to the package timeout if the bind blocked. ListenConfig.Listen on t.Context(), matching internal/health's listenHealth, and the two dials in the same file take t.Context() as well. 36 packages pass -race.
contextcheck 9 -> 4. The linter's complaint was accurate everywhere, and in three places the code around it was wrong in ways the missing context plumbing had been keeping out of view. Auto-remediation skipped exactly the critical issues. The gate was `severity >= PriorityHigh` and Priority is a string, so it compared bytes: "critical" < "high" < "low" < "medium". Measured by execution — critical false, high/low/medium true. Both PriorityCritical arms of detectProblems were the only ones auto-remediation refused, while an elevated latency got it. Priority.AtLeast now ranks explicitly, with a comment on why the constants' own order cannot be used. Three unlocked writes to issue.AutoRemediating racing GetComponentHealthDetail are fixed alongside. The S3 pool destroyed working clients under a bucket-scoped IAM policy. Its probe was ListBuckets with the verdict `err == nil`, and s3:ListAllMyBuckets is a different permission from anything granted on the bucket the pool serves. Verified against a 403 AccessDenied endpoint: every probe declared its connection dead, evicting up to three usable clients per round and recording "Found 3 unhealthy connections" as LastError, forever. Now HeadBucket on the pool's own bucket with the verdict on errors.As(&smithy.APIError) — a 403 or a 404 travelled to S3 and came back, which is what a liveness probe asks; only a transport failure means the client is unusable. pkg/recovery leaked a health-check goroutine per Connect, and Reconnect and the reconnect scheduler both call Connect. Measured at 58 probes where one loop gives ~10 after six calls at a 20ms interval; each surplus loop also called scheduleReconnect independently, so one broken connection produced N competing schedules racing MaxReconnectAttempts. Guarded with CompareAndSwap because Connect runs concurrently with itself. The context lifetimes are decided per site, not rewritten mechanically, and tests pin both answers. WithoutCancel where a separate signal ends the work (Checker.Stop, Monitor.Stop, ConnectionPool.Close, ConnectionManager.Close); plain ctx where the context is the stop signal (problemDetectionLoop selects on ctx.Done()). Monitor.attemptAutoRecovery's inter-attempt time.Sleep is now a select on ctx.Done(), stopCh and the delay. Eight mutations run, each failing with the predicted message — including the two wrong answers contextcheck also accepts: a struct field instead of a parameter does not satisfy it, and binding background work to the caller's cancellation satisfies it while breaking the pool. Refs #179
ReadAheadManager.Stop is exported, sync.Once-guarded, and documented "safe to call multiple times (#104)". Nothing outside tests calls it — not MountManager.Unmount, not Adapter.Stop, not anything on the unmount path. So the goroutines its constructor starts, ConcurrentReads prefetch workers plus a cleanup ticker, ran until the process exited. Measured 2 -> 27 after five NewFileSystem calls: five per filesystem at the default ConcurrentReads: 4, each holding its FileSystem and through it the backend and cache reachable. Not fixed by adding a Stop call to each unmount path, because that is the same obligation that was already being missed. NewReadAheadManager takes the mount's context and both workers select on mount.Done() alongside stopCh, so the cancelMount() the adapter already performs is what ends them. NewFileSystem and CreatePlatformMountManager take the same context and document that it is the mount's lifetime rather than the constructing call's. Each prefetch also derived its 5-second budget from context.Background(). Five seconds is the right scope for a speculative read either way; what changes is that a prefetch in flight when the mount goes away is canceled rather than running to its own deadline against a backend being closed underneath it. The adapter passes mountCtx, which is WithCancel over WithoutCancel(ctx) — it carries the caller's values and deliberately not its cancellation. contextcheck cannot see that, so the finding becomes "non-inherited new context" and takes a documented nolint matching the write path's two lines above. contextcheck 4 -> 3. Both halves verified by mutation. Dropping mount.Done() from the worker selects reports "20 read-ahead goroutines still running after every mount context was canceled (0 -> 25 -> 20)"; restoring the context.Background() prefetch budget reports "a prefetch on a canceled mount context issued 1 GET(s), want 0". The leak test counts goroutines by worker frame name rather than by runtime.NumGoroutine(). The first version measured the process total, which sits near 960 in this package, and flaked on 1 run in 6 by reading 24 where 25 had started — the setup guard failing, not the leak assertion. 16 subsequent runs of the package are clean, 6 of them on the final tree. Refs #179. Stop being test-only is filed as #376.
types.Cache assigns no context to any of its methods, so redis.Cache.Delete ran under context.Background() — and so did the delete the pub/sub invalidation subscriber performs on every message it receives. That one is different from the rest: it is a Redis round trip on the same connection pool the subscription holds, so a canceled subscription could leave a DEL in flight against a client being closed underneath it. Cache.DeleteContext is the same operation with the caller's context restored, and the subscriber uses it. Delete keeps context.Background(), now documented rather than implicit. A context stored on the Cache at construction would be a startup context outliving its scope, which NewCache already explains it avoids, and there is no per-call context to descend from. go-redis applies its own 5s dial and 3s read timeouts, so it is bounded, just not cancelable. Putting a context on types.Cache is a change across four implementations and every internal/fuse call site — a decision to take on its merits, not by way of a lint finding. Verified by mutation: making DeleteContext ignore its context reports "DeleteContext on a canceled context still reached Redis, so the context is decorative". The test also asserts the same call on a live context does delete, so the first assertion is about cancellation and not about the method being broken. contextcheck 3 -> 2. Found while here and filed as #377: the Invalidator that owns this subscriber has no production caller, so a Redis cache is shared across nodes and its cross-node invalidation is never started. Refs #179.
Coordinator.executeLocally applied op.Timeout to context.Background(), so neither caller could stop an operation once it reached S3. executeOnNode had the caller's context and dropped it. The other caller, handleNetworkOperation, is reached from the gossip receive loop, whose context is the cluster's own lifetime — so a node being shut down carried on issuing the GETs, PUTs and DELETEs peers had asked for, bounded only by a 30-second default, writing each result into a gossip socket that was closing. The context now runs from GossipProtocol.Start through the receive loop, handleIncomingMessage, and handleNetworkOperation to the backend call. handleIncomingMessage's other dispatch arms are unaffected: they update in-memory membership state, and NodeOperation is the only one that does I/O. Verified as two separate mutations, because either frame alone passing the test would be misleading. Reverting executeLocally to context.Background() reports "the backend received a live context from a canceled caller"; making handleNetworkOperation drop the context it was just given reports "a peer-requested operation ran under a live context after the cluster's context was canceled, so gossip's receive-loop context is not reaching the S3 call". A context threaded through three frames and dropped in the fourth is the shape of the defect, so there is one assertion per frame. Compatible with #284, which reworks what executeLocally does — consult the log and commitIndex rather than calling the backend directly — not the context it does it under. contextcheck 2 -> 0. That closes out all nine findings this batch started with. Refs #179.
tparallel 27 → 0. Every one of these test functions called t.Parallel() on
itself and then ran its subtests serially inside it, which buys nothing: the
parent yields to its siblings, the children still queue behind each other.
Eight packages: internal/metrics 9, pkg/errors 6, pkg/utils 3,
internal/circuit 3, pkg/api 2, internal/health 2, internal/storage/s3 1,
internal/adapter 1. Two of them had it inverted — TestHandleInfo and
TestCostOptimizer_CostCalculation had parallel subtests under a serial parent,
which serializes them against nothing while blocking the rest of the package
for the parent's whole duration.
Each of the 44 subtests was read rather than rewritten mechanically. All of
them either construct their own subject or call a pure function, and no parent
holds a defer a parallel child could outlive — a plain defer in a parent body
runs when the parent returns, which is before its parallel children finish, and
only t.Cleanup waits.
Verified by mutation in the two largest table-driven cases, because a
parallelized table test that aliases its loop variable reports the wrong row:
ErrCodeTokenExpired: 401 → 418
→ GetDefaultHTTPStatus(TOKEN_EXPIRED) = 418, want 401, under
TestGetDefaultHTTPStatus/TOKEN_EXPIRED
classifyError's "permission" arm returns "other"
→ classifyError() = "other", want "permission", under
TestClassifyError/permission_error
Both name the mutated row, so Go 1.22 per-iteration loop variables hold.
paralleltest 383 → 325: 44 are the same subtests, and the remaining 15 are
internal/metrics/detailed_test.go, taken here so that package finishes clean
rather than being left one file short.
Five consecutive -race runs of all eight packages, no failures.
Refs #179
…ind serial order paralleltest 325 -> 263. Sixty-one of the sixty-two are annotation-only; one was not. pkg/health's TestTracker_CanRead asserted that an unavailable component refuses reads, and it passed for a reason unrelated to what it claimed. The case set the component's state by assigning ComponentHealth.State directly, bypassing transitionState -- the only place that arms nextProbe on entry to a refusing state. nextProbe therefore stayed at the zero time, and admissionState reads a zero clock as "the probe interval has elapsed", so the first CanRead was admitted as a probe and returned true. All four cases shared one tracker, and the read-only case ran first, arming a probe clock 30 seconds out that the unavailable case then inherited. Serial order was the whole check. Giving each case its own tracker -- which parallelizing requires -- removed the accident and the assertion failed. Setup now goes through transitionState, so a case tests a state production can actually reach. Verified by mutation: dropping the nextProbe arming in health.go fails as "CanRead() = true, want false for state unavailable". testHealthListener also gets a mutex and a checks() accessor, independent of parallelism. notifyStateChange spawns a goroutine per listener while OnHealthCheck runs inline, so both methods genuinely run concurrently on one listener while the test reads its slices from a third goroutine. The rest, each read rather than added mechanically: pkg/retry (13; DefaultConfig returns a value, and the exact-backoff assertions survived five repeat -race runs), internal/health/remediation (14; each test builds its own engine and the shared-engine subtests only call DiagnoseProblem and GetRemediations, both of which read re.rules and write only a local diagnosis), internal/config (7), sdks/go/objectfs (6; the integration tests use disjoint key prefixes so they cannot collide in one bucket), internal/filesystem (1), pkg/types (1). internal/config's three TestLoadFromEnv* functions stay serial with a documented //nolint:paralleltest: t.Setenv panics on a test that has called t.Parallel, because the environment is process-wide. Refs #179
paralleltest 263 -> 194. All 69 findings in the package: pricing_manager_test (20), multipart_test (15), backend_test (12), cost_optimizer_test (11), tier_test (8), acceleration_test (6). Two subjects are shared across newly-parallel subtests, and both were checked rather than assumed. PricingManager holds no mutable state after NewPricingManager -- GetTierPricing, StorageRate and GetPricingSummary read config and region and nothing else. CostOptimizer.accessPatterns is guarded by co.mu, and the subtests reach it through patternFor/putPattern/PatternCount rather than indexing the map. Config.ShouldUseMultipart and GetOptimalChunkSize are pure. One real hazard removed on the way: TestPricingManager_ExternalDiscountConfig had a defer os.Remove(tempFile.Name()) and hands that path to two subtests. A plain defer in a parent runs when the parent returns, which is before its parallel children finish, so the file would have been deleted out from under the tests reading it. It lives in t.TempDir() already -- the framework cleans that up after the parallel subtests complete -- so the defer was redundant as well as wrong. Also fixes a tparallel finding this work created: parallelizing the subtests of TestTierRecommendations left parallel children under a serial parent, which serializes them against nothing and blocks the package for the parent's whole duration. tparallel is back to 0. Verified by mutation in two of the parallelized table tests, since a parallel table test that aliases its loop variable reports the wrong row. Widening ShouldUseMultipart's comparison to >= fails as "ShouldUseMultipart(33554432) = true, want false" under file_exactly_at_threshold. Making GetTierPricing ignore its CustomPricing override fails under both Uses_Custom_Pricing and Multiple_Discounts_Applied -- the two subtests that share a manager. Three repeat -race runs of the package are clean. Refs #179
`pkg/utils` had 56 `paralleltest` findings and they could not be annotated away, because the reason those tests were serial was real: `GetDebugManager` returned a process-wide singleton and was the only way to get a manager, and `RecordEvent` fans each event out to every open session. Two tests holding that manager see each other's events and neither can assert an event count. `NewDebugManager` returns a manager that shares nothing; `StartTrace` grows a method form so a test can trace a session on its own manager. The fan-out is now documented on `RecordEvent` rather than being something you deduce from a failing count — it is deliberate, and it means a session's event count is a function of what every other open session generated too. The two tests that assert the global behaviour keep the singleton on purpose. Reading that file for the constructor turned up two genuine unguarded reads: `StopSession` read `endTime`/`events`/`profiles` after releasing the session lock, to format a log line, while returning the session pointer to a caller that may still be recording into it; and `StartTrace` read `session.enabled` with no lock, racing any concurrent stop. Both read under the lock now. `paralleltest` 194 -> 138. Verified by mutation in both directions: reverting the tests to the shared manager reproduces #373's reported failures (`Expected 1 event, got 3`, `Expected 3 events in stats, got 8`), and mutating `FormatBytes`'s boundary fails as `TestFormatBytes/kilobytes` — so the newly parallel table tests still attribute rows to the case that produced them. #373 also asked that a `.golangci.yml` exclusion for `debug_mode_test.go` be deleted. There is no such exclusion; `grep debug_mode .golangci.yml` finds nothing. The 56 findings were never suppressed, so nothing was there to remove. Closes #373 Refs #179
`markDegraded` starts `attemptAutoRecovery` in a goroutine and then keeps writing `AttemptCount` under the manager's lock on every later failure for the same component. `attemptAutoRecovery` copied `NextAttempt` under the lock, released it, and then read `AttemptCount` off the shared pointer to format a log line. A second failure on one component is therefore a data race. The suite runs entirely under `-race` and never saw it: every test marks each component exactly once, and the one test that marks twice disables auto-recovery, so there was no goroutine to race with. `TestRecoveryManager_RepeatedDegradationWithAutoRecovery` produces that shape. Verified in both directions — restoring the unlocked read fails the new test with a race at `recovery.go:377` against the write at `:328`, and the fix is clean at `-count=5`. Found while parallelizing `pkg/recovery` and `pkg/status` for #179, which is the rest of this commit: `t.Parallel()` on 37 recovery tests and 21 status tests. `paralleltest` 138 -> 80. Mutation-checked both table tests — `ConnectionState.String` returning the wrong name fails `TestConnectionState_String` by value, and dropping the counter from `generateOperationID` fails `TestGenerateOperationID` and takes `TestTracker_GetAllOperations` down to one operation, so the parallel tests still attribute results to the case that produced them. Refs #179
37 sites across `lru_test.go` and `persistent_test.go`, plus three range-loop subtests. `paralleltest` 80 -> 43. Annotations were the whole change here: every test already constructs its own cache, and the persistent ones already take a `t.TempDir()`. Worth saying explicitly, since the two packages before this one each turned out to be hiding a real defect behind serial execution — this one was not. Clean at `-race -count=4`. Mutation-checked both table tests: changing the default eviction policy fails `TestNewLRUCache/nil_config_uses_defaults`, and changing the default cleanup interval fails `TestNewPersistentCache/zero_values_get_defaults`, each naming its own case. Refs #179
Eighteen `paralleltest` findings in `pkg/api/server_test.go`, taking the repo count 43 → 25.
Every one of the remaining 25 is in `tests/`.
Like `internal/cache` and unlike `pkg/utils`, `pkg/recovery`, and `pkg/status`, this package
needed no production change to make the annotations safe. Each test constructs its own `Server`,
`status.NewTracker`, `health.NewTracker`, and `prometheus.NewRegistry`; requests go through
`httptest.NewRequestWithContext(t.Context(), ...)` and `httptest.NewRecorder()` rather than a
socket, so no two tests share a handler, a registry, or a port. `TestServerShutdown` is the one
test that binds, and it binds `localhost:0`.
Mutation-checked rather than assumed, because the point of the annotation is that a parallel
subtest still reports the case that failed: changing `server.go`'s `version = "unknown"` default
to `"dev"` produces
--- FAIL: TestHandleInfo/version_defaults_to_unknown_when_not_set
server_test.go:481: Expected version='unknown', got dev
and nothing else. Restored, with an empty `git diff --stat`. `go vet` clean, `-race -count=2`
clean.
Refs #179
…e tests package The last 25 `paralleltest` findings, all in `tests/`. `golangci-lint run` is now at 0 issues, which closes #179. This package was the one flagged as likeliest to hold genuine shared state, and it did — though not where expected. `MockPredictiveBackend.GetObject` incremented an `int64` under `mu.RLock()`. An RLock is held by every concurrent reader simultaneously, so that is a plain data race between two readers, not a write protected by a mutex. Confirmed with a throwaway probe before changing anything: eight goroutines calling `GetObject` report a read at `predictive_cache_test.go:38` against a write at the same line. `PredictiveCache`'s prefetch workers call the backend concurrently with the test's own goroutines, so `TestPredictiveCache_ConcurrentAccess` reaches it. It survived a suite that runs entirely under `-race` because nothing reads `GetStats` — the increment's only observable effect was the race. Both counters are `atomic.Int64` now. The second change is an ordering contract rather than a bug. `fuse_test.go`'s two parent tests held `defer writeBuffer.Close()`, and a parent's deferred functions run when the parent *function* returns — which, for a test with parallel subtests, is before those subtests resume. Verified by execution rather than assumed: a parallel subtest observes a variable set by the parent's `defer`, while a `t.Cleanup` registered alongside it runs afterwards. `vfs.Writer.Close` is only `FlushAll` today, so nothing broke, but the subtests were writing through a closed writer by contract. Both are `t.Cleanup` now. Nothing else needed changing. The integration suite keeps its state on the testify suite value under one `os.MkdirTemp`; the metrics collector builds its own registry and mux and binds `127.0.0.1:0`; `TestConcurrentAccess` and the two predictive concurrency tests each build their own cache. Mutation-checked at the write path's defining defect: dropping the destination offset in `ExtentList.Splice` reproduces H7 and fails --- FAIL: TestWriteBufferUnit unit_test.go:155: expected "sync data", actual 9 zero bytes Two narrower mutations to the same loops were identity transforms, because adjacent extents coalesce and the base-fragment path is not on this test's route. Recorded because a mutation that changes nothing demonstrates nothing. Restored with an empty `git diff --stat`. `go vet` clean, `-race -count=3` clean. Closes #179
Test-only dependency; go.mod and go.sum are the entire diff and no production code references it. The S3 conditional-write behaviour #282 is built on was re-probed on the new version rather than assumed stable across five releases, since that issue's Testing section says to verify before starting. A throwaway probe against `testaws.Start`, since deleted, on both versions: 1. If-None-Match:* absent -> success 2. If-None-Match:* present -> 412 Precondition Failed 3. body after failed CAS -> "v1" (unmodified) 4. If-Match correct etag -> success 5. If-Match stale etag -> 412 Precondition Failed 6. If-Match absent key -> 404 Not Found Identical on v0.87.0 and v0.92.0. Case 6 is the one that matters: 404 and not 412, which is the distinction #282 makes load-bearing — a lost race means recompute and retry, a vanished object means the state being updated is gone, and an emulator collapsing both to 412 would let a caller conflate them with every test still green. Case 3 matters for the same reason: a failed precondition that modified the object would make the mechanism unusable. So #282 has no remaining external dependency. substrate#397 is closed and implemented; substrate#540, the 409-Conflict outcome, is still open and belongs to the retry path rather than to PutObjectIf's own contract. `go build ./...` clean. `-race` clean across the full suite, including the three packages that actually exercise substrate: internal/testaws, internal/storage/s3, internal/difftest.
Four conflicts, all in tests both sides had independently improved, and
three of the four would not compile if resolved to main's side:
- internal/cache/persistent_test.go — main added an outer tmpDir that the
body never uses (each subtest makes its own), so it would be an unused
variable. Kept this branch's plain t.Parallel().
- pkg/api/server_test.go (x2) — kept NewRequestWithContext(t.Context(), …)
over plain NewRequest, so the request dies with the test.
- pkg/health/health_test.go — both sides fix the same bug. Kept the side
that drives the component through transitionState, which already arms
nextProbe (health.go:469-474); main's side hand-assigns State and
nextProbe and can therefore drift from production.
- pkg/recovery/recovery_test.go — main's DegradedState literal leaves
`config` undefined and mismatches every assertion below it
("test-component", "read-object: boom", AttemptCount, RecoveryBackoff).
Kept markDegraded through the production path.
Also deletes .golangci.yml's paralleltest exclusion for
pkg/utils/debug_mode_test.go, which arrived from main via #374. Its
rationale said "#373 tracks giving the manager a constructor … which is
the fix that makes the exclusion removable" — this branch is that fix:
NewDebugManager exists (debug_mode.go:60) and the file now has 19
t.Parallel() calls. Leaving the exclusion would suppress a linter that
has nothing left to report.
Second sync: #374 and #375 both landed after this branch's last merge. - go.mod / go.sum — kept substrate v0.93.0 over main's v0.92.0. Same bump, this branch is one release ahead; `go mod tidy` is clean at v0.93.0. - CHANGELOG.md, three regions — two were both-sides additions to the same section, kept in full. The third is the substrate entry both sides wrote: kept the v0.93.0 text, which also carries the v0.93.0-only finding that If-None-Match and If-Match sent together answer 412. Also corrects a paragraph #375 left true-when-written and false-on-merge. It said "#373's fix plan also called for deleting a .golangci.yml exclusion for debug_mode_test.go. There is no such exclusion" — accurate when #375 was cut, but #374 added that exclusion, and merging main into #375 deleted it. Rewritten to say what actually happened, since the interesting fact is that merge order decided whether a dead suppression survived.
Part of #179.
intrange37 → 0 andmodernize2 → 0; the lint total goes 570 → 531.Independent of #372 and #374 — branched off
mainatbc16b62, so the three can merge in any order.What changed
Applied with
golangci-lint --fixrather than a hand-written transform: the fixer knows which loops it cannot safely rewrite, and a regex overfor i := 0;does not.Eight of the 39 findings were never ours
The
flattednpm package ships a Go port under its own package directory, so once anything runsnpm installindocs-platformorsdks/javascript,./...picks up two copies of it — sixintrangeand bothmodernizefindings, in a file nobody here can edit..golangci.ymlnow excludes/node_modules/by path.That is the same exclusion
scripts/coverage-gate.shgrew for the same two directories (#372), and that one is what made these visible: the copies showed up as unfloored packages at 0.0% first.Verified in the way that distinguishes the exclusion from the fixer — after the run, both vendored files still contain their three old-style loops each, so the findings went away without
--fixrewriting a dependency's source. Anolintdirective in someone else's package was never an option.Why
range b.Nand notb.Loop()29 of the 31 in-repo sites are
for i := 0; i < b.N; i++in benchmarks.b.Loopis the Go 1.24+ form and would also make the adjacentb.ResetTimer()calls redundant — but that is a semantic change to what each benchmark measures, and the concern that would have forced it does not apply.Settled by probe rather than preference:
modernize'sbloopanalyzer is present in the bundled binary (golangci-lint 2.12.2) and does not fire onrange b.N, even when explicitly enabled viasettings.modernize.enable: [bloop]. So this trades no finding for another.The benchmarks were run rather than assumed to still iterate —
-benchtime=10xreports 10 iterations and real per-op timings across every touched package.The two sites that are not benchmarks
Both are the outer loop of an adjacent-comparison sort over
len(x)-1—internal/distributed/coordinator.go:932andinternal/health/monitor_test.go:547. This is where the transform could change behaviour:rangeevaluates its bound once, where the three-clause form re-evaluated it every iteration.Equivalent here because the bodies swap elements without changing length, and
rangeover a negative int does zero iterations exactly asi < -1would — measured, since an empty slice makes that bound-1.Both mutation-verified:
LoadBalancersort (range 0)TestLoadBalancer_LeastLoadfails:got [n1], want [n2]TestAlertManager_GetRecentAlertsfailsThe second needed a probe first. A mutation that deletes an assertion loop passes by construction, so the useful check was whether the loop runs at all — it makes two comparisons over three alerts rather than being vacuous.
Verification
go build ./...,go vet ./..., andgo vet -tags=integrationon the tagged packages: cleango test -race ./...: 36 packages ok, no failures, two runsgofmt -lon every changed file: cleangolangci-lint config verify: passes, and rejects a typo in the newpaths:key (additional properties 'pathz' not allowed) — so the exclusion cannot be silently misspelled into a no-opCHANGELOG.mdadds zero markdownlint findings (362 before, 362 after)