Repository navigation
fix: etcd Close/watchLoop race, CNI watcher stop path, test races, and a scoped race CI gate (#772) - #776
Merged
Conversation
…#772) R1 in the 2026-09-15 races review, and the only production data race the detector found (`--config=race --runs_per_test=3` failed 2 of 3 runs on `//registry/internal/etcd:etcd_test`). `Close` cancelled the watch context and then immediately nil'd `r.client` and `r.watchCancel` without waiting for `watchLoop` to exit. `watchLoop` checks `ctx.Done()` and *then* dereferences `r.client` to re-establish the watch (etcd.go:200), so beyond the unsynchronised write/read pair there was a real nil-deref panic window on shutdown. `Close` was also unguarded, so two Closes raced each other. - `watchLoop` now takes a `done` channel and closes it on return. - `Close` cancels, waits on `done`, and only then closes the etcd client. The wait needs no context of its own: the loop honours cancellation on both select arms and clientv3 closes the watch channel when the watch context is cancelled, so the loop returns promptly and unconditionally. - `Close` no longer nils `client`; a post-Close call now fails with etcd's "client closed" error instead of panicking, and there is no unsynchronised write left for a concurrent reader to trip over. - `Close` is idempotent via `sync.Once` (with the result memoised so every caller sees the same error). - `Initialize`'s plain writes are documented as safe: every field the loop reads is written before the `go` statement that is itself the happens-before edge. Regression test `TestEtcdRegistry_CloseRacesWatchLoop` uses the package's existing testcontainers etcd fixture: it churns registry writes to keep the watch busy while three goroutines call `Close` concurrently, ten rounds. Verified it reproduces: against the old `Close` the test fails with `WARNING: DATA RACE` on the first round; with the fix `bazel test //registry/internal/etcd:etcd_test --config=race` passes. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
Finding S31 in the 2026-09-15 races review: `watchFiles` was the one select loop in the repo with no stop arm. It sent on an unbuffered `fileModified` (and `errChan`) with no ctx and no quit case, so if nobody was inside `Wait()` the goroutine parked in the send forever. `Close()` closed the fsnotify watcher, but a goroutine blocked in a send never returns to the select to notice — the goroutine leaked for the life of the process. That is exactly the production shape: `cni/internal/install/cniconfig.go` `getCNIConfigFilepath` does `defer watcher.Close()` and abandons `Wait` the moment its context is cancelled. - `Watcher` gains a `done` channel closed by `Close`; the watch loop selects on it in the outer loop and on both sends (`sendOrStop`). - `Close` closes `done` before the fsnotify watcher (the goroutine may be parked in a send that closing the watcher would not release) and is now idempotent via `sync.Once`. - `CreateFileWatcher` also closes `done` on the `watcher.Add` error path, where the caller never receives a `Watcher` to close. - The two per-channel cases move into `deliverEvent`/`deliverError`. Inlining the stop arms put `watchFiles` at cognitive complexity 19 against the repo's threshold of 15 (#556 campaign); split, it is well under. New `cni/internal/util/watcher_test.go` proves the exit by goroutine count (polled, with a stack dump on failure): a modification with no receiver, then `Close`, must return to baseline. Verified it reproduces — against the old blocking send the leak test fails with "goroutine leak: 4 goroutines, baseline 3". Also covers idempotent Close and that the new stop arm does not swallow real events (Wait still wakes on a modification, and still returns the ctx error on cancellation — asserted on its own quiescent watcher, since a select with a ready Events arm picks between arms at random). `bazel test //cni/internal/util:all //cni/internal/install:all --config=race --runs_per_test=10` green. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
R2/R3/R4 in the 2026-09-15 races review. All three fail deterministically under `--config=race` and are the reason `bazel test //... --config=race` could not be turned into a CI gate. No production code is touched. R2 `registrar/internal/server/server_test.go` — `fakeWatchServerStream.Send` appended to `sent` on the WatchEndpoints goroutine while the `require.Eventually` pollers ranged the same slice from the test goroutine (11 detector reports, one root cause). The fake now has a `sync.Mutex` and a `snapshot()` accessor returning a `slices.Clone`; every assertion goes through it, so the lock also supplies the happens-before edge for the response protos the server builds before each Send. R3 `prober/internal/prober/prober_test.go` — `TestProbeConnectionReuse` assigned `srv.Config.ConnState` *after* `httptest.NewServer` had already started serving, racing net/http's own reads on the serve goroutine (and risking the hook not taking effect at all). Switched to `httptest.NewUnstartedServer` → set `ConnState` → `Start()`. R4 `common/xds/callbacks_test.go` — `stubCallback.called` was a plain bool written by `PreListen` on the server's Start goroutine and polled by `assert.Eventually` in `server_test.go:123`. Now an `atomic.Bool`. Verified: `bazel test //registrar/internal/server:all //prober/internal/prober:all //common/xds:all --config=race --runs_per_test=3 --nocache_test_results` passes 3/3 on each (was 0/3). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
Phase A2's last piece: nothing in CI ran the Go race detector, so the
production etcd race (R1, fixed earlier in this branch) sat on main
undetected. `.bazelrc` already defined `test:race`; this wires it to a job.
The `race` job mirrors `test`'s setup and reuses the SAME bazel-diff impacted
lists, so it is scoped exactly like the other legs and an unrelated PR pays
nothing. It runs after `test` (so a red PR does not burn a second runner) and
in parallel with `integration`/`e2e`, and `ci` now lists it in `needs`.
Two legs, matching the review's methodology:
- every impacted Go test once;
- the 19 concurrency-heavy packages from the review at `--runs_per_test=3`.
That is not belt-and-braces: R1 reproduced only 2 of 3 runs and a single
pass missed it entirely.
Test EXECUTION stays on the runner: `--config=ci` pulls in `--config=remote`,
which sets `--strategy=TestRunner=local`. Only the race-instrumented compiles
go to RBE. That matters for the Docker-bound integration tests, which the
gate deliberately includes — the one production race ever caught lived in one.
The gate runs `kind(go_test, tests(//...))`, NOT `//...`. A literal
`bazel test //... --config=race` does not work in this repo: the race config
forces cgo on, and rules_go refuses it for the pure/static binaries the image
and chart targets link ("race instrumentation can't be enabled when cgo is
disabled"), so ~8 non-Go test targets fail analysis. They run no Go under
test and are not race candidates. The step fails loudly if that query comes
back empty rather than passing a gate over nothing.
Measured locally on the full impacted set (warm build cache, test caching
off): leg 1 = 43 s for 77 targets, leg 2 = 45 s for the 21 hot targets.
Both green, zero DATA RACE.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
bpalermo
added a commit
that referenced
this pull request
Sep 16, 2026
…review (#772) (#787) Phase E2 of the review: the docs were not wrong here, they were silent. Each addition below is sourced from the code or chart it describes. docs/configuration.md - New § 3 `prober` section (proposal 013, `charts/prober`): the binary's whole flag set with defaults from `prober/internal/prober/prober.go` DefaultConfig + `prober/internal/cmd/root.go`; the two metrics it exports (`aether_probe_requests_total`, `aether_probe_request_duration_seconds`), their tier/target/result attributes and the full `result` value set; why per-node identity is an OTel *resource* attribute rather than a metric label; and the chart's deployment shape (DaemonSet into a mesh-managed namespace, derived `config.aether.io/upstreams`, deliberately no CPU limit, #735). The prober takes none of the shared manager flags, which the section says. - `--lame-duck-max` (`10s`, #729) added to the `mesh-dns` flag list, with the successor-observation semantics and the derived terminationGracePeriodSeconds. - `--spire-wait-warn-after` (`2m`, #740) added to the agent identity flag list, with a paragraph saying it is a logging threshold everywhere except the node agent, where it doubles as the readiness dwell. - Chart values that shipped undocumented: `spire.waitWarnAfter`, `agent.meshDnsDaemon.{forwardPoolSize,lameDuckMax,debug}`, and a new `edge.config` table covering all 11 keys of the proposal-029 fleet-default EdgeConfig (`name`, `useRemoteAddress`, `headersWithUnderscoresAction`, `streamIdleTimeout`, `requestTimeout`, `idleTimeout`, `perConnectionBufferLimitBytes`, `http2.*` ×3, `http3.enabled`), sourced from values.yaml, `edge-defaultconfig.yaml` and `api/aether/config/v1/edge_config.proto`. The rest of the review's "28 undocumented keys" turned out to be false positives of its dotted-path matcher: `edge.httpsPort`, `edge.geoip.database.fileName`, `edge.gateway.tlsSecretNamespace`, `edge.admin.*`, `edge.service.*`, `edge.overload.*`, `edge.spire.clusterSpiffeID.*`, `registrar.service.*` and `proxy.hotRestart.adminUnresponsiveDeadline` are all already documented in combined table rows. CLAUDE.md / AGENTS.md - Binaries that existed but were listed nowhere: `agent/cmd/proxy-ready` (#673), `agent/cmd/mesh-dns-ready` (#683), `prober/cmd/prober` (proposal 013). - Packages that existed but were described nowhere: `common/spire` (the #740 identity-wait/readiness model), `agent/internal/identity`, `agent/internal/node` + `controller/internal/nodetaint` (proposal 033 taint lifecycle, split across its two writers), `agent/internal/cniconflist` (#645), `registrar/internal/replicator` (proposal 006 Phase 2). - The race detector next to the build/test commands, and the `scripts/go-deps-audit.sh` "reclassify, don't drop" rule next to `make deps-audit`. nogo and the `deps-audit` CI job were added by #773 and are not duplicated here. docs/runbook.md - New "The race gate" subsection under § 3 Test: the `--config=race` spelling from .bazelrc, the scoped and `--runs_per_test=3 --nocache_test_results` forms, why a bare `//...` run currently reports failures that are not yours (#772 phase A2), and why a clean run is not evidence of absence. - Cross-reference from the standalone-charts paragraph to the new prober section. The § "Go dependency hygiene" cross-reference from #769 was verified present and left alone. No race CI job is claimed: `.bazelrc` ships `--config=race` and the Makefile ships `make test-race`, but ci.yaml has no `race` job on main (it arrives with #776), so the docs describe only the commands that exist today. Verification: `bazel run //:format.check`, `bazel test //website:all` (the docs feed the site; its link/nav check passes), `bazel build //... //test/e2e:e2e_test`. Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr Co-authored-by: Claude Fable 5.1 <[email protected]>
bpalermo
added a commit
that referenced
this pull request
Sep 16, 2026
… tests, no sleeps in sync_test; stop proxy/*.md edits triggering Envoy releases (#772) (#788) * test: delete the two duplicate :server_integration_test targets (#772, C1) `//agent/internal/cni/server:server_integration_test` and `//agent/internal/xds/server:server_integration_test` added no assertions. Each declared a strict *subset* of the srcs of the sibling `:server_test` in the same package, and `:server_test` already lists `server_integration_test.go` itself — so every `TestIntegration_*` executed twice on a full `bazel test //...`. Re-proved on this tree with `comm -23 <(bazel query 'labels(srcs, <pkg>:server_integration_test)') <(bazel query 'labels(srcs, <pkg>:server_test)')`, empty for both packages: cni/server :server_integration_test = {pod_test.go, server_integration_test.go} :server_test = those + ghostsweep_lock_test.go, ghostsweep_test.go, identity_test.go, lifecycle_race_test.go, liveness_test.go, metrics_test.go, resubscribe_test.go, termination_test.go xds/server :server_integration_test = {server_integration_test.go, server_test.go} :server_test = those + identity_hold_test.go, initial_snapshot_test.go, odcds_test.go, refresh_identity_test.go, refresh_test.go No Go test file and no test function is removed: after the deletion `--test_filter=TestIntegration_` still runs 9 cases in cni/server and 4 in xds/server, from the surviving `:server_test` targets. The `integration` tag was the expensive part. `scripts/ci-impacted-targets.sh:41` selects the CI `integration` leg purely by `attr(tags, "integration", tests(//...))`, so any change touching either package scheduled a whole extra GitHub runner (checkout + setup-bazel + artifact download) to re-run tests the `test` leg had just run. Nothing in `.github/workflows/` or `bazel/` selects these targets by name, and the `integration` job is already conditional on `has_integration == 'true'`, so no workflow change is needed — the job simply stops being scheduled for agent-only changes. After the deletion the tag selects only the two genuine testcontainers targets: $ bazel query 'attr(tags, integration, tests(//...))' //registrar/internal/replicator:replicator_test //registry/internal/etcd:etcd_test (which also retires the false `no-remote-exec` justification comment on the deleted targets — neither imported testcontainers, and `.bazelrc:71` already pins every test action to the runner.) Verification: `bazel query` output above; both `:server_test` targets pass with `--test_filter=TestIntegration_`; `bazel run //:gazelle` produces no churn. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr * test(etcd): make -test.short actually Docker-free (#772, C1) `registry/internal/etcd/etcd_test.go` guards all 17 container-backed tests with `testing.Short()`, but `TestMain` started, waited on, and terminated the etcd container before `m.Run()` regardless — so `--test_arg=-test.short` skipped every test and still required a working Docker daemon and still paid the pull/start/readiness cost. Parse the test flags and check `testing.Short()` before touching testcontainers, exactly as `registrar/internal/replicator/replicator_test.go:29` already does. `flag.Parse()` is required: `testing.Short()` reads a flag value that is not populated until the test flags are parsed, and in `TestMain` that has not happened yet. The short path still runs the suite rather than exiting, because `TestEtcdRegistry_CloseWithoutStart` deliberately has no short guard — it closes a registry that was never started and needs no endpoint. #776's `TestEtcdRegistry_CloseRacesWatchLoop` does carry the guard and is unaffected. No production code and no test case changed. Verification: # short: Docker untouched $ docker ps -aq | wc -l -> 2 (before) $ bazel test //registry/internal/etcd:etcd_test --nocache_test_results \ --test_arg=-test.short --test_arg=-test.v PASSED in 0.1s (was ~4.6s) $ docker ps -aq | wc -l -> 2 (after, no etcd container ever created) 17 SKIP + 1 PASS (TestEtcdRegistry_CloseWithoutStart) # full: unchanged, 18/18 pass incl. #776's test $ bazel test //registry/internal/etcd:etcd_test --nocache_test_results --test_arg=-test.v PASSED in 4.4s, --- PASS: TestEtcdRegistry_CloseRacesWatchLoop Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr * test(proxy): delete the misnamed TestSortRoutesBySpecificity_HeaderCountRanksHigher (#772, C1) This is the one sanctioned test deletion in C1 (the tests report's move #10). `agent/internal/xds/proxy/edge_test.go:859` was named for `sortRoutesBySpecificity`, but it never called it — it cannot: that function is unexported and lives in a different package (`agent/internal/xds/cache/edge.go:90`). What the body actually did was build two routes with `BuildEdgeRoute` and assert that one ended up with two `HeaderMatcher` entries and the other with one, then comment "the route with 2 headers must sort before the route with 1" without asserting any ordering. So it tested header copying under a name that promised specificity ordering — the worst failure mode for a test, because the name is what a reader trusts when deciding whether a behaviour is covered. Both halves are already covered, properly, elsewhere: - header copying: `TestBuildEdgeRoute_HeaderMatch` (`agent/internal/xds/proxy/edge_test.go:730`) asserts the exact and regex `HeaderMatcher` shapes this one only counted. - specificity ordering: `agent/internal/xds/cache/edge_test.go` calls the real `sortRoutesBySpecificity` directly at :1030, :1051, :1157, :1171, :1185 and :1213 and asserts the resulting order. Deleting it rather than renaming it, because a rename would leave a third BuildEdgeRoute header-count assertion with nothing to say that `TestBuildEdgeRoute_HeaderMatch` does not already say more precisely. Verification: `bazel test //agent/internal/xds/proxy:proxy_test //agent/internal/xds/cache:cache_test` both pass. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr * test(registrar): synchronise sync_test on conditions, not on time.Sleep (#772, C1) `registrar/internal/server/sync_test.go` was the one package in the tree that consistently slept instead of waiting: 10 `time.Sleep` calls (30–200 ms) used as synchronisation, ~930 ms of hard-coded wall time and the target's only flake surface. A sleep that is long enough today is a flake on a loaded CI runner and dead time on every other run. Each one is replaced by the narrowest observable condition: - Waiting for the initial sync now uses `Syncer.Synced()`, the channel the production code already closes after the first successful cycle (`sync.go:184`) — exact, not approximate. `requireSynced` wraps it with a 5 s deadline. Used by InitialSync, VersionAdvancesOnSync, EmptyRegistryPopulatesEmptySnapshot, MultipleEndpointsAcrossServices, NoEventsAfterInitialSync, RegistryErrorOnSubsequentSyncDoesNotCrash and StopsOnContextCancellation. - BroadcastsChangesOnSubsequentSync waits for the event to reach the watcher (`len(eventCh) > 0`) rather than for two poll intervals to elapse. - RegistryErrorDoesNotCrash has no observable effect to wait on — a failing cycle closes neither `Synced()` nor the snapshot — so `mockRegistry` gains an atomic `listCalls` counter and the test waits for the call itself. - RegistryErrorOnSubsequentSyncDoesNotCrash's cycle counter `httpCalls` became an `atomic.Int64` so the test goroutine can read it; the test waits for two failing periodic cycles instead of 200 ms. - NoEventsAfterInitialSync waits for `2*len(syncedProtocols)` further list calls, i.e. two real cycles, derived from the production protocol list instead of hard-coded. The two remaining `time.After` calls are assertion deadlines (Start must return within 500 ms of cancellation), not synchronisation, and stay. The poll intervals of the two change-detecting tests drop 60 ms → 20 ms now that nothing depends on a sleep lining up with them. No production code changed and no test case was removed or renamed. Verification: $ bazel test //registrar/internal/server:server_test --runs_per_test=10 --config=race PASSED in 2.8s, Stats over 10 runs: max = 2.8s, min = 2.8s, dev = 0.0s $ grep -c time.Sleep registrar/internal/server/sync_test.go -> 0 TestSyncer subset, uncached: 1.2s -> 0.4s Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr * ci: stop a proxy docs edit from rebuilding Envoy (#772, C1) PR #773 changed one line of `proxy/README.md`. `proxy-release.yml`'s push trigger filters on `paths: ["proxy/**"]`, so the merge compiled Envoy on both RBE pools, pushed a new multi-arch image and opened chart-pin PR #786 — for a comment. `proxy.yml` had the same hole at PR time: its `changes` job's dorny/paths-filter pattern is also `proxy/**`, so a README-only PR ran the heavy compile on both arches before anyone could review it. Exclude Markdown under proxy/ from both. proxy-release.yml (GitHub-native `paths`): GitHub rejects `paths` and `paths-ignore` on the same event, so the exclusion has to be a negated pattern inside `paths`. GitHub evaluates the list in order and a later negative wins, so `"!proxy/**/*.md"` must follow `"proxy/**"`; the trailing workflow-self entry is unaffected because the negation does not match it. `proxy/**/*.md` covers `proxy/README.md` as well as nested files — in GitHub's filter patterns `**/` matches zero directories (their own cheat sheet lists `docs/README.md` under `docs/**/*.md`). proxy.yml (dorny/paths-filter@v4): the same `!` spelling would NOT work under the action's default quantifier. It ORs the compiled patterns, and picomatch compiles a leading `!` into "matches everything the positive pattern does not", so `'!proxy/**/*.md'` would match `.github/**`, `agent/**`, … and the filter would be permanently true. v4 ships `predicate-quantifier: 'some-with-excludes'` for exactly this: a file matches when at least one positive pattern matches it and no negated pattern does. Set it, then add the same `'!proxy/**/*.md'`. Verified against the action's own matching logic (filter.ts `isInclude` / `isExclude`, the latter being `excludes.some(m => !m(path))`) with picomatch: proxy/README.md -> false proxy/BUILD.bazel -> true proxy/docs/a.md -> false proxy/MODULE.bazel -> true agent/main.go -> false .github/workflows/proxy.yml -> true Exclusion is per changed file, so a PR touching both `proxy/README.md` and a real proxy source file still builds. The `proxy` gate job is `if: always()` (proxy.yml:120), so a docs-only proxy PR still reports the required check — same path a control-plane-only PR already takes. Verification: both files parse under `python3 -c 'import yaml,sys; yaml.safe_load(open(sys.argv[1]))'`; dorny behaviour simulated as above. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Phase A2 of #772.
fix(registry/etcd): wait for the watch loop before closing the client (#772)
R1 in the 2026-09-15 races review, and the only production data race the
detector found (
--config=race --runs_per_test=3failed 2 of 3 runs on//registry/internal/etcd:etcd_test).Closecancelled the watch context and then immediately nil'dr.clientand
r.watchCancelwithout waiting forwatchLoopto exit.watchLoopchecks
ctx.Done()and then dereferencesr.clientto re-establish thewatch (etcd.go:200), so beyond the unsynchronised write/read pair there was
a real nil-deref panic window on shutdown.
Closewas also unguarded, sotwo Closes raced each other.
watchLoopnow takes adonechannel and closes it on return.Closecancels, waits ondone, and only then closes the etcd client.The wait needs no context of its own: the loop honours cancellation on
both select arms and clientv3 closes the watch channel when the watch
context is cancelled, so the loop returns promptly and unconditionally.
Closeno longer nilsclient; a post-Close call now fails with etcd's"client closed" error instead of panicking, and there is no unsynchronised
write left for a concurrent reader to trip over.
Closeis idempotent viasync.Once(with the result memoised so everycaller sees the same error).
Initialize's plain writes are documented as safe: every field the loopreads is written before the
gostatement that is itself thehappens-before edge.
Regression test
TestEtcdRegistry_CloseRacesWatchLoopuses the package'sexisting testcontainers etcd fixture: it churns registry writes to keep the
watch busy while three goroutines call
Closeconcurrently, ten rounds.Verified it reproduces: against the old
Closethe test fails withWARNING: DATA RACEon the first round; with the fixbazel test //registry/internal/etcd:etcd_test --config=racepasses.fix(cni): give the file-watch goroutine a stop path (#772)
Finding S31 in the 2026-09-15 races review:
watchFileswas the one selectloop in the repo with no stop arm. It sent on an unbuffered
fileModified(and
errChan) with no ctx and no quit case, so if nobody was insideWait()the goroutine parked in the send forever.Close()closed thefsnotify watcher, but a goroutine blocked in a send never returns to the
select to notice — the goroutine leaked for the life of the process.
That is exactly the production shape:
cni/internal/install/cniconfig.gogetCNIConfigFilepathdoesdefer watcher.Close()and abandonsWaitthemoment its context is cancelled.
Watchergains adonechannel closed byClose; the watch loop selectson it in the outer loop and on both sends (
sendOrStop).Closeclosesdonebefore the fsnotify watcher (the goroutine may beparked in a send that closing the watcher would not release) and is now
idempotent via
sync.Once.CreateFileWatcheralso closesdoneon thewatcher.Adderror path,where the caller never receives a
Watcherto close.deliverEvent/deliverError. Inliningthe stop arms put
watchFilesat cognitive complexity 19 against therepo's threshold of 15 (ci(lint): ratchet gocognit threshold down from 109 toward 20 #556 campaign); split, it is well under.
New
cni/internal/util/watcher_test.goproves the exit by goroutine count(polled, with a stack dump on failure): a modification with no receiver,
then
Close, must return to baseline. Verified it reproduces — against theold blocking send the leak test fails with "goroutine leak: 4 goroutines,
baseline 3". Also covers idempotent Close and that the new stop arm does not
swallow real events (Wait still wakes on a modification, and still returns
the ctx error on cancellation — asserted on its own quiescent watcher, since
a select with a ready Events arm picks between arms at random).
bazel test //cni/internal/util:all //cni/internal/install:all --config=race --runs_per_test=10green.test: fix the three test-only races that block the CI race gate (#772)
R2/R3/R4 in the 2026-09-15 races review. All three fail deterministically
under
--config=raceand are the reasonbazel test //... --config=racecould not be turned into a CI gate. No production code is touched.
R2
registrar/internal/server/server_test.go—fakeWatchServerStream.Sendappended to
senton the WatchEndpoints goroutine while therequire.Eventuallypollers ranged the same slice from the test goroutine (11 detector reports,
one root cause). The fake now has a
sync.Mutexand asnapshot()accessorreturning a
slices.Clone; every assertion goes through it, so the lock alsosupplies the happens-before edge for the response protos the server builds
before each Send.
R3
prober/internal/prober/prober_test.go—TestProbeConnectionReuseassigned
srv.Config.ConnStateafterhttptest.NewServerhad alreadystarted serving, racing net/http's own reads on the serve goroutine (and
risking the hook not taking effect at all). Switched to
httptest.NewUnstartedServer→ setConnState→Start().R4
common/xds/callbacks_test.go—stubCallback.calledwas a plain boolwritten by
PreListenon the server's Start goroutine and polled byassert.Eventuallyinserver_test.go:123. Now anatomic.Bool.Verified:
bazel test //registrar/internal/server:all //prober/internal/prober:all //common/xds:all --config=race --runs_per_test=3 --nocache_test_resultspasses 3/3 on each (was 0/3).
ci: add a race gate to the ci fan-in (#772)
Phase A2's last piece: nothing in CI ran the Go race detector, so the
production etcd race (R1, fixed earlier in this branch) sat on main
undetected.
.bazelrcalready definedtest:race; this wires it to a job.The
racejob mirrorstest's setup and reuses the SAME bazel-diff impactedlists, so it is scoped exactly like the other legs and an unrelated PR pays
nothing. It runs after
test(so a red PR does not burn a second runner) andin parallel with
integration/e2e, andcinow lists it inneeds.Two legs, matching the review's methodology:
--runs_per_test=3.That is not belt-and-braces: R1 reproduced only 2 of 3 runs and a single
pass missed it entirely.
Test EXECUTION stays on the runner:
--config=cipulls in--config=remote,which sets
--strategy=TestRunner=local. Only the race-instrumented compilesgo to RBE. That matters for the Docker-bound integration tests, which the
gate deliberately includes — the one production race ever caught lived in one.
The gate runs
kind(go_test, tests(//...)), NOT//.... A literalbazel test //... --config=racedoes not work in this repo: the race configforces cgo on, and rules_go refuses it for the pure/static binaries the image
and chart targets link ("race instrumentation can't be enabled when cgo is
disabled"), so ~8 non-Go test targets fail analysis. They run no Go under
test and are not race candidates. The step fails loudly if that query comes
back empty rather than passing a gate over nothing.
Measured locally on the full impacted set (warm build cache, test caching
off): leg 1 = 43 s for 77 targets, leg 2 = 45 s for the 21 hot targets.
Both green, zero DATA RACE.
🤖 Generated with Claude Code
https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr