Repository navigation
fix(agent): decouple startup from OTel export so a shedding collector cannot crash-loop agents (#662) - #668
Merged
Conversation
…nd flush
Telemetry work must never share a lifecycle context with the component it
observes. Two helpers make that explicit:
- DetachedTimeout keeps the parent's values but drops its cancellation and
bounds the work, so telemetry can neither spend the caller's startup budget
nor observe a cancellation of the caller's context.
- BestEffortShutdown runs a provider's final flush on such a context. On
SIGTERM the caller's context is ALREADY cancelled by the signal handler, so
passing it through made every final flush a guaranteed no-op that failed
with "context canceled" — dropping precisely the records worth having.
Refs #662.
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
…662) manager.Bootstrap returned an error when the OTel metric/trace providers could not be built, and SetupManagerLogging did the same for the OTLP log exporter — so a telemetry problem exited the process. Both now degrade to less telemetry and log a WARN instead, and SetupManagerLogging drops its error return entirely so the "telemetry cannot fail startup" property is enforced by the type. Setup runs on a detached, bounded context (setup.DetachedTimeout) and every returned shutdown is wrapped in setup.BestEffortShutdown, so: - a wedged or shedding collector cannot consume the startup budget of a binary whose health probes only begin answering once initialization finishes; - a telemetry failure cannot cancel the context SPIRE, xDS and CNI initialization hang off — the two contexts are now separate; - the final flush still runs after SIGTERM has cancelled the caller's context. Bootstrap takes the component's logger so it can report the degradation; the --otel-enabled=false path is unchanged (no MeterProvider, TracerProvider still installed for trace_id on logs). Tests use a fake collector that answers every RPC with ResourceExhausted "data refused due to high memory usage" — the exact status a saturated otel-collector's memory_limiter returns — plus a black-hole listener and an unparseable endpoint for the hard-failure path. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
…eness budget (#662) This is the stall that actually produced the crash loop in #662. Every binary here initializes its dependencies BEFORE starting the controller-runtime manager, and the manager is what begins answering /healthz and /readyz — so any unbounded wait during initialization is invisible to the process and fatal to it. workloadapi.NewX509Source retries an unreachable or non-attesting SPIRE agent forever, so the agent sat there silently; the chart's liveness probe (10s period, 3 failures) killed the container at ~35s, the signal handler cancelled the single shared startup context, and the wait aborted with the misleading "failed to create SPIRE Workload API source: context canceled" — which reads as a SPIRE bug rather than a probe kill. NewSource now bounds the first-SVID wait at 25s (below the liveness budget) and names the socket in the error, and the agent logs the wait before entering it. The bound is safe for rotation: go-spiffe derives the rotation watcher's context from context.Background() (workloadapi.newWatcher), not from the one passed in, so the returned source keeps refreshing for its whole lifetime. The readiness cache-sync check is bounded the same way. WaitForCacheSync blocks until the cache syncs or the request ends, so an unsynced cache hung the probe until the kubelet's own timeout expired and was reported as "Readiness probe failed: context deadline exceeded" — indistinguishable from a wedged process. It now answers below the probe timeout with an honest "informer cache not synced". Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
bpalermo
added a commit
that referenced
this pull request
Sep 5, 2026
… decoupling on demand (#690) #668 made agent startup independent of OTel export, but the branch it fixed has never run since: over the 09-03 and 09-04 soaks the collector peaked at 245 MiB, 21.7% of its 1126 MiB memory_limiter soft limit, and refused zero metric points. A soak drives mesh traffic, not telemetry volume, so it cannot reach that state. e2e/pressure/ reaches it deliberately and reversibly: a telemetrygen Job floods the shared collector's logs pipeline (memory_limiter is one process-wide component, so every pipeline — including the metrics pipeline the agents export to — starts refusing), then one node's agent pod is deleted under that pressure and asserted to start, attest to SPIRE and resume exporting. Refs #662 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 5, 2026
…e FAIL criterion (#699) (#714) * fix(e2e): abort the pressure harness on heap vs GOMEMLIMIT, narrow the FAIL criterion (#699) Four runs against talos-main on 2026-09-05 exposed two defects in the #662 collector-shedding harness. 1. The abort ceiling sat below the point the limiter actually engages. memory_limiter triggers on the Go heap, and refusal onset was measured at 1,077-1,300MiB heap while RSS at that same instant was 1,250-1,650MiB (GC slack runs RSS 1.15-1.4x ahead). The fixed 1,500MiB RSS ceiling therefore landed inside that band: runs 2 and 3 aborted after shedding had engaged but before the poll observed it. The primary ceiling is now heap against GOMEMLIMIT (95%, read off the live pod's env, falling back to the container memory limit when it is derived), with RSS kept only as a cgroup-OOM backstop at 90% of the pod limit. Both are derived at run time instead of hard-coded, so a resize of the o11y plane cannot silently invalidate them; the soft/hard limiter thresholds are likewise derived from limit_percentage/spike_limit_percentage. The counters and gauges are now read from the collector's own :8888/metrics over one port-forward per replica, which removes the scrape lag that made the poll miss the onset. The deployed collector does not currently serve :8888 -- its service.telemetry.metrics has only a periodic OTLP push reader -- so --metrics-source auto detects that, warns, and falls back to Prometheus at a 15s poll; the README carries the GitOps snippet that opens the pull reader. Metric names are matched tolerantly across otelcol_processor_memory_limiter_refused_* (what 0.159.0 emits), otelcol_processor_refused_* and otelcol_receiver_refused_*. Collector replica discovery reads the Deployment's own .spec.selector: the otel-scraper Deployment shares app.kubernetes.io/name=opentelemetry-collector and would otherwise have folded a second process into the sums. 2. The FAIL criterion was broader than #662. Run 4's agent came Ready in 16s with 0 restarts and SPIRE resolved -- the #668 fix held -- but the harness printed FAIL over one self-recovering client retry logged at ERROR (`failed to start watch stream, retrying` / `context canceled`, tracked in #700). FAIL is now exactly #662's signature: `failed to create SPIRE Workload API source`, a container exit (restartCount > 0, a terminated previous container, or CrashLoopBackOff), or the trust-domain resolution never being logged. Every other ERROR line is listed as informational. Also adds --dry-run, which resolves GOMEMLIMIT, the pod limits, the thresholds and the metrics source, prints the plan and the current readings, and exits without applying the Job or touching an agent. The README now records the observed numbers so nobody re-derives them (heap trigger ~1,126MiB = RSS 1,250-1,650MiB, limiter caps RSS at ~1,743MiB on the 2Gi pod, 0 collector restarts across four runs) and warns that rate() over the prober SLI under-reads during shedding (12-18/s against a real 25/s) because of export lag on cumulative counters that self-heal -- not lost requests. Validated: shellcheck clean, make format-check clean, --dry-run exercised against talos-main on two nodes (resolves GOMEMLIMIT=1638MiB -> 1,556MiB heap ceiling and 2Gi -> 1,843MiB RSS backstop), --metrics-source collector correctly exits 2 while :8888 is closed, and parse_bytes/agg_samples unit-tested against a synthetic exposition fixture. The harness itself was NOT run against the cluster. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr * fix(e2e): make the 3-pod rate-3 pressure job the default; 2/2 never reaches shedding (#699) Two of two runs at 2 pods x rate 2 on 2026-09-05 timed out at 300s with the collector heap at 10% of GOMEMLIMIT and zero refusals; every run that reached shedding used 3 x 3. Corrects the arithmetic (144MiB/s aggregate, ~72MiB/s per replica, ~70% of the limiter's spike frontier) and the observed numbers from the fifth run (heap peak 1,497MiB = 91% of GOMEMLIMIT, RSS peak 1,766MiB, 0 restarts). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr * docs(e2e): five runs (#699) 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 7, 2026
) (#741) 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. 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
…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]>
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.
Closes #662.
The mechanism, as found in the code
Every one of these binaries initializes its dependencies before starting the
controller-runtime manager — and the manager is what begins answering
/healthzand
/readyz. So the whole initialization sequence runs inside the kubelet'sliveness budget while the probe endpoint is silent, and everything in it shares
one context:
ctrl.SetupSignalHandler(), threaded frommainthroughrunAgentinto telemetry, storage, SPIRE and the registrar client.That gives the observed failure a precise shape:
commonspire.NewSource→workloadapi.NewX509Sourcewaits for the first SVIDwithout any bound (
common/spire/tls.go:26before this PR). The WorkloadAPI client treats
Unavailableas retryable and retries forever, so anunreachable or non-attesting SPIRE agent parks the agent here — silently,
with no log line at all.
/healthznever answers, becausem.Start(ctx)is the last statement ofrunAgent(agent/internal/cmd/root.go:316). At 10s period × 3 failures thekubelet kills the container at ~35s.
with
failed to create SPIRE Workload API source: context canceled—attributing a probe kill to SPIRE.
(
deferTelemetryShutdown/deferLogShutdown), which is exactly why bothreported
context canceledand exported nothing. That was true of everySIGTERM, not just this incident: the last records of a terminating process
were always dropped.
The
exporter export timeout: ... data refused due to high memory usageline isemitted by the periodic reader's background goroutine through OTel's global
error handler. It is a symptom of the same saturation, not the thing that
blocked startup — the OTLP gRPC clients are lazy (
grpc.NewClient), so exporterconstruction never dials.
But the coupling the issue names is real, just in a different direction than the
log ordering suggests: telemetry could kill the process outright.
manager.Bootstrapreturned an error if the metric or trace provider failed tobuild, and
SetupManagerLoggingreturned one if the OTLP log exporter did — andboth errors exit(1). An observability backend was a hard dependency of the data
plane.
Why that matters
Telemetry is best-effort by definition; the data plane is not.
agent can't start, that node's mesh config goes stale and new pods there get
no listeners. An agent that programs Envoy but cannot export metrics is
degraded, not dead.
collector and every agent attests against the same SPIRE server, so one
saturated dependency can take out every node's agent simultaneously — most
likely during a rolling restart, when they all start at once. Same class as
agent: ghost-sweep prune needs a mass-delete circuit breaker (power-blip incident 2026-07-19) #566/CNI boot race: pods restarted before cni-install come up unregistered — no self-heal, total mesh outage after node reboot #640. On 2026-09-02 that was 3 of 5 nodes, with worker-02 at 5 restarts
and still CrashLoopBackOff.
memory_limiterworking correctly. The right response is degraded telemetry, not death.
What changed
common/telemetry/setup/lifecycle.go(new) — two helpers that make thecontext separation explicit:
DetachedTimeout(parent, d)keeps the parent's values but drops itscancellation and bounds the work. Telemetry can neither spend the caller's
startup budget nor observe a cancellation of the caller's context.
BestEffortShutdown(fn)runs a provider's final flush on such a context, sothe flush still works after SIGTERM has cancelled the caller's context.
common/manager— telemetry is now best-effort by construction:setupTelemetry(extracted fromBootstrap) builds the providers on adetached, bounded context; a failure logs a WARN and continues with less
telemetry instead of returning an error that exits the process.
SetupManagerLoggingdrops its error return entirely — an OTLP logexporter that cannot be built degrades to stderr-only logging with a WARN. The
"telemetry cannot fail startup" property is now enforced by the type, not by
convention.
BestEffortShutdown, which fixes thefailed to shutdown telemetry: context canceled/failed to flush OTel logs: context canceledpair for all four binaries atonce (agent, edge, registrar, controller) with no change at the call sites.
Bootstraptakes the component's logger so it can report the degradation.common/spire/tls.go—NewSourcebounds the first-SVID wait at 25s(
SourceTimeout, deliberately below the ~35s liveness budget) and names thesocket in the error;
NewSourceWithTimeoutexposes the bound for tests. Theagent logs the wait before entering it, so the next incident has a breadcrumb.
The bound is safe for rotation: go-spiffe derives the rotation watcher's context
from
context.Background()inworkloadapi.newWatcher, not from the one passedin, so the returned source keeps refreshing SVIDs for its whole lifetime. This
turns an opaque 35s probe kill into a fast restart with an accurate error — it
does not make an unavailable SPIRE survivable, which it isn't: the agent cannot
serve mTLS xDS without an SVID.
common/telemetry/setup/healthz.go— the readiness cache-sync check isbounded at 500ms.
WaitForCacheSyncblocks until the cache syncs or the requestends, so an unsynced cache hung the probe until the kubelet's own timeout
expired and was reported as
Readiness probe failed: context deadline exceeded— indistinguishable from a wedged process. It now answers below theprobe timeout with an honest
informer cache not synced.--otel-enabled=falseis unchanged: no MeterProvider, TracerProvider stillinstalled (it is what stamps
trace_idonto logs), same shutdown shape.The readyz decision
readyzshould not depend on telemetry, and after this PR it structurallycannot.
An agent that can program Envoy but cannot export metrics is degraded, not
unready. Gating readiness on telemetry would make a saturated collector
mark every agent in the fleet unready at once — turning a metrics outage into
a data-plane outage, which is the same correlation failure this PR removes, just
one layer up. Readiness should describe what the node's consumers depend on:
Envoy getting its config.
Concretely,
readyzkeeps its two existing checks (healthz.Pingandcache-sync) and gains none. Telemetry can no longer influence readiness evenindirectly, because it can no longer fail the bootstrap that installs those
checks. Export health stays observable where it belongs — the collector's own
otelcol_*metrics and theOtelCollectorRefusingDataalert, which did firecorrectly here.
Test evidence
New tests, all verified to fail without the fix (negative controls run by
reverting each fix in place):
TestSetupTelemetry_SheddingCollectorDoesNotFailStartupResourceExhausted: data refused due to high memory usage; caller's context untouched; flush after SIGTERM is notcontext canceledTestSetupTelemetry_BlackHoleCollectorDoesNotBlockStartupTestSetupTelemetry_DetachedFromCallerContextTestSetupTelemetry_SetupFailureIsNotFatalTestSetupManagerLogging_SheddingCollectorTestSetupManagerLogging_SetupFailureFallsBackToStderrTestSetupTelemetry_Disabled/TestSetupManagerLogging_Disabled--otel-enabled=falsebehaves exactly as beforeTestNewSourceWithTimeout_BoundsFirstSVIDWaitTestNewSourceWithTimeout_HonoursCallerCancellationTestBestEffortShutdown_RunsWithCancelledCallerThe fake collector needs no OTLP protos: a
grpc.UnknownServiceHandlerreturning
ResourceExhaustedreproduces the shed exactly (and is correctlynon-retryable per the OTLP spec, so the test is fast and deterministic).
No dependency, proto, or chart changes.
How to verify on-cluster
limit down until
OtelCollectorRefusingDatafires) andkubectl rollout restart ds/aether-agent. Expect the agents to start,serve xDS, and log at most a telemetry WARN — no
Error: failed to create SPIRE Workload API source, no restarts.kubectl delete podan agent and check its final log lines: the flush shouldno longer report
failed to shutdown telemetry: context canceled, and thelast records should reach the collector.
the aether agent there: expect one clean exit at ~25s naming the workload
socket, preceded by
waiting for the SPIRE Workload API to issue this agent's SVID, instead of a silent 35s liveness kill.Not deployed — a soak is being scheduled on talos-main.
🤖 Generated with Claude Code
https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr