Skip to content

fix(agent): wait for the SPIRE Workload API instead of dying on it (#740) - #741

Merged
bpalermo merged 1 commit into
mainfrom
fix/740-spire-startup-decouple
Sep 7, 2026
Merged

bpalermo merged 1 commit into
mainfrom
fix/740-spire-startup-decouple

Conversation

@bpalermo

@bpalermo bpalermo commented Sep 7, 2026

Copy link
Copy Markdown
Owner

Part 1 of #740 (the agent). PR 2 = controller/registrar/edge.

The mechanism

workloadapi.NewX509Source was called in exactly one place — common/spire/tls.go's
NewSourceWithTimeout, with the 25s SourceTimeout #668 introduced to turn the SDK's
unbounded first-SVID wait into a bounded one. Bounded, but still fatal: the agent
called it at root.go:243, before m.Start, so /healthz and /readyz were still
silent, and a SPIRE server that was itself still coming up — the normal state of a cold
boot — exited the process with failed to create SPIRE Workload API source: context deadline exceeded. On the 2026-09-07 power failure that cost 2–4 restarts on every
node and ~60s of mesh readiness, for a dependency that recovered on its own in 13s.

Nothing downstream ever needed the process to die:

  • the SPIRE→SDS bridge dials lazily and retries its streams forever,
  • nodeSource is already an interface whose GetX509SVID errors are retried,
  • the xDS cache skips upstream-mTLS injection until SetNodeIdentity lands, and Envoy
    tolerates the absent secret (feat(agent): add the inbound identity-binding discriminator (#638) #715),
  • go-spiffe reconnects mid-life on a context.Background() watcher, so only the one-shot
    creation was ever fatal.

What changed

common/spire — a narrow SVIDSource interface (x509svid.Source +
x509bundle.Source + Updated()); every TLS helper widened to it; the Source alias
kept, so the three call sites PR 2 will move still compile untouched. New
WaitingSource (waiting.go): a controller-runtime Runnable that creates the source in
a retry loop — 10s per attempt, jittered backoff 1s→30s, never fatal — serving
ErrNoSVIDYet until the first SVID and then delegating to the real source. A source
that connects but cannot serve an SVID is discarded and re-created (the only path that
increments source_restarts).

Agent — setupSpireSource → startSpireIdentity, in the same slot, returning
immediately. The trust domain is late-bound through a tiny atomic holder
(agent/internal/identity) seeded with the mesh domain — the only value that can work,
since peer authorization is scoped to it unconditionally — and reconcileSpireIdentity
folds in what SPIRE actually issued when the SVID lands (WARN + a merge-safe
LoadListenersFromStorage re-run if it ever differs). The bridge's node-SVID refresh
now also wakes on Updated(), so a late identity is served immediately instead of on
the next 30s tick. defer spireSource.Close() unchanged in shape.

Registrar client — Config.IdentityReady func() bool. A stream that cannot
handshake before the SVID exists logs INFO watch stream deferred until this agent has an SVID, counts no watch_errors, and does not escalate the backoff (only the usual
jitter). Waiting on our own certificate is not a registrar failure, and burying #700's
ERROR under a boot's worth of it is exactly what #712 removed.

Nothing in runAgent or PreListen is reordered (#700/#712), and
--spire-enabled=false (#421) is byte-identical: no source, no runnable, no log line.

The dwell decision

readyz gains spire-svid beside cni-chained, with a 2m dwell equal to the warn
threshold
— the non-obvious part. The controller's node-taint guard (proposal 033)
re-arms aether.io/agent-not-ready:NoSchedule on any agent NotReady past its 30s grace
(controller/internal/nodetaint/guard.go:31), and spire-server does not tolerate that
taint
. A gate that failed from t=0 would let a 40s SPIRE hiccup taint every node and
block spire-server's own rescheduling — the outage would fence out its own cure. With
the dwell, the 2026-09-07 boot (SPIRE healthy 16:00:35Z, agents up by 16:02:45Z)
produces zero NotReady and zero taints; a real outage (>2m) still escalates to NotReady,
which is what an operator wants: stop scheduling pods onto a node that cannot give them
an identity. TestNotReadyDwellOutlastsTaintGuardGrace pins the relationship.

SPIRE is deliberately not added to the #667 taint gate: that gate is for the
CNI-never-issues-ADD failure, a different class. SPIRE is fleet-correlated, exactly like
#668's collector argument.

What an operator sees

INFO  waiting for the SPIRE Workload API to issue this workload's SVID  socket=… attempt=7 elapsed=41.2s warnAfter=2m0s error=…
WARN  waiting for the SPIRE Workload API to issue this workload's SVID  … elapsed=2m3.4s …
INFO  obtained this workload's SVID from the SPIRE Workload API  socket=… attempts=9 elapsed=52.8s trustDomain=aether.internal
INFO  resolved workload trust domain from SPIRE  trustDomain=aether.internal

readyz?verbose reads spire-svid ok for the first 2 minutes and then
no SPIRE SVID after 2m10s (socket …); this workload cannot serve or verify mesh identity. Metrics (as Prometheus sees them):
aether_agent_spire_wait_seconds_{bucket,sum,count} (seconds-oriented buckets, #732),
aether_agent_spire_source_restarts_total (must stay 0),
aether_agent_spire_svid_ready (1/0 gauge).

Test evidence

All hermetic — a fake workload.SpiffeWorkloadAPIServer on a temp UDS with a
startServing() switch (asserting the workload.spiffe.io: true header), plus the
existing fake SPIRE agent. Negative controls run by reverting each fix in place, per the
#668 precedent:

Test Asserts Without the fix
TestWaitingSourceIsNeverFatal unreachable socket → one INFO line per attempt, attempt/elapsed increasing, Start never returns an error — (the pre-fix path is NewSource, whose bound is already pinned by #668's TestNewSourceWithTimeout_BoundsFirstSVIDWait)
TestWaitingSourceEscalatesToWarn past warnAfter the same line is WARN and carries the error —
TestWaitingSourceBecomesReadyWhenSPIREArrives becomes ready when SPIRE starts serving; Updated() fires; wait_seconds recorded once; svid_ready 0→1; source_restarts 0; header asserted —
TestWaitingSourceErrNoSVIDYet typed ErrNoSVIDYet naming the socket, on both source methods —
TestWaitingSourceBackoffIsBounded doubling, capped at 30s, jitter within 20% —
TestReadyChecker (table) nil source passes; holding an SVID passes; waiting inside the dwell passes; waiting past it fails FAILED (dwell removed → "inside the dwell" case fails)
TestNotReadyDwellOutlastsTaintGuardGrace dwell > the taint guard's 30s grace, and == the WARN threshold —
TestStartSpireIdentityReturnsImmediately returns in <100ms against an unreachable socket, registers the runnable, seeds the trust domain, runnable exits clean FAILED in 25.2s (old synchronous NewSource restored — the exact SourceTimeout hang)
TestStartSpireIdentityDisabledIsUnchanged SPIRE off: nil source, mesh domain, no runnable, no log output —
TestTrustDomain* (incl. concurrent) seed readable, Set reports change; race-clean under --features=race —
TestNodeSVIDServedWhenIdentityArrivesLate no identity → no SetNodeIdentity, bridge still running; identity arrives → served within 1s (ticker is 30s) FAILED (update wake removed)
TestWatchLoop_DefersWhileIdentityNotReady INFO deferral, zero ERROR lines, no watch_errors; then with identity ready the ERROR + counter come back FAILED in 30.1s (deferral removed)
bazel test --test_arg=-test.short //agent/... //common/... //registry/... //registrar/... //controller/...  → 71 tests pass
bazel build --config=lint //agent/... //common/... //registry/...  → OK (gocognit 15 gate; runAgent gained no branch)
make format-check → clean
helm lint charts/aether → 0 failed; helm template … | grep spire-wait-warn-after → 4 (agent, edge, registrar, controller)

Chart

spire.waitWarnAfter: 2m, threaded to all four binaries under the existing SPIRE guard
idiom. The registrar and controller parse the flag but do not act on it yet (PR 2) —
they must accept it now, or the chart would hand them an unknown flag. values.yaml
carries the toleration note: spire-server and spire-agent must tolerate
aether.io/agent-not-ready:NoSchedule
. charts/aether 0.92.8 → 0.92.9.

On-cluster validation (talos-main)

Scaling spire-server to 0 alone does not reproduce it — the node's spire-agent keeps
serving from cache. Pre-flight the SVID TTL and abort if < 30m.

Tier 1 (one node). Scale spire-server to 0, wait 60s, then delete that node's
spire-agent pod and its aether-agent pod. Expect: Running with 0 restarts,
the waiting… INFO lines, readyz spire-svid ok inside the dwell and failing
after it, and no taint inside the dwell. Scale spire-server back to 1 → ready within
~10s, taint cleared, obtained this workload's SVID logged.

Tier 2 (fleet). Same, but rollout restart ds/spire-agent + ds/aether-agent,
completed under 10 minutes, with no workload pod creation in the window. The prober
SLI must be flat throughout (Envoy serves on its last certs).

Abort criteria: any agent restart, any failed to create SPIRE Workload API source, any
aether_agent_spire_source_restarts_total > 0, any prober http_error attributable to
the window, or a node tainted inside the dwell. Note ssl_fail_verify_san_total needs
the _total suffix when querying.

Not deployed; a soak is being scheduled.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

)

Agent startup no longer exits when SPIRE is not serving yet. The one-shot,
fatal `commonspire.NewSource` (25s bound, #668) is replaced by a
`WaitingSource` runnable that retries forever with bounded, jittered backoff,
serves `ErrNoSVIDYet` meanwhile, and announces the wait at INFO with
attempt/elapsed — escalating to WARN after `--spire-wait-warn-after` (2m).

Everything downstream already tolerated a late identity: the SDS bridge dials
lazily and now also serves the node SVID on the source's `Updated()` wake
rather than the next 30s tick; the registrar watch loop defers (INFO, no
`watch_errors`, no backoff escalation) while the SVID is pending; the xDS cache
omits upstream mTLS until `SetNodeIdentity` lands and Envoy tolerates the absent
secret (#715). The trust domain is seeded with the mesh domain through a small
atomic holder and reconciled against the real SVID when it arrives.

Readiness gains a `spire-svid` check beside `cni-chained`, with a 2m dwell equal
to the warn threshold: the controller's node-taint guard re-arms
`aether.io/agent-not-ready:NoSchedule` after 30s of NotReady and spire-server
does not tolerate that taint, so a hard-from-t=0 gate would fence the cluster
against spire-server's own rescheduling.

New metrics: `aether.agent.spire.wait_seconds` (seconds-oriented buckets, #732),
`aether.agent.spire.source_restarts` (expected 0), `aether.agent.spire.svid_ready`.
Chart: `spire.waitWarnAfter: 2m` threaded to all four components. Runbook: "The
agent is stuck waiting for SPIRE".

The `--spire-enabled=false` path (#421) is unchanged, and nothing in `runAgent`
or `PreListen` is reordered (#700/#712). The controller/registrar/edge sources
still create synchronously; PR 2 moves them.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo merged commit 1559e83 into main Sep 7, 2026
18 checks passed
@bpalermo
bpalermo deleted the fix/740-spire-startup-decouple branch September 7, 2026 19:05
bpalermo added a commit that referenced this pull request Sep 7, 2026
…ad of dying on it (#740) (#742)

PR 1 (#741) moved the node agent off the one-shot, fatal `commonspire.NewSource`
(25s bound, #668). This closes the three remaining call sites, which all still
exited the process when SPIRE was not serving yet — measured negative control:
`NewSource` on an unserved socket returns after 25.02s with
`failed to create SPIRE Workload API source: context deadline exceeded`.

Controller (`buildControllerBootstrapOpts`, the earliest of the four — it runs
before `manager.Bootstrap` because the webhook server is built from its options):
constructs a `WaitingSource` and starts its `Run` on the command context, then
hands it to `spire.WebhookServerCert`. The certificate is resolved per handshake
(`tls.Config.GetCertificate`), so a source that is still waiting fails individual
TLS handshakes rather than the process; both webhook configurations are
`failurePolicy: Ignore`, so the apiserver fails OPEN meanwhile — admission
proceeds unvalidated and pods are not ndots-mutated, exactly as they were while
the container was crash-looping, only now the controller is alive and starts
serving the moment the SVID lands. `CABundleInjector.Source` widens to
`SVIDSource` and its initial-inject ERROR becomes INFO on `ErrNoSVIDYet`; the
injection is then performed by the `Updated()` wake `WaitingSource` fires on first
land as well as on rotation, so no retry logic was added.

Registrar (`buildSpireGRPCCreds`): same `WaitingSource`, registered with the
manager. `grpc.Creds` accepts a lazy source because the whole `tls.Config`
resolves at handshake time — the trust-domain resolution moves out of startup and
into `ServerTLSConfigForOwnTrustDomain`, which reads the registrar's own SVID per
handshake (so it stays correct across a rotation), plus one post-arrival callback
that logs the resolved trust domain. Until the SVID lands the registrar authorizes
NOTHING: the handshake fails before the authorizer is ever consulted.

Edge (`resolveEdgeIdentity`): needs the trust domain AND its own SPIFFE ID, so it
returns the seeds (mesh domain, empty ID) immediately and folds the real identity
in on the first SVID. `SnapshotCache.UpdateEdgeIdentity` is the after-start form
of `SetEdgeIdentity` — it rebuilds the cached mTLS clusters and pushes a snapshot,
so the edge Envoy picks the identity up on the next CDS update instead of on a
restart. The empty SPIFFE ID does not leak: `recomputeMTLSClusters` skips
injection entirely while it is empty.

All three register the same `spire-svid` readiness gate (`spire.ReadyCheckName`)
with the same `commonspire.NotReadyDwell` (2m). Here it is load-bearing in a way
it is not on a DaemonSet: these are Deployments behind Services, so past the dwell
the replica leaves the endpoints — the apiserver stops routing admission to a
controller that cannot handshake, agents stop dialing a registrar that cannot, and
the edge stops advertising an ingress whose upstreams have no identity. A workload
that already holds an SVID keeps it, so the gate can only fail one that never got
its first.

The wait's log lines are PR 1's, unchanged and shared, so one LogsQL phrase covers
all four binaries: `waiting for the SPIRE Workload API to issue this workload's
SVID` and `obtained this workload's SVID from the SPIRE Workload API`. Only the
metric namespace differs, via a new minimal `WithComponent` option on
`NewWaitingSource`: `aether.controller.spire.*`, `aether.registrar.spire.*`,
`aether.edge.spire.*` (the agent's names are unchanged by default).

`--spire-enabled=false` (#421) is byte-identical on all three paths — no source,
no runnable, no readiness check, no log line — and pinned by a test each. PR 1's
fake Workload API server moves to `common/spire/spiretest` so all four binaries
test against it.

Chart: the values.yaml note is corrected (the dwell now applies to all four
components) and Chart.yaml PATCH bumped. Runbook: the "stuck waiting for SPIRE"
section gains the per-component symptoms.


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 7, 2026
…ady (#740) (#743)

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.


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