Skip to content

fix(agent): hold xDS, hold the taint, and mean it when identity is ready (#740) - #743

Merged
bpalermo merged 2 commits into
mainfrom
fix/740-pr3-hold-xds-taint-bundle
Sep 7, 2026
Merged

bpalermo merged 2 commits into
mainfrom
fix/740-pr3-hold-xds-taint-bundle

Conversation

@bpalermo

@bpalermo bpalermo commented Sep 7, 2026

Copy link
Copy Markdown
Owner

PR 3 of #740. Fixes the three findings from the on-cluster validation of #741
(talos-main rev209 / chart 0.92.9-1559e83, 2026-09-07 19:14–19:28Z, verdict
PARTIAL). #741's core claim held — the agent survived a 6m41s SPIRE blackout
with 0 restarts, never fatal, waiting ladder and metrics exactly as designed —
but three assertions in its body did not survive contact with the cluster.

F1 — a restarted agent loses the node's data path (regression vs. the crash loop)

Observed. mesh_dns non-success over the window: +5,083, all of it from
prober-rw6z8 = main-worker-03; every other node exactly 0.
AetherProberHTTPErrorBurst CRITICAL fired at 19:18:55Z. liveness stayed at
0 of 298,495 and aether_mesh_dns_records was 14 on all five nodes — DNS was
never implicated.

Mechanism. With no SVID the fresh agent cannot handshake to the registrar, so
PreListen's bounded registry-ready wait expires, the local-only fallback fires,
and the agent pushes that snapshot — replacing a complete one and evicting
every cross-node endpoint. echo has no replica on w03, so ~95% of that node's
probes failed for the whole outage. The crash loop this replaced never did that:
a dying agent publishes nothing, so Envoy kept its last config and the node kept
working. The exposure is not "SPIRE is down" but "SPIRE is down AND that node's
agent restarts"
— exactly the power-failure scenario #740 is about.

Fix. PreListen holds while identity is pending instead of falling through:

holding xDS until this agent has an SVID; Envoy keeps its current configuration  elapsed=15s
…
identity acquired; generating the initial snapshot  held=6m41.2s

The socket is not opened, so Envoy keeps its configuration exactly as it did
under the crash loop. From the moment identity exists, the registry wait and its
local-only fallback apply unchanged. Mid-life is already correct and is left
alone
: once a snapshot is published the cache keeps it, so a registrar that
goes away later costs nothing (confirmed in retryInitialRegistryLoad + the
refresher; no change).

F2 — the taint escalation is a fight between two controllers

Observed. The controller's guard armed aether.io/agent-not-ready at
19:19:38.9Z (29.9s after NotReady — the 30s grace is right), and the agent's own
agent-taint-remover removed it ~50 ms later, repeating every 30s for eight
cycles. The node was tainted ~50 ms per 30s: effectively never.

Mechanism. SPIRE was deliberately excluded from the #667 taint gate, so the
remover saw socket + chained satisfied and cleared a taint the controller had
armed for a check it could not see.

Fix. The remover now consults the same readiness aggregate the kubelet
polls
(agentReadiness.Err()), so both controllers read one verdict. The
socket + chained conditions keep their #667 semantics and are still conjunctive.
This is only safe because spire-server, spire-agent and the SPIFFE CSI driver now
tolerate the taint (k8s-talos-main #45, applied 2026-09-07) — the deadlock
argument that kept SPIRE out of the gate no longer applies. values.yaml and the
runbook now say those tolerations are required, not advisory.

F3 — recovery signalled 2m11s early

Observed. SVID at 19:23:11.0Z, svid_ready=1, pod Ready 19:23:14Z — but mTLS
clients kept failing x509svid: could not get X509 bundle until 19:25:22.0Z,
and the prober error bleed stopped at that same instant.

Mechanism, two parts. (a) Readiness flipped on the SVID alone; an mTLS peer
needs the SVID and the bundle for its trust domain. (b) The gRPC ClientConn's
own reconnect backoff — invisible to the app-level loop, whose logged backoff
stayed ~1.0–1.2s — had reached its ~120s cap after an outage's worth of failed
handshakes and was answering new RPCs from the cached failure instead of dialling.
Nothing polls a ClientConn out of that.

Fix. Readiness = SVID AND bundle (firstIdentity; the WaitingSource
publishes its source only when both are servable, so HasSVID, /readyz, the
xDS hold and the registrar's IdentityReady all mean the same thing). And the
registrar client is woken on identity — ResetConnectBackoff() plus a wake that
cuts the retry sleep short:

identity acquired; reconnecting the registrar client immediately rather than waiting out its backoff

Also: the withheld readiness reason

/readyz?verbose prints spire-svid failed: reason withheld — controller-runtime
redacts checker errors, so the useful text is unreachable from the endpoint an
operator would curl. Each check now logs its reason once per transition:

WARN  spire-svid readiness failing   reason="no SPIRE SVID after 2m10s (socket /run/secrets/…)"
INFO  spire-svid readiness passing

Runbook updated with all of the above.

Negative controls

Tests

TestPreListen_HoldsUntilIdentity (registry not consulted, PreListen does not
return, then proceeds once identity lands) · TestPreListen_IdentityAlreadyHeld ·
TestReconcileReadinessGate (held past the dwell while the SPIRE gate fails,
released once it passes) · TestAgentReadinessErr / …LogsTransitions (one
verdict, one line per transition, silent steady state) ·
TestFirstIdentityRequiresBothHalves · TestNotifyIdentityReadyCutsTheRetrySleep
(30s backoff cut to <2s on both retry paths) ·
TestWatchLoop_ConnectsImmediatelyWhenIdentityArrives (first successful watch
attempt ~1s after the peer becomes reachable).

Re-validation recipe

Tier 1 on main-worker-03 again (the no-local-replica node — the blast radius
is why it was chosen the first time), per #740's plan: pre-flight the SVID TTL
(abort under 30m), scale spire-server to 0, wait 60s, delete that node's
spire-agent and aether-agent pods, then scale back to 1. Grade from
attestation, not from the scale command.

Expect:

  1. The node's mesh_dns errors stay at 0 through the outage (they were
    +5,083 last time) — Envoy keeps its config because nothing is pushed. Log
    shows holding xDS until this agent has an SVID and no
    registry unavailable for initial snapshot; starting with local-only config.
  2. The taint STAYS armed from ~2m30s after the agent goes NotReady until
    recovery — no removed startup taint lines during the outage, one at the end.
    Verify with the controller's guard log rather than a JSONPath loop (zsh mangles
    [?(@.key=="…")] silently).
  3. Readiness flips only when both SVID and bundle are present, and the
    registrar reconnects within seconds of it — the gap between identity acquired and the last could not get X509 bundle should be seconds, not the
    2m11s measured last time.
  4. Unchanged from fix(agent): wait for the SPIRE Workload API instead of dying on it (#740) #741: 0 restarts, source_restarts absent, one wait_seconds
    observation matching the log's elapsed, liveness non-success 0.
  5. spire-svid readiness failing/passing bracket the outage in the log, with
    the reason text.

Tier 2 (fleet) is now reasonable to run once Tier 1 is clean, since assertion 1
removes the per-node data-path loss that made it a fleet-wide outage last time —
still with echo scaled to every node.

Chart bumped 0.92.9 → 0.92.10 (values.yaml comment change is CI-enforced).

Follows #741. PR 2 (controller/registrar/edge) is in flight separately and does
not overlap these files.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

bpalermo and others added 2 commits September 7, 2026 16:47
…ady (#740)

The three findings from #741's on-cluster validation (talos-main rev209,
2026-09-07). None is a defect in what #741 set out to fix — the agent no longer
dies on a cold SPIRE, 0 restarts across a 6m41s blackout — but the first is a
regression against the crash loop it replaced.

F1. A restarted agent with no SVID cannot handshake to the registrar, so
PreListen's bounded registry-ready wait expires, the local-only fallback fires,
and the agent PUSHES that snapshot — replacing a complete one and evicting every
cross-node endpoint. On main-worker-03 (no local echo replica) ~95% of the
node's mesh_dns probes failed for the whole outage, +5,083 errors, while the
other four nodes were at exactly 0. The crash loop never did this, because a
dying agent publishes nothing and Envoy keeps its last config. PreListen now
holds while identity is pending — INFO `holding xDS until this agent has an
SVID; Envoy keeps its current configuration` every 15s with a rising elapsed —
and the registry wait plus its local-only fallback apply unchanged from the
moment identity exists. Mid-life is already correct and is untouched: once a
snapshot is published the cache keeps it.

F2. The controller's node-taint guard re-armed `aether.io/agent-not-ready` 30s
after the agent went NotReady, and the agent's own remover — gated on the CNI
socket and conflist chaining only (#667) — dropped it ~50ms later, eight times
in a row. The node was tainted for ~50ms per 30s, i.e. never. The remover now
consults the SAME readiness aggregate the kubelet polls, so both controllers
read one verdict; the socket+chained conditions keep their #667 semantics. This
is safe now that spire-server, spire-agent and the SPIFFE CSI driver tolerate
the taint (k8s-talos-main #45), which is why SPIRE was kept out of the gate
before.

F3. Recovery was announced 2m11s early: readyz `spire-svid` passed 3s after the
SVID landed while every mTLS client kept failing `could not get X509 bundle`.
Two causes, both fixed — readiness now means SVID AND the bundle for its trust
domain (the WaitingSource publishes its source only when both are servable), and
the registrar client is woken on identity, resetting the gRPC ClientConn's own
backoff (at its ~120s cap by then, answering from the cached handshake failure
rather than dialling) and cutting the retry sleep short.

Also: /readyz?verbose prints `spire-svid failed: reason withheld` because
controller-runtime redacts checker errors, so each check now logs its reason
once per transition — WARN `spire-svid readiness failing` / INFO `… passing`.
Runbook and the values.yaml toleration note updated; the tolerations are now
REQUIRED, not advisory.

`--spire-enabled=false` (#421) is byte-identical: no gate, no check, no hold.

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

# Conflicts:
#	agent/internal/cmd/BUILD.bazel
#	agent/internal/cmd/root.go
#	common/spire/BUILD.bazel
@bpalermo
bpalermo merged commit 8310818 into main Sep 7, 2026
18 checks passed
@bpalermo
bpalermo deleted the fix/740-pr3-hold-xds-taint-bundle branch September 7, 2026 20:00
bpalermo added a commit that referenced this pull request Sep 16, 2026
…e a watch-filter re-assert, atomic Diff+Replace, optimistic-lock taint patches (#772) (#781)

* fix(registry): hand out copies of the cached endpoint slices (#772, A3/S2)

The registrar client's watch goroutine mutates a service's endpoint slice in
place: `upsertLocked` overwrites `eps[i]` when an endpoint's IP already exists,
`removeLocked` left-shifts the tail over the hole. Both `ListEndpoints` and
`ListAllEndpoints` handed out that same slice — `ListEndpoints` returned the
cache's own slice header after dropping the RLock, and `ListAllEndpoints`
copied the map but aliased every value.

Consumers read them on another goroutine: `agent/internal/xds/cache/cluster.go`
builds CDS/EDS from both, and its cold-path RPC-fill appends into what it read.
This is not only a detector finding — a reader ranging the backing array while
the left-shift runs can see one endpoint twice and skip another, so it corrupts
EDS content.

- `registry/internal/registrar/registrar.go:385` and `:414`: `slices.Clone` the
  slice(s) under the read lock before returning.
- State the ownership contract in both method docs: the slice/map is the
  caller's copy, the `*registryv1.ServiceEndpoint` elements are shared and must
  be treated as immutable (no consumer mutates them today — the only in-place
  writes are the two cache mutators, which swap the pointer rather than edit the
  message — so a shallow copy is sufficient and a `proto.Clone` per endpoint is
  not paid on the xDS rebuild path).
- Note the in-place rewrite at `upsertLocked`/`removeLocked` so the coupling is
  visible from the mutating side too.

Verification: new `registry/internal/registrar/cache_alias_test.go` interleaves
a `ListEndpoints`/`ListAllEndpoints` consumer that appends and ranges with the
watch-apply path. Before the fix: 6 DATA RACE reports and both tests fail under
`--config=race`. After: `//registry/internal/registrar:registrar_test` passes
5/5 runs under `--config=race`; `//registry/...` and
`//agent/internal/xds/cache/...` green.

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

* fix(registry,registrar): never lose a watch-filter re-assert; diff+replace atomically (#772, A6d/S8/S13)

S8 — lost watch-filter re-assert (registry/internal/registrar/registrar.go).
The watch loop read the filter to assert in one filterMu critical section
(`currentFilter`) and published the new stream's canceller in another. A
`SetServiceFilter` landing entirely between the two read the PREVIOUS stream's
`streamCancel` — already spent — so its cancel was a no-op, while the loop went
on to open a stream carrying the filter it had read before the update. Nothing
then cancels that stream, so the node's new dependency set is never asserted
until the stream dies for some other reason: the #682 "demand-set change
invisible until the next roll" shape.

`assertFilter` now publishes the canceller and reads the filter under one hold
of filterMu, leaving only two interleavings: SetServiceFilter runs entirely
before (this stream carries the new filter) or entirely after (it sees this
stream's canceller and cancels it). `currentFilter` is gone; its one test caller
uses `assertFilter`.

S13 — Diff/Replace TOCTOU (registrar/internal/server). DECISION: fixed, not
documented-around. The fix is local and safe — one production caller
(`sync.go:168`) — so `Snapshot.DiffAndReplace` now holds `mu` across both halves
(`diffLocked` + `replaceLocked`; the exported `Diff`/`Replace` keep their own
locking for their remaining callers). Previously a `RegisterEndpoint` → `Apply`
landing between them was broadcast as ENDPOINT_ADDED and then erased by a
replacement computed before it existed, with no compensating REMOVED. That hole
was masked by `Syncer.writeBehind.Overlay` re-adding the intent — i.e. the
invariant was held by the write-behind queue, not by the snapshot, and the
legacy constructor path (writeBehind nil) had nothing holding it at all. The
masking relationship is now stated at `DiffAndReplace` either way.

Verification:
- `registry/internal/registrar/watch_filter_test.go`: drives the real watch loop
  against the in-process fake registrar and bursts filter updates at it; the
  fake holds every stream open, so a lost re-assert never self-heals. With the
  read and the publish split back into two critical sections (plus a
  `runtime.Gosched()` to widen a window that is otherwise a few instructions) it
  fails 2/10; with the fix, 10/10 green. Plus a unit-level invariant test over
  500 interleavings: a stream that asserted the stale filter must have had its
  canceller invoked.
- `registrar/internal/server/snapshot_toctou_test.go`: 500 interleavings of
  `DiffAndReplace` against a concurrent `Apply`; an endpoint absent from the
  snapshot afterwards must have been announced REMOVED. Fails 5/5 with the
  halves split (iteration 57 on the first run), passes 10/10 with the fix.
- `//registrar/...` and `//registry/...` green; `//registry/internal/registrar`
  green 5/5 under `--config=race`. `//registrar/internal/server:server_test`
  still trips the known pre-existing test-only race at `server_test.go:26`
  (report R2, owned by A2) under `--config=race` — unrelated to this change.

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

* fix(agent,controller): optimistic-lock both node-taint writers (#772, A6d/S37)

`spec.taints` has no patch-merge key, so `client.MergeFrom` emits the WHOLE
array. Both taint writers read the node and then patched it without an
optimistic lock, which makes every write a lost-update candidate: a taint added
between the Get and the Patch — by the controller's guard, a drain,
node-problem-detector — is silently reverted by a writer that never saw it, and
symmetrically for the guard reverting the agent's removal. #743 removed the
SEMANTIC taint fight (both sides now read the same readiness verdict); this is
its residual on the write path.

- `agent/internal/node/taint.go`: the removal moves into `dropTaint`, which
  patches with `client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})`
  and answers a 409 by re-reading the node and retrying via
  `retry.RetryOnConflict` (bounded — the precedent is
  `agent/internal/edge/gatewayapi/status.go:320`). A conflict that never clears
  is returned to controller-runtime, which requeues with backoff.
- `controller/internal/nodetaint/guard.go`: `armTaint` takes the node NAME and
  re-Gets inside the same retry, skipping the write when the taint is already
  present (idempotent, no duplicate taint).

Semantics are unchanged and deliberately so: the agent still holds the taint
while its readyz aggregate says not-ready and only ever removes it; the guard
still only ever adds it, and only after 30s with no Ready agent pod.

Verification: new `taint_conflict_test.go` / `guard_conflict_test.go` drive the
fake client through an interceptor that returns a 409 on the first Patch. They
assert the patch body carries a `resourceVersion` (i.e. is actually locked),
that the conflict is retried exactly once more, and that the end state is
right; plus a persistent-conflict case pinning the retry bound, and an
already-armed case for the guard's idempotence. Reverting both writers to plain
`MergeFrom` with no retry fails both new tests. `//agent/internal/node/...` and
`//controller/internal/nodetaint/...` pass 3/3 under `--config=race`.

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