Repository navigation
fix(storage,cni): storage owns its values; bound and unwind the ghost-sweep critical section (#772) - #782
Merged
Conversation
…dary (#772, A3/S1) `agent/storage`'s RWMutex protects the map, not the values, so `GetAll` and `GetResource` handed every caller the cache's own pointer. Two goroutines then touched the same proto with nothing ordering them: - `agent/internal/cni/server/termination.go:114` — `cur.Terminating = true`, written in place by the termination watch under `lifecycleMu`; - `agent/internal/cni/server/liveness.go:95` — `pod.GetTerminating()`, read by the 5s liveness tick holding no lock at all (it released storage's RLock inside `GetAll`). `AddResource`'s own `protojson.Marshal` is a third concurrent reader of the same value. The type's doc claimed the implementation was "safe for concurrent access", which was true of the map and false of everything it contained. Fixed at the source (option (a) of the two the review offered) rather than by making the two call sites copy-on-write: the contract now is that the cache owns its values and every message crossing the boundary is deep-copied — `AddResource` caches a clone of what it is given, `GetResource`/`GetAll`/`loadAll` return clones of what they hold. Callers own what they get back and may mutate it freely; to persist a change they write it back with `AddResource`, which is exactly what termination.go already does. Documenting immutability instead would have left every future `GetAll` consumer one in-place write away from the same bug, with no test able to catch it. The cost is real but small, and was measured rather than assumed (`BenchmarkGetAll`/`BenchmarkGetResource`, added here, on a record carrying the label/annotation maps a meshed pod actually has): BenchmarkGetAll/1pods 7.0 us 1320 B 33 allocs BenchmarkGetAll/10pods 68.0 us 13203 B 321 allocs BenchmarkGetAll/50pods 296.3 us 66016 B 1601 allocs BenchmarkGetResource 7.4 us 1312 B 32 allocs The readers are a 5s liveness tick and a 60s ghost sweep over a node-local pod table, so at 50 pods/node that is ~0.3 ms every 5 s — and `AddResource` already marshals to JSON and fsyncs a file, next to which a clone is noise. `MockStorage` gets the same treatment: a double that hands two goroutines the same pointer when the real storage would not turns a concurrency test into a test of the double. While in the package doc, dropped its claim of "file watching via fsnotify" — there is no fsnotify anywhere in `agent/storage`. Tests: `agent/internal/cni/server/lifecycle_race_test.go` interleaves the two real call sites — the liveness tick reading the snapshot against the termination watch marking pods — with a deliberately slow health gateway so a pass spans the writes. Temporarily reverting only local.go+mock.go and running bazel test //agent/internal/cni/server:server_test --config=race \ --test_filter=TestLivenessReadRacesTerminationWrite --runs_per_test=5 fails 5 of 5 with `WARNING: DATA RACE`, naming exactly `termination.go:114` (write) against `liveness.go:95` (read); with the fix in place it passes. `agent/storage/isolation_test.go` does the same at the storage level (3 of 3 failures pre-fix) and pins the in/out isolation contract. Verification: `bazel test //agent/storage/... //agent/internal/cni/... --config=race --runs_per_test=3` green. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
…A6b/S19+S20) `sweepGhostEndpoints` took `lifecycleMu` at the top and held it — `defer Unlock` — across the entire pass: one registry RPC per endpoint in both directions, plus the Eviction API requests and the Event writes of the two self-heal paths, none of them with a deadline. Every CNI ADD/DEL that needs the lock (pod.go:218 and the whole RemovePod body) queues behind all of it, so a registrar that is rolling — or an apiserver that stalls — stretches a CNI DEL past the plugin's 5s `delTimeout` (cni/internal/plugin/client.go:21). A DEL that times out is a DEL that never tore the netns down, which is the documented route to the stale-netns Envoy SIGSEGV (#245). Two changes, both about the LOCK HOLD rather than the lock: 1. Every out-of-process call the sweep makes now has a deadline, sized off the plugin's own budget (new constants in ghostsweep.go): - lifecycleRegistryTimeout 2s — one registry RPC made while lifecycleMu is held. This is the worst case a CNI ADD/DEL can wait, so it sits well under the plugin's 5s: a DEL that queues behind one still has >3s of its own budget. Applies to the sweep's (de)registrations and, for S20, to the liveness loop's health re-registration (liveness.go) and the termination watch's drain marking and pool-close (termination.go), which are the same class with a smaller blast radius. - sweepListTimeout 10s — the authoritative registry listing, lock not held. - sweepAPITimeout 5s — the node pod List, the Eviction API request and the Event write, lock not held. Every one of these is best-effort (the sweep retries in 60s, the liveness loop in 5s), so a cut-off costs a retry and nothing else. 2. The pass is split into a plan half and an execution half. `planSweep` holds the lock across local work only — read storage, prune dead entries, drop their listeners, update the lifecycleMu-guarded streak maps, classify — and returns a `sweepPlan` of what to do. The execution half issues the RPCs with the lock released, re-taking it per mutation to re-validate and make ONE bounded call. Holding the lock across that one call is deliberate: the check and the registry mutation must be atomic against RemovePod, which holds the lock across "delete from storage, then unregister". Dropping it entirely would let the sweep blackhole an endpoint a CNI ADD just re-acquired, or resurrect one a DEL just removed (the R4 hazard of docs/proposals/002). So what shrinks is the hold — one call capped at 2s, with Go handing a starved waiter the mutex on release — not the atomicity. Re-validation is the other half of the split, because a plan is a snapshot: `deregisterGhost` re-reads storage and skips any endpoint whose IP is accounted for again (live or terminating), and `registerMissingEndpoint` re-reads the pod and skips it if it is gone or now terminating. Behaviour preserved deliberately: the eviction budget (`sweepEvictPerPass`) is spent at execution time, not plan time, so a PDB-blocked 429 still does not consume it; the two self-heal paths keep their order (stale-while-Running first) and both interlocks (#566 breaker, #667 unchained conflist); the breaker's hysteresis, fraction, relog rate-limiting and orphan carve-out (#670) are untouched and their tests pass unchanged. The node pod List now happens just before the lock instead of just inside it, which only makes the API cross-check marginally staler — it is already guarded by multi-pass hysteresis. Tests (agent/internal/cni/server/ghostsweep_lock_test.go): - TestSweepDoesNotBlockPodLifecycle — twelve ghosts against a registrar taking 150ms per deregistration (a ~1.8s pass); a CNI DEL issued once the sweep is in its execution half must complete in under 900ms and while the sweep is still mid-flight. On the pre-fix tree it fails with "CNI DEL waited 1.804117723s on lifecycleMu" and 12 of 12 deregistrations already done — i.e. the DEL waited for the whole sweep, which is S19 exactly. - TestSweepRegistryCallsAreBounded / TestTerminationRegistryCallsAreBounded / TestLivenessRegistryCallIsBounded — the registry double records the deadline on each call's context and asserts it exists and fits its budget. - TestSweepRevalidatesGhostBeforeDeregistering — a pod that races back into storage between plan and execution is not deregistered. Verification: `bazel test //agent/internal/cni/... //agent/storage/... --config=race --runs_per_test=3` green, including the 24 existing sweep tests. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
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 A3 (storage/CNI half) + A6b of #772.
fix(storage,cni): storage owns its values — deep-copy across the boundary (#772, A3/S1)
agent/storage's RWMutex protects the map, not the values, soGetAllandGetResourcehanded every caller the cache's own pointer. Two goroutines thentouched the same proto with nothing ordering them:
agent/internal/cni/server/termination.go:114—cur.Terminating = true,written in place by the termination watch under
lifecycleMu;agent/internal/cni/server/liveness.go:95—pod.GetTerminating(), read bythe 5s liveness tick holding no lock at all (it released storage's RLock
inside
GetAll).AddResource's ownprotojson.Marshalis a third concurrent reader of the samevalue. The type's doc claimed the implementation was "safe for concurrent
access", which was true of the map and false of everything it contained.
Fixed at the source (option (a) of the two the review offered) rather than by
making the two call sites copy-on-write: the contract now is that the cache owns
its values and every message crossing the boundary is deep-copied —
AddResourcecaches a clone of what it is given,
GetResource/GetAll/loadAllreturn clonesof what they hold. Callers own what they get back and may mutate it freely; to
persist a change they write it back with
AddResource, which is exactly whattermination.go already does. Documenting immutability instead would have left
every future
GetAllconsumer one in-place write away from the same bug, with notest able to catch it.
The cost is real but small, and was measured rather than assumed
(
BenchmarkGetAll/BenchmarkGetResource, added here, on a record carrying thelabel/annotation maps a meshed pod actually has):
The readers are a 5s liveness tick and a 60s ghost sweep over a node-local pod
table, so at 50 pods/node that is ~0.3 ms every 5 s — and
AddResourcealreadymarshals to JSON and fsyncs a file, next to which a clone is noise.
MockStoragegets the same treatment: a double that hands two goroutines thesame pointer when the real storage would not turns a concurrency test into a
test of the double. While in the package doc, dropped its claim of "file
watching via fsnotify" — there is no fsnotify anywhere in
agent/storage.Tests:
agent/internal/cni/server/lifecycle_race_test.gointerleaves the tworeal call sites — the liveness tick reading the snapshot against the termination
watch marking pods — with a deliberately slow health gateway so a pass spans the
writes. Temporarily reverting only local.go+mock.go and running
fails 5 of 5 with
WARNING: DATA RACE, naming exactlytermination.go:114(write) againstliveness.go:95(read); with the fix inplace it passes.
agent/storage/isolation_test.godoes the same at the storagelevel (3 of 3 failures pre-fix) and pins the in/out isolation contract.
Verification:
bazel test //agent/storage/... //agent/internal/cni/... --config=race --runs_per_test=3green.fix(cni): bound and unwind the ghost sweep's critical section (#772, A6b/S19+S20)
sweepGhostEndpointstooklifecycleMuat the top and held it —defer Unlock— across the entire pass: one registry RPC per endpoint in bothdirections, plus the Eviction API requests and the Event writes of the two
self-heal paths, none of them with a deadline. Every CNI ADD/DEL that needs the
lock (pod.go:218 and the whole RemovePod body) queues behind all of it, so a
registrar that is rolling — or an apiserver that stalls — stretches a CNI DEL
past the plugin's 5s
delTimeout(cni/internal/plugin/client.go:21). A DEL thattimes out is a DEL that never tore the netns down, which is the documented route
to the stale-netns Envoy SIGSEGV (#245).
Two changes, both about the LOCK HOLD rather than the lock:
Every out-of-process call the sweep makes now has a deadline, sized off the
plugin's own budget (new constants in ghostsweep.go):
held. This is the worst case a CNI ADD/DEL can wait, so it sits well under
the plugin's 5s: a DEL that queues behind one still has >3s of its own
budget. Applies to the sweep's (de)registrations and, for S20, to the
liveness loop's health re-registration (liveness.go) and the termination
watch's drain marking and pool-close (termination.go), which are the same
class with a smaller blast radius.
Event write, lock not held.
Every one of these is best-effort (the sweep retries in 60s, the liveness loop
in 5s), so a cut-off costs a retry and nothing else.
The pass is split into a plan half and an execution half.
planSweepholdsthe lock across local work only — read storage, prune dead entries, drop their
listeners, update the lifecycleMu-guarded streak maps, classify — and returns
a
sweepPlanof what to do. The execution half issues the RPCs with the lockreleased, re-taking it per mutation to re-validate and make ONE bounded call.
Holding the lock across that one call is deliberate: the check and the
registry mutation must be atomic against RemovePod, which holds the lock
across "delete from storage, then unregister". Dropping it entirely would let
the sweep blackhole an endpoint a CNI ADD just re-acquired, or resurrect one a
DEL just removed (the R4 hazard of docs/proposals/002). So what shrinks is the
hold — one call capped at 2s, with Go handing a starved waiter the mutex on
release — not the atomicity.
Re-validation is the other half of the split, because a plan is a snapshot:
deregisterGhostre-reads storage and skips any endpoint whose IP isaccounted for again (live or terminating), and
registerMissingEndpointre-reads the pod and skips it if it is gone or now terminating.
Behaviour preserved deliberately: the eviction budget (
sweepEvictPerPass) isspent at execution time, not plan time, so a PDB-blocked 429 still does not
consume it; the two self-heal paths keep their order (stale-while-Running first)
and both interlocks (#566 breaker, #667 unchained conflist); the breaker's
hysteresis, fraction, relog rate-limiting and orphan carve-out (#670) are
untouched and their tests pass unchanged. The node pod List now happens just
before the lock instead of just inside it, which only makes the API cross-check
marginally staler — it is already guarded by multi-pass hysteresis.
Tests (agent/internal/cni/server/ghostsweep_lock_test.go):
150ms per deregistration (a ~1.8s pass); a CNI DEL issued once the sweep is
in its execution half must complete in under 900ms and while the sweep is
still mid-flight. On the pre-fix tree it fails with "CNI DEL waited
1.804117723s on lifecycleMu" and 12 of 12 deregistrations already done —
i.e. the DEL waited for the whole sweep, which is S19 exactly.
TestLivenessRegistryCallIsBounded — the registry double records the deadline
on each call's context and asserts it exists and fits its budget.
storage between plan and execution is not deregistered.
Verification:
bazel test //agent/internal/cni/... //agent/storage/... --config=race --runs_per_test=3green, including the 24 existing sweep tests.🤖 Generated with Claude Code
https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr