Skip to content

fix(storage,cni): storage owns its values; bound and unwind the ghost-sweep critical section (#772) - #782

Merged
bpalermo merged 3 commits into
mainfrom
fix/772-a3-cni-server-cache-and-sweep
Sep 16, 2026
Merged

bpalermo merged 3 commits into
mainfrom
fix/772-a3-cni-server-cache-and-sweep

Conversation

@bpalermo

Copy link
Copy Markdown
Owner

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, 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.

fix(cni): bound and unwind the ghost sweep's critical section (#772, 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.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

bpalermo and others added 3 commits September 15, 2026 20:11
…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
@bpalermo
bpalermo merged commit 3508299 into main Sep 16, 2026
20 checks passed
@bpalermo
bpalermo deleted the fix/772-a3-cni-server-cache-and-sweep branch September 16, 2026 00:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant