Repository navigation
feat(s3): a write that happens only if an assertion about the key holds (#282) - #379
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.
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.
Test-only dependency; go.mod and go.sum are the whole diff. Re-probed the conditional-write semantics rather than assuming a patch release left them alone, because #282's PutObjectIf contract is being written directly against these answers. All six behaviors are identical to v0.87.0 and v0.92.0, including If-Match against an absent key answering 404 rather than 412 — the distinction that decides whether a caller recomputes and retries or concludes the state it was updating is gone. The probe gained a seventh case this time, and it settled a design question rather than confirming one: If-None-Match:* and If-Match sent together answer PreconditionFailed. S3 evaluates both headers instead of picking one, so that request can never succeed, which is why Precondition.Validate rejects the combination locally — a caller error at the call site is actionable, a remote 412 is indistinguishable from a lost race. Also worth recording because it cost a run: the first probe reported every case as "unseekable stream is not supported without TLS and trailing checksum", which looks like a substrate limitation and is not. The SDK computes an input header checksum and needs to rewind the body, so a minimal hand-rolled io.Reader fails before a request leaves the process. bytes.Reader is seekable and all seven cases then answered normally.
Backend.PutObjectIf is the primitive the coordination work is being rebuilt on:
Precondition{Absent: true} is a lease acquisition, Precondition{ETag: current} is
a compare-and-swap, and the store — not any of the contenders — decides which one
proceeds. Eight concurrent writers asserting absence of one key elect exactly one,
verified against both the emulator and real S3.
Most of this change is not about two HTTP headers. A precondition is the only thing
in this package whose *failure* is the outcome its caller wants, and almost every
mechanism the backend wraps a request in — the retryer, the circuit breaker, the
health tracker — is built to treat a failed request as evidence of trouble.
ErrorThreshold is 3, so counting a lost race as a service failure would take writes
offline for every contender under exactly the contention the precondition exists to
arbitrate. So ErrCodePreconditionFailed is a non-failure in errors.IsServiceFailure,
which both the tracker and the breaker consult, and it is absent from
retry.DefaultConfig's retryable set: the answer is definitive, and retrying spends
MaxAttempts requests to be told the same thing. ErrConditionalConflict is retryable.
That asymmetry is now asserted in pkg/retry, because PutObjectIf deliberately does
not wrap itself in a retryer — a CAS caller has to re-read state and recompute its
bytes, a loop only it can run — so nothing in the S3 package could fail if the
classification were wrong. Verified: it was the one mutation of eight that survived.
An absent key is ErrCodeObjectNotFound, not a precondition failure, and preserving
that fixed a real defect found by execution. S3 answers 404 to an If-Match against a
missing key, but the AWS SDK does not model NoSuchKey among PutObject's typed errors
— an unconditional PutObject cannot produce one — so the code arrives as a bare
smithy.APIError, falls past translateError's typed arms to its pessimistic default,
and became ErrCodeStorageRead: a service failure degrading s3-writes and moving the
breaker toward open, for a key that is simply not there. A caller that cannot tell a
lost race from a deleted object retries forever against a key nobody will recreate.
The same gap applied at CompleteMultipartUpload, where a declined conditional write
reported STORAGE_READ until a conditional translator was wired in there too.
A conditional write above MultipartThreshold is still conditional. The assertion can
only be evaluated at CompleteMultipartUpload, because parts are not an object until
assembled, so the large path carries it on a different request than the caller's
data and completeMultipartUpload now returns the ETag it previously discarded. The
cost is inherent: a losing conditional multipart write has already transferred every
part. The deferred abort covers that, asserted through ListMultipartUploads against
real S3, since an orphaned upload's parts are billed and invisible to ListObjects.
Whether the endpoint evaluates preconditions at all is established by attempt, once,
and cached — not read from configuration. The probe is an If-Match no object can
satisfy against a key expected absent, and the answer it wants is a 404: that shape
writes nothing, and it catches the dangerous direction, because a store that accepts
conditional headers and ignores them answers with a *success*, having created the
object. Anything the probe cannot classify leaves the capability absent, and
PutObjectIf then refuses rather than falling back to an unconditional write — a
fallback would turn "exactly one node performs this transition" into "every node
does", silently, at the moment it matters most. Ceph RGW documents conditional
headers for GET/HEAD only; Wasabi is unverified and treated the same until probed.
PutObject and PutObjectIf share one prepareUpload, so they cannot disagree about the
checksum, the compressor, or the metadata map. Had they each computed their own, a
conditional write would have been one edit away from storing an object whose
objectfs-sha256 did not describe its bytes.
Tested against internal/testaws rather than a mock, because a mock evaluating a
precondition against its own in-process map agrees with its caller by construction
and would exclude nobody; against real AWS under -tags=integration, because every
claim here is about S3's semantics rather than ObjectFS's; and against httptest
endpoints that misbehave in specific ways, the only way to reach the
ignores-preconditions case. Mutation-verified in eight directions: dropping either
header on either path, delegating the 404, reclassifying a precondition failure as a
service failure or as retryable, removing the capability gate, and making the probe
fail open each break a named test.
pkg/types is floored at 100 and leaves the no-statements block: #282 gave it its
first function bodies, and TestNoStatementPackagesStillHaveNone caught the
transition on the commit that made it, which is what that test is for.
Closes #282
…f-282 # Conflicts: # CHANGELOG.md
All three are in #282's own files. The contextcheck one is the only one with a design claim behind it, and the claim is verified rather than asserted: probeConditionalWrite on a cancelled context reports a capable endpoint as not-capable (measured against an httptest endpoint that does evaluate preconditions — "context canceled" in the detail, ConditionalWrite false). Since Capabilities caches through a sync.Once and fails closed, threading a caller's ctx in would let one writer's cancellation make conditional writes permanently unavailable for the whole process. Suppressed with that rationale; the probe bounds itself with capabilityProbeTimeout instead. The waitgroupgo rewrite uses done.Go and deliberately leaves `start` an explicit WaitGroup: it is a gate waited on inside each goroutine, not a counter of them, which is not what Go models. Mutation-verified that the rewrite did not weaken what it tests — dropping applyPrecondition still yields 8 winners where the test wants exactly 1.
|
Merged
No production Go code came in with the merge (main contributed Verified on the merged tree:
The merge surfaced three lint findings in this branch's own files, fixed in 27f27c8. The The Now |
The runs created for this branch during the incident never materialized as jobs: run 31127479636 reports status=queued with zero jobs and run_attempt=1 despite a `gh run rerun --failed` being accepted, and its one reported failure (`coverage`) recorded zero steps while showing an assigned runner — the signature GitHub's 22:18Z update named as "runners being assigned jobs that are no longer valid". Nothing about the tree changed. The incident was mitigated at 00:06Z and Actions is operational, so an empty commit is the cheapest way to get a clean dispatch without cancelling runs that are still nominally the required checks. The coverage failure was verified non-real three ways before this: zero steps executed, CI's exact command reproduced locally (CGO_ENABLED=1, -timeout 20m, no -race) passing with the gate at 36 packages above their floor, and GitHub naming this exact failure mode.
Runs 31126521849 (CI) and 31126521846 (Security) were created at 18:57Z during the incident and never materialized as jobs: both report status=queued with zero jobs and run_attempt=1, despite a `gh run rerun --failed` being accepted at 20:25Z. Their three cancelled checks — Security Scan, docs-site, and fuzz-smoke (./internal/storage/s3, FuzzRoundTrip) — each recorded steps=0 after sitting queued 77-87 minutes, which is the queue timeout GitHub's incident warned about rather than any finding. The other 27 checks on this PR passed. Nothing about the tree changed. The incident was mitigated at 00:06Z and the same approach on #379 dispatched immediately, so this is a clean re-dispatch rather than a fix.
…luck (#179) (#374) * test: t.Parallel across seventeen files, and one test that passed by luck (#179) 278 of the paralleltest/tparallel backlog cleared: 570 lint findings to 299. t.Parallel() on every test and subtest in pkg/errors, pkg/status, pkg/health, pkg/recovery, pkg/retry, pkg/api, pkg/utils, pkg/types, internal/cache and internal/metrics. CLAUDE.md already required this; the finding count was the gap between the requirement and the tree. Each package ran under -race -count=2 after the change with its coverage checked against its floor, because parallelizing a test that shares state is a way to make it pass less often rather than a way to make it faster. Two packages resisted, and both are why this was worth doing rather than suppressing. pkg/health's TestTracker_CanRead had a real order dependency. It wrote a component's State directly and asserted what CanRead answered, but State alone does not decide that: admissionState admits one probe against a refusing component once nextProbe has elapsed, and reports StateDegraded to get that probe past the gate. So State=StateUnavailable with a zero-value nextProbe — always in the past — reads as readable, a combination the tracker never produces, since RecordError sets both fields and the test set one. One tracker shared across the table concealed it. The first subtest to reach a refusing state took the probe path, pushing nextProbe ProbeAfter into the future, and every later subtest then read raw state and agreed with the table. Giving each subtest its own tracker — the isolation t.Parallel requires — removed the accident and the unavailable case failed with CanRead() = true, want false. Fixed by setting nextProbe alongside State in the shape RecordError leaves it, and verified by deleting that line and watching the case fail. No production defect: the tracker's own path sets both fields together. What was broken is a test that could not have caught it if they came apart. pkg/utils/debug_mode_test.go's 19 findings cannot be fixed by a t.Parallel at all. DebugManager is a sync.Once singleton with no exported constructor, and RecordEvent fans every event out to all open sessions, so a session's event count depends on what every concurrently-open session recorded. Measured: "Expected 1 event, got 17", and five other counts inflated by siblings' traffic, with no data race — the locking is correct and the broadcast does what it is written to do. Excluded in .golangci.yml with that reasoning and filed as #373, rather than silenced with a t.Parallel that would leave the tests sequential in effect and the lint green. * ci: re-trigger workflows stranded by the 2026-08-06 Actions outage Runs 31126521849 (CI) and 31126521846 (Security) were created at 18:57Z during the incident and never materialized as jobs: both report status=queued with zero jobs and run_attempt=1, despite a `gh run rerun --failed` being accepted at 20:25Z. Their three cancelled checks — Security Scan, docs-site, and fuzz-smoke (./internal/storage/s3, FuzzRoundTrip) — each recorded steps=0 after sitting queued 77-87 minutes, which is the queue timeout GitHub's incident warned about rather than any finding. The other 27 checks on this PR passed. Nothing about the tree changed. The incident was mitigated at 00:06Z and the same approach on #379 dispatched immediately, so this is a clean re-dispatch rather than a fix.
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.
Closes #282. CAS-1: the foundation the rest of the coordination series sits on.
What this is
Backend.PutObjectIf(ctx, key, data, meta, cond) (etag, error)— a write that lands only if anassertion about the key's current state holds.
Precondition{Absent: true}is a lease acquisition,Precondition{ETag: current}is a compare-and-swap. Eight concurrent writers asserting absence ofone key elect exactly one, verified against both the emulator and real S3.
A new method rather than a changed signature, per the issue:
PutObjecthas one productionimplementation and — it turned out — seven test doubles, not the five the issue named
(
tests/posix_test.godoes not exist;internal/archive/vfs_test.go,internal/distributed/coordinator_test.go×2, andinternal/vfs/writer_test.gowere not listed).Another instance of predicted signatures being wrong.
What most of the change is actually about
Not two HTTP headers. A precondition is the only operation in this package whose failure is the
outcome its caller wants, and the retryer, circuit breaker, and health tracker are all built to
treat a failed request as evidence of trouble.
ErrorThresholdis 3, so counting a lost race as aservice failure would take writes offline for every contender under exactly the contention the
precondition exists to arbitrate.
ErrCodePreconditionFailedis a non-failure inerrors.IsServiceFailure, which both the healthtracker and
circuit.defaultIsSuccessfulconsult — one authority for both mechanisms.retry.DefaultConfig's retryable set: the answer is definitive.ErrConditionalConflictis retryable, because S3 could not order the write against a concurrentone and the caller's view may still be current.
PutObjectIfis deliberately not wrapped in the retryer. A CAS caller has to re-read stateand recompute its bytes; that loop is only its own.
Two real defects found by execution
1. A conditional 404 was a service failure. S3 answers 404 to
If-Matchagainst a missing key,but the AWS SDK does not model
NoSuchKeyamongPutObject's typed errors — an unconditionalPutObjectcannot produce one. So the code arrives as a baresmithy.APIError, falls pasttranslateError'sisErrorType[*s3types.NoSuchKey]arm to its pessimistic default, and becameErrCodeStorageRead: degradings3-writesand moving the breaker toward open, for a key that issimply absent. A caller that cannot tell a lost race from a deleted object retries forever against
a key nobody will recreate.
2. The same gap at
CompleteMultipartUpload. A declined conditional multipart write reportedSTORAGE_READrather than a precondition failure, with substrate having correctly declined it. Foundwhen the first run of
TestPutObjectIfAbsentAboveTheMultipartThresholdIsStillConditionalfailed.Neither was reachable by reading.
A large conditional write is still conditional
A precondition can only be evaluated at
CompleteMultipartUpload— parts are not an object untilassembled — so above
MultipartThresholdthe assertion travels on a different request than thecaller's data, and
completeMultipartUploadnow returns the ETag it previously discarded. Withoutthis, a conditional write over the threshold would silently become unguarded: every contender uploads
its parts, every Complete lands, and the lease belongs to whoever finished last.
The cost is inherent — a losing conditional multipart write has already transferred every part — so
the deferred abort matters more here than anywhere. Asserted through
ListMultipartUploadsagainstreal S3, since an orphan's parts are billed and invisible to
ListObjects.Capability by attempt, and refusal rather than fallback
The probe is an
If-Matchthat no object can satisfy against a key expected absent, and the answerit wants is a 404. That shape writes nothing, and it catches the dangerous direction: a store
that accepts conditional headers and ignores them answers with a success, having created the
object — which is exactly the endpoint a config flag or URL heuristic would call capable. A non-hex
ETag is used because the probe key is only expected absent.
Anything the probe cannot classify leaves the capability absent, and
PutObjectIfthen refuses.A fallback to an unconditional PUT would turn "exactly one node performs this transition" into
"every node does", silently. Same reasoning the read path already follows in refusing a
Content-Encodingit cannot decode. Ceph RGW documents conditional headers for GET/HEAD only;Wasabi is unverified and treated the same until probed.
Probed lazily and once: every backend pays construction, including ones that will never issue a
conditional write.
One
prepareUploadPutObjectandPutObjectIfshare it, so they cannot disagree about the checksum, the compressor,or the metadata map. Had they each computed their own, a conditional write would have been one edit
away from storing an object whose
objectfs-sha256did not describe its bytes — a seam defect ofexactly the shape that let 32,680 lines of tests miss ~45 others.
Testing
Three layers, each for something the others cannot reach:
internal/testaws(13 tests) — a mock evaluating a precondition against its own in-process mapagrees with its caller by construction and would exclude nobody.
-tags=integration(5 tests, all passing inus-west-2) — every claim here isabout S3's semantics rather than ObjectFS's. Confirms the 404-not-412 behavior, that
CompleteMultipartUploadevaluates the header, and that AWS arbitrates an 8-way race to exactlyone winner.
httptestendpoints that misbehave (in-package, followingpool_health_test.go) — the onlyway to reach an endpoint that ignores preconditions, which
testawscannot supply.Mutation-verified in eight directions, each breaking a named test: dropping
If-None-Matchonthe single-part path · on the multipart path · dropping
If-Match· delegating the 404 totranslateError· flippingErrCodePreconditionFailedto a service failure · removing thecapability gate · making the probe fail open · adding
ErrCodePreconditionFailedto the retryableset.
The eighth is worth calling out: it survived the first pass, because
PutObjectIfis not wrappedin a retryer so nothing in the S3 package consults that set. It is now covered by
TestDefaultConfigClassifiesTheTwoConditionalOutcomesDifferentlyinpkg/retry, which fails on themutation.
pkg/typesleaves the no-statements blockPrecondition.ValidateandIsZeroare its first function bodies.TestNoStatementPackagesStillHaveNonecaught the transition on the commit that made it — which iswhat that test exists for. Floored at 100 with its own tests, including the Absent+ETag rejection,
which is measured rather than defensive: substrate v0.93.0 and real S3 both answer 412 to a request
carrying both headers.
Gates
go test -race ./...— cleanAWS_PROFILE=aws AWS_REGION=us-west-2 go test -race -tags=integration ./internal/storage/s3/— cleanmake lint·go vet ./...·go vet -tags=integration ./...— clean./scripts/coverage-gate.sh— clean,pkg/typesat 100.0% against its new floorNext in the series
#283 (a lease over this), #284 (removing the
executeStrongConsistencyfan-out), #285, plus #129.