Skip to content

fix(agent): one source of truth for the trust domain; the inbound mTLS probe is can't-tell, not unhealthy (#815, fixes #819) - #821

Merged
bpalermo merged 1 commit into
mainfrom
fix/815-release-one-fixes
Sep 19, 2026
Merged

bpalermo merged 1 commit into
mainfrom
fix/815-release-one-fixes

Conversation

@bpalermo

Copy link
Copy Markdown
Owner

Fix forward for #819 (release one of #815), which failed its live validation on talos-main and was rolled back (rev222 → rev223, 2026-09-19). main has been undeployable since; this makes it deployable again. Deploy only with the live validation at the bottom.

Root cause of the outage — a lock-ordering hoist widened a nanosecond race into a ~700 ms one

The node agent's trust domain is late-bound (#740). LoadListenersFromStorage filled c.listeners under listenerMu and only afterwards recorded c.trustDomain — so for the duration of the load the cache held a complete listener map together with an empty trust domain. Pre-#819 the regeneration paths read c.trustDomain at the point of use, inside listenerMu, so the losing window was a few instructions wide and was never hit. #819 hoisted that read above the blocking Lock() ("read before taking listenerMu"), so any regeneration that merely queued on the lock during the load sampled "", waited, and then rewrote every per-pod listener from it: spiffe:///ns/<ns>/sa/<sa>.

On main-worker-03 the gamma reconciler's first SetServiceChainFilters fired 416 ms into the 710 ms load:

17:31:21.608 listener.go   generating listeners                  ← load starts
17:31:22.024 gamma.go      service chain filters updated         ← INSIDE the load
17:31:22.218 snapshot .1   secret=spiffe://aether.internal/…     ← correct
17:31:22.318 listener.go   generated listeners count=16          ← load ends
17:31:22.423 snapshot .2   bound_spiffe_id=spiffe:///ns/…        ← all 15 chains broken

w01 and w02 had the same event land after the load; w05 had it inside and won the race. Envoy subscribed to five SDS names nobody serves (envoy_sds_spiffe_ns_*_init_fetch_timeout_total = 1 each), the inbound listeners came up with no certificate, the new TLS probe could never pass, and four endpoints were demoted and never re-promoted.

Fix 1 — one source of truth; spiffe:/// is unrepresentable

  • The cache's trust domain is a single atomic.String, published under listenerMu and read inside every listener-rebuild critical section (rebuildPodListenersLocked), so a rebuild can neither straddle a change nor see a stale value. AddPod / LoadListenersFromStorage record it BEFORE generating anything. SetTrustDomain rebuilds everything derived and publishes exactly one snapshot on a change; it refuses "". The SPIRE reconciler now sets it even when SPIRE merely confirms the seed.
  • SpiffeIDFromPod returns "" for an unknown trust domain; NewInboundListener returns ErrNoTrustDomain; mTLS injection, SAN matchers, validation-context names and the capture/edge TCP clusters are skipped rather than rendered from an empty value. A pod whose listeners cannot be built is skipped with a WARN and keeps its previous config. SPIRE-off stays byte-identical.

Fix 2 — the gate can no longer be silently absent (the w05 case)

#819 hung the probe-cluster recompute off two one-shot events (the bulk load and SetNodeIdentity, which the bridge calls once ever). Why w05 missed both could not be reconstructed from its log — so the dependence on catching an event is removed: probes are reconciled on every snapshot generation (a no-op map walk in steady state; bytes never change), each missing precondition has a name, and the agent logs once per start and on every change inbound-readiness promotion gate ACTIVE … gated_pods=N or NOT active … missing="…". New gauge aether_agent_liveness_inbound_gate_pods{aether_gate_state="gated|ungated"}.

Fix 3 — a stranded endpoint has a way back, and a signal

The TLS probe gets its own gateway path (/healthz/inboundready_<pod>; /healthz/health_<pod> is the app probe alone again), so the liveness loop sees both results:

app probe TLS probe already served? action
fails any any UNHEALTHY (grace + streak apply)
passes 404 (ungated) any HEALTHY
passes passing any HEALTHY
passes never passed this epoch yes HEALTHY — can't-tell; WARN + inbound_gate_held_pods
passes never passed this epoch no held un-promoted; WARN after 60 s
passes passed earlier, failing now any UNHEALTHY after the streak

"Already served" = the endpoint is or has been advertised HEALTHY, not "the app probe passed once". The first promotion — the hole the gate exists to close — stays a hard precondition. The demote streak and gateway re-arm are kept and re-justified at the constant. aether_agent_liveness_health_transitions_total is now seeded at 0 for HEALTHY→UNHEALTHY and UNHEALTHY→HEALTHY (it had no series before the incident, so "zero demotions" could not be graded); new gauge aether_agent_liveness_inbound_gate_held_pods.

Tests

Each new test was verified to FAIL with its guard disabled. TestRegenerationDuringTrustDomainWindowKeepsIdentities reproduces the w03 interleaving; TestNoMalformedIdentityUnderArbitraryMutatorOrder runs the public mutators concurrently in rotated order with the trust domain arriving late and scans the wire bytes of every resource (inside typed_config Anys too) for spiffe:///; gate-convergence tests for missed triggers; liveness tests for every row of the table incl. TestStrandedEndpointHasAWayBack and TestProxyRollDoesNotDemoteTheNode. 18/18 targets incl. //test/envoy_validate; --config=race ×3 clean; lint clean. No chart change (0.92.27 was published but never stayed deployed; tags are per-SHA).

Live validation required before this stays deployed

  1. {__name__=~"envoy_sds_spiffe_ns_.*"} empty on every node at every moment of the roll — one series is a STOP.
  2. Every agent logs promotion gate ACTIVE … gated_pods=N; inbound_gate_pods{aether_gate_state="ungated"} == 0 on all nodes.
  3. HEALTHY→UNHEALTHY increase == 0 (series exists at 0 beforehand); inbound_gate_held_pods returns to 0.
  4. A proxy roll on every node, and a prober target with a pod on every node (the last run was blind: echo had no pod on w03).
  5. Then what feat(agent): stamp the source SPIFFE ID in filter state; HEALTHY requires an mTLS handshake with the pod's inbound listener (#815, release 1/3) #819 never measured: SVID → inboundready → promotion timeline (TCP-HC-over-TLS == handshake done is still NOT established), the new promotion delay, and the release-two "before" warming_clusters baseline.

Refs #815.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

…S probe is can't-tell, not unhealthy (#815 re-land)

Release one of #815 (PR #819) failed its live validation on talos-main and was
rolled back. Three defects, all fixed here.

DEFECT 1 — listeners published with an EMPTY trust domain (the outage).

On main-worker-03 Envoy subscribed to SDS secrets named `spiffe:///ns/<ns>/sa/<sa>`
— no trust domain. The agent never serves that name, so five pods' inbound
listeners came up with no certificate, the new mTLS readiness probe could never
pass, and four endpoints were demoted HEALTHY -> UNHEALTHY permanently.

Root cause. The node agent's trust domain is late-bound (#740).
LoadListenersFromStorage published the whole per-pod listener map under
listenerMu and recorded the trust domain ~700ms LATER under localMu, so there
was a long window in which the cache held listeners and an empty trust domain.
#819 then hoisted regenerateAllHTTPListeners' trust-domain read OUT of the
listenerMu critical section (to avoid nesting locks), so a reconciler that
STARTED inside that window sampled "", blocked on listenerMu for the rest of the
load, and rewrote every listener with the malformed identity. w03's log shows
exactly that: LoadListenersFromStorage 17:31:21.608 -> 17:31:22.318, the gamma
reconciler's first SetServiceChainFilters at 17:31:22.024 in between, snapshot
...081526.1 with correct chains and the next snapshot ...082222.2 with
`spiffe:///` on all 15. w01/w02 ran the same build and the same reconciler
AFTER the load finished, and were fine.

Pre-#819 read the same field unlocked but at the point of USE, inside the lock,
so the value hole existed only between the unlock and the localMu write —
nanoseconds. #819 widened it to the whole duration of a listener load.

Fix, four layers, each with a test:
  - proxy.SpiffeIDFromPod returns "" for an unknown trust domain — `spiffe:///`
    is now unrepresentable, not merely discouraged. ValidationContextName does
    the same for "spiffe://<td>".
  - builders that need a real identity REFUSE: NewInboundListener returns
    proxy.ErrNoTrustDomain, the mTLS matcher emits no SAN and no injected
    cluster, the inbound-readiness probe is skipped. The regeneration loops log
    the pod and skip it, keeping its previous (correct) listener.
  - the cache's trust domain is ONE atomic value read at the point of use,
    INSIDE the listenerMu section that writes the listeners; setTrustDomain
    publishes under the same lock, so a rebuild can neither straddle a change
    nor observe a stale value, and an empty value never displaces a known one.
  - LoadListenersFromStorage and AddPod record it BEFORE publishing anything,
    so the window does not exist. SetTrustDomain rebuilds every
    identity-derived resource and publishes exactly one snapshot.

DEFECT 2 — main-worker-05 emitted no inboundready_* cluster at all.

#819 hung the probe recompute off two one-shot events: a bulk listener load and
SetNodeIdentity, which the SPIRE bridge calls ONCE ever (`if firstServe`). Any
ordering where both fire while a precondition is missing leaves the gate absent
for the life of the agent, with no third trigger and no signal. (I could not
reconstruct w05's exact losing ordering from its log — both triggers appear to
have had their preconditions met — so the fix removes the whole class rather
than one ordering.) The probes are now reconciled on EVERY snapshot, skipping
entries already rendered from the current identity, so nothing depends on
catching an event. Plus: a gauge of gated/ungated pods recorded every liveness
pass, and one INFO line per agent naming the missing precondition.

DEFECT 3 — a stranded endpoint had no signal and no way back.

