Skip to content

fix(agent,proxy): prune stale-netns pods + supervisor crash-fast-fail - #245

Merged
bpalermo merged 2 commits into
mainfrom
feat/agent-prune-stale-netns
Jun 19, 2026
Merged

bpalermo merged 2 commits into
mainfrom
feat/agent-prune-stale-netns

Conversation

@bpalermo

Copy link
Copy Markdown
Owner

Problem (diagnosed on talos worker-01)

A missed CNI DEL left 7 stale pod files in the agent's registry after the pods' netns were torn down. The agent generated each pod's per-pod cluster with NetworkNamespaceFilepath pointing at a nonexistent netns, pushed it via CDS, and Envoy segfaulted opening the dead netns — every epoch:

failed to open netns file /run/aether/netns/930bd2c…: No such file or directory
→ Caught Segmentation fault

The hot-restart supervisor mislabeled the crash as a base-id bind collision and looped silently for ~4.5 min (90 × 3s) before giving up; a fresh pod re-read the same stale files and crashed identically — a cross-pod wedge. (Notably not an orphan process: the proxy supervisor is the container's PID 1, so an Envoy can't outlive its pod.)

Fix

Agent — self-heal + visibility:

  • The ghost sweep now prunes storage entries whose netns no longer exists (RemoveResource + drop the listener via snapshotCache.RemovePod); the dead pod's registry endpoints then fall through to ghost deregistration. New metric aether.agent.ghost_sweep.stale_pruned + trace attribute surfaces these missed DELs.
  • LoadListenersFromStorage skips a missing-netns pod, so a stale entry can't poison the snapshot at startup before the first sweep runs (the worker-01 window). netnsExists is an overridable package var for tests.

Proxy supervisor — fail fast instead of masquerading:

  • Distinguish a fatal signal crash (SIGSEGV/SIGABRT/SIGBUS/SIGILL) from a clean bind-collision exit (errno 98, no signal). A crash gets a small budget (maxCrashRetries=5, ~15s) instead of the 90-retry bind-collision budget, so a deterministically crashing Envoy surfaces as CrashLoopBackOff in seconds — alertable, not silent.

Tests

Stale-pod prune (storage entry removed + endpoint deregistered, live pod kept); LoadListenersFromStorage skips missing-netns; isCrashSignal classification (real SIGSEGV vs clean exit vs success/non-exec). Full build, agent suite (15/15), lint, format pass.

Notes

  • worker-01 was recovered manually (delete the 7 stale files + restart its agent — the agent's fsnotify doesn't cross bind mounts, so it needed a re-read). This PR makes that self-healing.
  • Out of scope: the underlying missed-CNI-DEL cause (the sweep now cleans up after it); the Envoy NULL-deref on a missing netns (an upstream Envoy hardening matter — we now never feed it a dead netns).

🤖 Generated with Claude Code

bpalermo and others added 2 commits June 19, 2026 19:35
…l in the supervisor

A missed CNI DEL can leave a pod's registry file behind after its netns is torn
down. The agent then generates that pod's per-pod cluster referencing a
nonexistent netns path, pushes it via CDS, and Envoy SEGFAULTs opening the dead
netns on every epoch — the supervisor mislabels the crash as a base-id bind
collision and loops silently for ~4.5 min. (Diagnosed on talos worker-01,
2026-06-19; root cause: 7 stale registry files referencing gone netns.)

Agent (self-heal + visibility):
- Ghost sweep now prunes storage entries whose network namespace no longer exists:
  RemoveResource + drop the listener (snapshotCache.RemovePod); its registry
  endpoints then fall through to ghost deregistration. New metric
  aether.agent.ghost_sweep.stale_pruned (+ trace attribute) surfaces the missed
  DELs.
- LoadListenersFromStorage skips a pod whose netns is missing, so a stale entry
  can't poison the snapshot at startup before the first sweep runs (the worker-01
  failure window). netnsExists is an overridable package var for tests.

Proxy supervisor (fail fast instead of masquerading):
- Distinguish a fatal SIGNAL crash (SIGSEGV/SIGABRT/SIGBUS/SIGILL) from a clean
  bind-collision exit (errno 98, no signal). A crash gets a small retry budget
  (maxCrashRetries=5, ~15s) instead of the 90-retry bind-collision budget, so a
  deterministically crashing Envoy surfaces as CrashLoopBackOff in seconds.

Tests: stale-pod prune (storage removed + endpoint deregistered, live kept);
LoadListenersFromStorage skips missing-netns; isCrashSignal classification
(SIGSEGV vs clean exit vs success/non-exec error).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Pihqn5RmVPhV9HTdBnqbvY
…sters

RemovePod deletes the whole listenerEntry — the inbound/outbound listeners AND
the per-pod app/health clusters that carry the netns (the actual segfault
trigger). The comment said only "listener"; tighten it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Pihqn5RmVPhV9HTdBnqbvY
@bpalermo
bpalermo merged commit 3866c66 into main Jun 19, 2026
14 checks passed
@bpalermo
bpalermo deleted the feat/agent-prune-stale-netns branch June 19, 2026 22:46
bpalermo added a commit that referenced this pull request Jun 22, 2026
…262)

RemovePod removed local storage LAST, gated behind a fatal, request-context-bound
UnregisterEndpoints (and the listener removal). So a canceled request ctx (the
plugin's del timeout, a kubelet cancel, or agent SIGTERM — the xDS server
force-stops in-flight RPCs after ShutdownTimeout) OR a transient registrar
outage (observed during a registrar roll: UnregisterEndpoints fails with
"context canceled") made the handler return BEFORE storage.RemoveResource —
leaving a ghost storage entry whose netns pin lingers (so the #245 stale-netns
guard can't prune it) and whose listener is re-emitted on agent restart against
a dead netns. This is the prevention root cause behind the prober/edge
connection_error degradation.

Make DEL mirror AddPod (which stores first + treats registration as best-effort):
- Run the removal on a detached context (context.WithoutCancel) so request-ctx
  cancellation can't skip it.
- Remove LOCAL STORAGE FIRST — the authoritative local truth. It's the only fatal
  error (kubelet retries the DEL). Once gone, the liveness loop can't resurrect
  the endpoint and the ghost sweep deregisters whatever is left in the registry.
- Listener removal + endpoint deregistration are now BEST-EFFORT (logged, not
  fatal); the snapshot rebuild / restart drops the listener and the ghost sweep
  reconciles the registry. The deregister is bounded (unregisterTimeout) so it
  can't hang the DEL when the registrar is rolling.

Tests: the old "unregister failure returns error" case now asserts the DEL is
tolerated (SUCCESS); new TestRemovePodDurableDeleteOnCanceledCtx proves storage
is still removed with an already-canceled ctx AND a down registrar.

This is the prevention layer; the storage<->pods reconcile (cure) and the
startup taint (cold-start) are separate PRs on #261.


Claude-Session: https://claude.ai/code/session_01N7oY7W8oDXrqDzFgoZh25S

Co-authored-by: Claude Opus 4.8 <[email protected]>
bpalermo added a commit that referenced this pull request Jun 22, 2026
…sue #261) (#264)

The ghost sweep reconciled the registry against local storage but never
reconciled local storage against the node's real pods, so two desync classes
went uncured (talos worker-01, 2026-06-22):

  - Orphan ghost: a missed CNI DEL that left the netns bind-mount pin behind.
    netnsExists() stats the lingering pin and reports present, so the existing
    stale-prune never removed it; the agent kept emitting a listener bound to a
    dead netns (prober-vhbp8) — a connection sink and a latent #245 segfault.
  - Missing pod: a live, mesh-managed pod with no storage entry (a lost CNI ADD)
    that therefore had no listener and 100% connection_error (prober-k7vsm), and
    never self-healed.

The agent's manager cache is already scoped to spec.nodeName=<this node>, so
listing the node's pods is local and cheap (no new RBAC — it already has
pods get/list/watch). The sweep now:

  - Prunes a stored pod when EITHER its netns is gone (existing) OR its
    Kubernetes pod no longer exists — by pod identity, regardless of a lingering
    pin. The pruned pod's registry endpoint then falls through to ghost
    deregistration as before. If the pod list fails we skip prune-by-absence
    (an empty list would nuke every entry) but still run the netns prune.
  - Surfaces live, Running, mesh-managed pods that storage has no entry for: the
    agent can't synthesize the CNI data to self-heal, so it emits a metric +
    warning (the pod must be rolled) instead of silently serving no listener.

New metrics: ghost_sweep.orphans_pruned, ghost_sweep.missing_storage. Tests:
TestSweepPrunesOrphanedPods (lingering-pin orphan pruned + ghost-deregistered,
live pod kept) and TestIsMeshManagedK8sPod; existing sweep tests keep a nil
k8sClient and skip the pod reconcile via a defensive guard.

This is the cure layer; the guaranteed-delete reorder (#262) is the prevention
and the startup taint (#263) closes the cold-start window.


Claude-Session: https://claude.ai/code/session_01N7oY7W8oDXrqDzFgoZh25S

Co-authored-by: Claude Opus 4.8 <[email protected]>
bpalermo added a commit that referenced this pull request Sep 16, 2026
…-sweep critical section (#772) (#782)

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

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

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

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]>
bpalermo added a commit that referenced this pull request Sep 16, 2026
…ds kept out of every snapshot (#796) (#798)

* fix(cni): CNI DEL no longer blocks on the agent — unpin on the normal delay and let the ghost sweep reconcile (#796)

CmdDel returned the DEL error whenever `sendRemovePod` failed, on the grounds
that unpinning a netns the agent had not yet ACKed reintroduced the Envoy
segfault of #112/#245. containerd retries a failed DEL forever, so when the
agent pod was simply *gone* the sandbox could never be torn down: the
Terminating pod kept its CPU request, the node's own replacement
agent/proxy/mesh-dns pods hit `Insufficient cpu`, and worker-03 ran unmanaged
for 12m47s (#796).

The premise no longer holds. The pinned proxy snapshot
(1.40.0-dev.20260904.13144fb) contains envoyproxy/envoy#45975 — an upstream dial
into a vanished netns is a `FailedToCreateConnection` pool failure (a clean `UF`)
instead of a nullptr deref — and envoyproxy/envoy#46503, which closes the second
crash site by making the active TCP/HTTP/gRPC health checkers record a `NETWORK`
failure rather than crash on the same dial. (#45976, opt-in netns validation at
config load, is in the snapshot too and stays OFF: it would turn a stale pod into
an LDS/CDS NACK, which is worse than a clean dial failure.) A stale per-pod
cluster now costs at most one failed request and an unhealthy host until the
agent prunes it.

CmdDel therefore classifies the failure instead of blanket-returning it:

- `agentUnreachable` — the socket file is gone, or the RPC came back
  `codes.Unavailable` / `DeadlineExceeded` / `Canceled`, or an unwrapped
  ENOENT/ECONNREFUSED reached us. Nothing answered, and nothing will ACK a
  retry: log WARN "agent unreachable at CNI DEL; unpinning on the normal delay
  and letting the ghost sweep reconcile", skip the DEL readiness probe (there is
  no agent to have removed the listener, so the probe can only burn its whole
  timeout), spawn the usual detached unpinner on `NetnsUnpinDelay`, and return
  nil so the sandbox teardown completes and the CPU request is released.
- any other RPC error — a live agent answered, still owns the pod's xDS
  resources, and will ACK a retry: unchanged behaviour, return the error and let
  containerd retry with the netns still pinned.

That second branch is bounded rather than infinite: a new conflist key
`netns_del_give_up_after_seconds` (`AetherConf.NetnsDelGiveUpAfter()`, default
5m, negative = give up at once) caps how long a live-but-erroring agent can hold
the node. The plugin process lives for exactly one CNI call, so the first
failure's timestamp is kept in a `<pin>.delfail` marker beside the netns pin;
past the bound the DEL degrades to the unreachable path. The marker is cleared
on a successful DEL and on the give-up path, and `sweepNetnsPins` now recognises
markers so CNI GC neither treats one as a pin nor resets the bound of a DEL that
is still being retried.

The pin and the unpin delay both stay. The window they cover is real even
without a crash: a hot-restart successor re-creates the pod's listeners, and
deferred dials (health checkers and pool drains were measured 10-13s after
removal under churn) still *fail* through a released pin — they merely fail
cleanly now instead of taking the node proxy down.

Seams for the tests in the following commit: `spawnDetachedUnpinFn` and
`delReadinessWait` indirect the process fork and the DEL probe.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* docs(cni,agent): the stale-netns dial is a clean failure now, not a segfault (#796)

Comments-only. Several of them still described the deleted-netns SIGSEGV as
current Envoy behaviour, which is what made "CNI DEL must block until the agent
ACKs" look mandatory rather than merely conservative. All three relevant fixes
are in the pinned proxy snapshot 1.40.0-dev.20260904.13144fb:

  - envoyproxy/envoy#45975 (2026-07-13) — the pool dial into a vanished netns
    returns FailedToCreateConnection / LocalConnectionFailure (a clean UF for
    that request) instead of a nullptr the caller dereferences.
  - envoyproxy/envoy#46503 (2026-08-11) — the active TCP/HTTP/gRPC health
    checkers, which build upstream connections directly and so still crashed
    after #45975, record a NETWORK health-check failure instead. This is the
    "cold-start health checkers dial immediately → proxy unbootable" case of
    #245.
  - envoyproxy/envoy#45976 (2026-08-27) — opt-in netns validation at config
    load. Also in the snapshot; stays OFF, because it would turn a stale pod
    into an LDS/CDS NACK, which is worse than a clean dial failure.

Rewritten:

  - cni/internal/plugin/netnspin.go — package comment: the crash is history,
    cites the three PRs and the snapshot, and states why the pin and the unpin
    delay stay. The window is still real (a hot-restart successor re-creating
    the pod's listeners; deferred dials measured 10-13s after removal), it is
    just the difference between those dials working and failing cleanly rather
    than between the node proxy living and dying. Also notes that CNI DEL no
    longer waits on the agent's ACK to unpin.
  - cni/internal/plugin/plugin.go — the ADD-side pin-failure fallback no longer
    calls the fallback "the old crash window".
  - cni/config/config.go — NetnsPinDisabled, NetnsUnpinDelaySeconds and
    defaultNetnsUnpinDelay: same correction, same citations. The pin is a
    data-plane-quality measure now, not a crash guard.
  - agent/internal/xds/cache/listener.go — the missing-netns skip in
    LoadListenersFromStorage KEEPS its behaviour; only the reason changes. It is
    no longer "this faults Envoy", it is "this config can never become correct
    again, so programming it buys nothing but health-check noise against a host
    that will never come back".
  - agent/internal/cni/server/ghostsweep.go — the sweep header and
    pruneStaleStoragePods: the stale entry a lost DEL leaves behind now also
    arrives via the #796 path (the plugin completes the DEL without the agent
    and leaves reconciliation here), and its cost is a clean failure plus an
    eternally unhealthy host rather than a crash.

The supervisor's crash budget (#245, agent/internal/proxy/hotrestart) is
untouched and stays as the last line of defence.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* test(cni): cover CmdDel against a missing, an erroring and a healthy agent (#796)

CmdDel had no direct test at all — the DEL path was only exercised through
CNIClient unit tests, which is why "the agent is gone" could keep returning the
dial error unnoticed. New cni/internal/plugin/cmddel_test.go drives CmdDel
end to end against a fake CNI service on a real Unix socket (the plugin builds
its own client from the netconf path, so bufconn cannot stand in), with two
seams added in the first commit stubbed out: spawnDetachedUnpinFn (no process
forked, the scheduled target and delay recorded) and delReadinessWait (counted,
never run).

  (a) TestCmdDelAgentUnreachableSucceedsAndUnpins — socket path absent: DEL
      returns nil, the unpin is scheduled on the pin path with the ordinary 60s
      delay, the readiness probe is NOT awaited, and no marker is written.
      THIS TEST FAILS ON MAIN. Verified by restoring the pre-fix classification
      locally: "Received unexpected error: failed to remove pod from agent: rpc
      error: code = Unavailable desc = ... dial unix .../absent.sock: connect:
      no such file or directory".
  (b) TestCmdDelAgentErrorRetriesAndMarks — socket present, agent answers
      codes.Internal: DEL returns the error, nothing is unpinned, and the
      <pin>.delfail marker is written with a parseable first-failure timestamp.
  (c) TestCmdDelAgentErrorPastGiveUpDegrades — same, with a marker 10m old
      against the 5m default: DEL returns nil, the unpin is scheduled, the
      marker is removed.
  (d) TestCmdDelAgentOKUnchanged — agent ACKs: RemovePod reached it with the
      right pod name, the DEL readiness wait ran exactly once, the unpin is
      scheduled, no marker.

Plus the edges that make the bound trustworthy rather than decorative:
TestCmdDelAgentErrorWithinGiveUpStillRetries (a young marker does not degrade
the DEL, and a later attempt must not refresh the timestamp the bound is
measured from), TestCmdDelClearsStaleMarkerOnSuccess (or the next container to
reuse the ID starts with an already-expired bound),
TestSweepNetnsPinsHandlesDelMarkers (CNI GC must not mistake a marker for a pin
— unpinning one would silently reset the bound of a DEL still in flight — and
must take an orphan's marker with the orphan), and
TestAgentUnreachableClassification, a table over the classifier itself
including the wrapped-status forms CmdDel actually receives.

cni/config: TestNetnsDelGiveUpAfter and TestNetnsDelGiveUpAfterFromNetconf pin
the 5m default, the negative "give up at once" spelling and the conflist key.

Also corrects one stale comment in netnspin_test.go that still called a dial
through a released pin a segfault.

Verification: bazel test //cni/... passes; the three touched test targets pass
under --config=race --runs_per_test=3 (image targets are excluded from the race
run — rules_go refuses race instrumentation with cgo disabled).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* fix(agent): keep stale-netns pods out of EVERY snapshot, not just the first (#796, #717)

An experiment against the pinned proxy (1.40.0-dev.20260904.13144fb, Envoy
source 13144fb) settled what a dangling `network_namespace_filepath` does on the
LISTENER path, which is the one case envoyproxy/envoy#45975 and #46503 do not
cover:

  - A listener whose netns file is missing is REJECTED, not fatal:
    `listener_create_failure+1`, `lds.update_rejected+1`, process alive, manager
    still usable. No crash anywhere.
  - But a HOT-RESTART SUCCESSOR asked (LDS) to create such a listener NACKs the
    whole SotW response and comes up with ZERO listeners — every listener on the
    node, not just the stale one — and the port dies when the parent finishes
    draining. `createListenSocket()` jumps into the netns BEFORE it calls
    `duplicateParentListenSocket()` (the netns jump wraps the entire
    `createListenSocketInternal()` body, parent handoff included), so a listener
    that rode the previous handoff fine is silently dropped at the next one.
  - An in-place LDS MODIFY of such a listener is ACCEPTED: `hasCompatibleAddress`
    matches on the netns string and the socket factory is cloned, so
    `createListenSocket()` is never called and the dangling path stays invisible
    until a remove+re-add or a hot restart.

So the agent must not put a stale-netns pod in any snapshot. The existing skip in
`LoadListenersFromStorage` only covers startup, and the window it does not cover
is exactly the one #796 opens routinely: CNI DEL now completes without the agent,
so between the unpin and the ghost sweep's next pass (≤60s) the entry sits in
`c.listeners` with a netns that no longer exists — and that is precisely when a
proxy roll is likely, since the agent being absent usually means the node is
rolling.

  - `SnapshotCache.staleNetns` (reusing the existing `netnsExists` seam) is
    consulted in `meshListeners()` and `appClusters()`, so neither the per-pod
    listeners nor the per-pod app/health clusters (which carry the same netns)
    reach a generation. One stat per pod per regeneration.
  - WARN `skipping pod with missing network namespace in snapshot generation`
    is rate-limited to once per pod (`staleNetnsWarned`, its own mutex — the
    read paths hold only `listenerMu.RLock`), and forgotten on RemovePod so a
    reused netns can warn again. Without the limit a stale entry would log on
    every regeneration for a minute.
  - New counter `aether.agent.snapshot.stale_netns_skipped`, incremented once
    per stale pod per generation from the listener pass only (appClusters
    applies the same filter but must not double-count), and SEEDED AT ZERO at
    registration like the #638 discriminators — an unseeded counter that is
    never incremented never appears in Prometheus, and "no series" grades the
    same as "zero".

The ghost sweep still owns the actual prune; this only keeps the bad config out
of the wire in the meantime. The load-time skip stays.

Tests (agent/internal/xds/cache/stalenetns_test.go): two pods registered with
live namespaces, one netns then removed → the snapshot carries only the live
pod's listeners AND only its per-pod clusters, counter 1, one WARN naming the
pod; three generations → counter 3, still one WARN; after RemovePod the counter
stays (a counter keeps the evidence, it does not reset), and a healthy node
exports an explicit zero.

Verification: bazel test //agent/internal/xds/cache:all passes, and the cache +
cachemetrics targets pass under --config=race --runs_per_test=3.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* refactor(cni): split the pin-sweep loop body out of sweepNetnsPins (#796)

Teaching the sweep about `.delfail` markers pushed sweepNetnsPins to a cognitive
complexity of 21, over the repo's gocognit threshold of 15 (the #556 campaign's
target), so `--config=lint` failed the build. The per-entry decision — marker,
pin still backing a valid attachment, or orphan to release — moves into
sweepPinEntry, which is the whole of the added branching and reads better on its
own anyway. No behaviour change; the sweep tests cover it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* docs: runbook section for a stuck Terminating pod and stale netns entries (#245, #796, #717)

The #796 outage had no runbook entry, and the #245 stale-netns story was only in
code comments and agent memory. New troubleshooting section
"A pod is stuck `Terminating`, or a node has stale netns entries", covering both
symptoms of one mechanism (a CNI DEL that never completed):

  - Symptom A, the sandbox that will not tear down: what it looks like, why the
    Terminating pod's retained CPU request starves that node's own DaemonSets,
    and why priority cannot break the loop (the scheduler refuses to preempt on
    a node with a terminating pod). Then what the plugin now does instead —
    the two classes of DEL failure, the WARN each emits, the
    `netns_del_give_up_after_seconds` bound and its `<pin>.delfail` marker — so
    the reader knows that a pod STILL stuck means either a live agent refusing
    the removal or a failure outside aether. Commands to tell which, before
    force-deleting.
  - Symptom B, stale storage entries for pods that no longer exist: expected
    after the unreachable path, self-healing, do not hand-edit the registry.
    The three layers that heal it (the load-time skip, the per-generation skip,
    the ghost sweep) and the metrics to watch:
    `aether_agent_ghost_sweep_stale_pruned_total` and the new
    `aether_agent_snapshot_stale_netns_skipped_total`, both seeded so a flat
    zero is a real reading, with the usual false-zero warning about the metric
    family name.
  - Why the stale entry is no longer dangerous on the upstream side
    (envoyproxy/envoy#45975, #46503 in the pinned snapshot; #45976 deliberately
    off) — and why the LISTENER side still needs the agent to filter: a
    hot-restart successor asked to create a listener in a vanished netns NACKs
    the whole LDS response and comes up with ZERO listeners, while an in-place
    LDS modify of the same listener is silently accepted, so "LDS is being
    accepted" must not be read as "no stale netns" (#717). Envoy-side stats to
    check after a roll.

docs/configuration.md: the netconf keys the plugin reads but `cni-install` does
not write, including the new `netns_del_give_up_after_seconds`.

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]>
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