#819 ANDed both probe clusters behind the single /healthz/health_<pod> path, so
the agent saw only their conjunction and could not tell "the app died" from
"the mesh inbound never came up". Each probe cluster now gets its OWN gateway
path reflecting that cluster alone, and the liveness loop combines them:

  app     inbound-readiness      already serving?   action
  fails   any                    any                UNHEALTHY
  passes  404 (ungated)          any                HEALTHY
  passes  passing                any                HEALTHY
  passes  never passed (epoch)   yes                HEALTHY (can't-tell) + WARN
  passes  never passed (epoch)   no                 held un-promoted + WARN
  passes  passed, now failing    any                UNHEALTHY (demote streak)

"Already serving" means the endpoint is or has been advertised HEALTHY, and
survives an Envoy epoch change on purpose. livenessDemoteStreak and the gateway
re-arm both stay and are re-justified at the constant: the streak now covers a
hot restart the agent never notices (the supervisor's two-epoch overlap keeps
the gateway answering, so no re-arm fires) plus the app probe's own epoch
warm-up; the re-arm covers a proxy container restart.

New metrics:
  aether.agent.liveness.inbound_gate_pods{aether.gate.state=gated|ungated}
  aether.agent.liveness.inbound_gate_held_pods
  aether.agent.liveness.health_transitions is now SEEDED at 0 for
  HEALTHY->UNHEALTHY and UNHEALTHY->HEALTHY — it had no series at all before the
  incident, so "0 demotions" could not be graded.

Runbook rewritten for the new semantics, including `envoy_sds_spiffe_ns_*` as a
named failure with its query.

Not touched: the cluster transport_socket_matcher (release two), inbound peer
validation, agent/internal/spire. SPIRE-off output stays byte-identical.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo merged commit 0f2b6c4 into main Sep 19, 2026
20 checks passed
@bpalermo
bpalermo deleted the fix/815-release-one-fixes branch September 19, 2026 18:50
bpalermo added a commit that referenced this pull request Sep 19, 2026
…netns path (#815, release 2/3) (#822)

Every local pod ADD/DEL rewrote EVERY mesh cluster on the node. The per-source
upstream-mTLS transport_socket_matcher keyed its exact_match_map on the source
pod's netns path, which is unique per pod, so one unrelated CNI ADD changed a
field of every service cluster. Under delta-xDS each rewritten EDS cluster then
re-warmed for the full 15 s EDS initial_fetch_timeout (delta sends no EDS
request for a name the old cluster already watches), and the warming->active
swap destroyed the old ClusterEntry on every worker, draining every upstream
connection pool on the node. Measured on talos-main rev224: one new pod -> 20-24
clusters warming for 15 s, two -> 30 for 30 s, nodes with no new pod -> 0. That
handshake storm is the latency after a service roll and cost an 8 h soak its
largest error episode.

The matcher always SELECTED per-ServiceAccount -- the transport_socket_matches
entry name is the SPIFFE ID -- so keying the map by identity loses nothing and
makes the Cluster proto byte-stable across pod churn within a ServiceAccount.
Release one (#819/#821) made every mesh-originating chain stamp
aether.source.spiffe_id; this reads it. Only the first pod of a ServiceAccount
arriving on a node, or the last one leaving, changes a cluster now.

The matcher, the matches and the identity set all derive from one sorted,
deduplicated identity list, so nothing is a function of map-iteration order.
The netns->identity index stays in c.localWorkloads for the #638 discriminator;
nothing in the Cluster proto is keyed by netns any more.

UPGRADE ORDER: a proxy must run release-one listeners before it is handed
release-two clusters. LDS and CDS are separate xDS responses with no ordering
guarantee, so a release-two cluster facing a pre-#819 listener matches nothing,
takes on_no_match and presents the node identity. Going from a chart older than
0.92.27 straight to 0.92.28 is therefore unsupported. Recorded in the chart
NOTES, docs/runbook.md section 7, and the constants' contract comment.

SA-entry stickiness (keeping a departed ServiceAccount's entry for a grace
period, to spare the scale-to-zero case) was evaluated and rejected: the
retained entry would name an SDS secret the agent stops serving, which a NEW
Envoy epoch would warm on until initial_fetch_timeout and then come up with
upstream_context_secrets_not_ready -- the same defect on the proxy-roll path.
The entry is also unreachable while retained, since no listener stamps a
departed pod's identity. Reasoning is in the runbook.

Observability: the chart lifts the per-match counter's SPIFFE ID into the
aether.transport_socket_match tag, so it exports as one
envoy_cluster_total_match_count family instead of one metric NAME per
ServiceAccount. on_no_match increments the NAMED socket's counter, never
`default`, so a rising spiffe://<td>/node/... on a service cluster is the
"connection did not carry the key" signal. Also fixes the health_/inboundready_
exclusion alternative, which said default_total_match and therefore matched
nothing -- the stat is default.total_match_count.

Tests: TestLocalPodChurnRewritesEveryServiceCluster is replaced by its inverse,
TestServiceClusterBytesStableWithinServiceAccount, plus
TestServiceClusterBytesChangeOnFirstAndLastPodOfServiceAccount (the events that
still cost a re-warm, reversibly), TestNoNetnsPathInServiceClusterBytes (a wire
scan of the serialized cluster, which reaches inside typed_config Anys),
TestServiceClusterBytesUnaffectedByPodChurnWithSpireOff, and in the proxy
package TestClusterMatcherKeyedOnSourceIdentity and
TestClusterMatcherIsOrderIndependent. The stock-Envoy gate now validates a
service cluster carrying the one-level matcher with two local ServiceAccounts.


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