Skip to content

fix(supervisor): probe on a detached ctx, bound the successor wait by the grace budget, fix epoch bookkeeping, atomic file publishes (#771, #772) - #785

Merged
bpalermo merged 5 commits into
mainfrom
fix/772-a5-supervisor-shutdown
Sep 16, 2026

Conversation

@bpalermo

Copy link
Copy Markdown
Owner

Phase A5 of #772. Closes #771. Cluster validation: hitless roll + delete-pod check on talos-main with the Phase A batch.

fix(proxy-supervisor): probe the admin endpoint on a detached ctx at shutdown (#771) (#772)

handleShutdown has exactly one call site — case <-lp.ctx.Done() in
restartLoop.run — so the context it is handed is ALWAYS already cancelled by
controller-runtime's signal handler. It passed that context straight into the
epoch-identity probe (adminLiveAtEpoch -> adminServerInfo ->
context.WithTimeout on an already-cancelled parent), so http.Client.Do failed
with "context canceled" in microseconds without ever opening a socket.
!adminLiveAtEpoch(...) was therefore true on every SIGTERM regardless of
Envoy's actual state, and the "termination requested mid-handoff; waiting for
successor" branch was taken unconditionally — including when Envoy was LIVE at
our own epoch and no successor existed, in which case Envoy was never drained.

Measured on talos-main (issue #771 reproduction): both sampled pods recorded
aether_supervisor_admin_probes_total{probe_endpoint="server_info", result="unreachable"} exactly once in a 2d21h lifetime — at their SIGTERM —
while result="live" was still climbing +10/30s on the same series and
envoy_server_state was 0 (LIVE). The mid-handoff line was logged 194ms/195ms
after the delete, 4.3-6.3s before any successor Envoy started.

Fix: run the probe on a context detached from the caller's, keeping its values
but not its cancellation, bounded by shutdownProbeTimeout. This is the same
trap and the same idiom as common/telemetry/setup/lifecycle.go's
DetachedTimeout (issue #662). The branch semantics are unchanged: admin LIVE at
our epoch -> drain; not LIVE at our epoch (a successor has taken the admin
port) -> leave Envoy alone for the successor's parent-shutdown protocol.

Tests (agent/internal/proxy/hotrestart/shutdown_test.go), both driving
handleShutdown with an already-cancelled context against a production-shaped
supervisor (StateDir set, real admin address, a live tracked child at epoch 0):

  • LIVE at our own epoch -> drain branch taken, child SIGTERMed and reaped, and
    the fake admin's /server_info hit counter advanced (i.e. the probe really
    reached the network).
  • LIVE at epoch 1 -> the genuine mid-handoff case: still blocks, child
    untouched, and the decision was again made off a real probe.
    Reverting the WithoutCancel makes the first test fail with "handleShutdown
    blocked: the drain branch was not taken", which is the production bug verbatim.

Verification: bazel test //agent/internal/proxy/... passes.

fix(proxy-supervisor,chart): bound the mid-handoff wait by the pod's own grace period (#771) (#772)

awaitProtocolTermination was a bare <-s.childExited loop with no deadline and
no context, so a termination where no successor can ever appear — graceful node
shutdown, node deletion / scale-down, kubectl delete daemonset or a chart
uninstall, or a replacement stuck Pending/ImagePullBackOff/unschedulable —
blocked until the kubelet's SIGKILL at terminationGracePeriodSeconds with Envoy
never SIGTERMed and connections still open. With #771's ctx fix that branch is
now entered only when admin really answers at another epoch, but the residual
exposure is real, and it is precisely the case a kubectl delete pod cannot
reproduce (the DaemonSet's replacement hot-restarts the parent within ~1s, so a
delete self-rescues into the surge path).

The fix is deliberately NOT a blind timer. The function's own comment explains
why there wasn't one: the successor's parent-shutdown timer starts only after
its xDS-gated, unbounded init, and it keeps using the parent socket for stat
merges right up to protocol-terminate, so cutting a healthy handoff short
aborts the successor with errno 111 (the 2026-06-11 node data-plane gap). The
only non-arbitrary bound is the pod's own death sentence, so the supervisor is
now told what it is:

  • Config.TerminationGrace / --termination-grace, passed by the chart from the
    same value it sets on terminationGracePeriodSeconds (0 = unknown = wait
    indefinitely, i.e. the previous behavior, which is what every older chart
    and every unit-test supervisor gets).
  • successorWaitBudget = TerminationGrace - (DrainTime + shutdownGrace) -
    terminationFallbackMargin(10s): wait as long as the pod has, minus what the
    drain will then cost, minus head-room. Deployed values give 155s of 180s. A
    grace period too small to fit a drain yields 0 and keeps waiting rather than
    guaranteeing an errno-111 abort.
  • On expiry: log at WARN with the epoch state observed at that moment (a fresh
    probe, again on a detached context), then s.shutdown() — SIGTERM every
    tracked epoch and reap, so Envoy drains and exits 0 before the SIGKILL.

Also fixes the stale comment at the top of handleShutdown, which promised "a
deadline fallback" that did not exist; the function comment on
awaitProtocolTermination said the opposite. Both now describe the same thing.

Chart: proxy.terminationGracePeriodSeconds (default 180, unchanged behavior)
replaces the hard-coded literal and feeds both the pod spec and the new flag.
charts/aether bumped 0.92.19 -> 0.92.20.

Tests:

  • TestSuccessorWaitBudget pins the arithmetic at the deployed values, at an
    unset grace, and at a grace too small to fit a drain.
  • TestHandleShutdownFallsBackToDrainWhenNoSuccessorComes: admin LIVE at a newer
    epoch (mid-handoff branch correctly entered) with nothing ever terminating
    our Envoy — the wait expires at the budget, not before it, and the child is
    drained and reaped.

Verification: bazel test //agent/internal/proxy/... //agent/internal/cmd/...
passes; helm template renders terminationGracePeriodSeconds: 180 and
--termination-grace=180s.

fix(proxy-supervisor): epoch bookkeeping — no key reuse, no epoch bump before fork, atomic gate publish, readiness held across retries (#772)

The four epoch findings from the 2026-09-15 race review (S14-S17), all four
confirmed from the code and all four reachable only through the bind-collision
retry path, which is why none of them shows up in a normal roll.

S14 (supervisor.go, hotRestart): s.children[epoch] = cmd could reuse a key
whose child is still tracked. resetEpochForRetry rewinds nextEpoch to 0 on every
retry and initStartEpoch leaves it there when the heartbeat is stale, so a
relaunch overwrote the *exec.Cmd of a still-draining epoch-0 Envoy. The draining
process was then orphaned (signalEpoch resolves epoch 0 to the new cmd, so
shutdown() never signals it), awaitProtocolTermination's pending count
undercounted it, and its eventual exit could take the container down non-zero
while the new Envoy was healthy. Fix: reserveEpoch() advances past any epoch
still present in children and logs when it does. A tracked child at E also means
E's base-id domain socket is still held, so E+1 is both the safe map key and the
correct hot-restart epoch to attach at — no restructuring of the children map.

S15 (same function): nextEpoch was incremented BEFORE cmd.Start(), with no
rollback. A fork failure is non-fatal on the handleDebounce path ("keeping
current epoch"), so currentEpoch() was left naming an epoch with no child — and
both wedge watchdogs and the readiness hold are gated on childTracked(epoch), so
none of them could fire again: pod NotReady forever, no watchdog, old Envoy
still serving. Fix: publish nextEpoch only after Start() succeeds.

S16 (coordination.go, initStartEpoch): the successor readiness gate was set by a
separate gateReadinessIfSuccessor() call AFTER nextEpoch was published. A
watchLiveness tick landing in that window reads the successor epoch E and finds
the PREDECESSOR's Envoy answering LIVE at exactly E, so it marks the pod Ready
before this pod's Envoy has been forked — #132's hazard re-entering through the
retry path, where the previous gate is certainly stale (retries run up to 4.5min
against a 15s parent-shutdown-time). Fix: nextEpoch and readyGate are now
published in one critical section; gateReadinessIfSuccessor and setReadyGate are
gone.

S17 (coordination.go, onNotLiveEpoch): the readiness hold asked
childTracked(currentEpoch()). Between resetEpochForRetry and the relaunch —
which includes initStartEpoch's up-to-8s re-probe loop — currentEpoch() is -1,
an epoch that never had a child, so a supervisor that was Ready on epoch 0 and
lost a just-forked epoch 1 to a bind collision cleared its ready marker (and
recorded ready_transitions{ready=false}) for the whole retry while its epoch-0
Envoy was still serving every request on the node. Fix: hold on
anyChildTracked() — "is one of our Envoy processes still serving this node?" —
which is the question the hold was always documented to be asking. This is a
candidate mechanism for the still-open proxy readiness-marker flap seen on
w01/w05 in the 2026-09-03 soak.

Tests (agent/internal/proxy/hotrestart/epoch_test.go), one per finding:

  • TestReserveEpochNeverReusesATrackedEpoch: relaunch with epoch 0 still tracked
    lands on epoch 1, both children stay independently addressable.
  • TestHotRestartDoesNotAdvanceEpochWhenStartFails: after a failed fork,
    currentEpoch() still names a tracked child.
  • TestInitStartEpochPublishesEpochAndGateTogether (+ a no-predecessor control):
    initStartEpoch alone must leave the gate in the future.
  • TestReadinessHeldWhileAnEarlierEpochStillServes: hold at epoch -1 with epoch 0
    tracked; clear once nothing of ours is left.

Verification: bazel test //agent/internal/proxy/... passes, including the
existing #132 hold test (TestReadinessHeldWhileServingParentMidHandoff) and the
bind-collision retry test.

fix(proxy-supervisor): route the atomic writes through common/file (#772)

S24/S25 from the 2026-09-15 race review.

S24 CONFIRMED, two sites, both bypassing common/file with a FIXED temp filename
and no fsync:

  • agent/internal/cmd/supervisor.go installFile staged at dest + ".tmp" and
    renamed without flushing. What it publishes is an EXECUTABLE that the proxy
    container then runs as its entrypoint, so an un-fsynced rename can survive a
    node crash as a directory entry pointing at data that was never written, and
    a fixed temp path is a collision waiting for any second writer.
  • agent/internal/proxy/hotrestart/coordination.go writeState staged at
    <statePath>.tmp on the SHARED hostPath StateDir. The flock around the
    read-check-write is explicitly best-effort ("a lock failure falls back to the
    unlocked behavior"), and on that fallback two overlapping supervisor pods
    write the same temp path — so the rename can publish the other process's
    half-written bytes into the file that decides the next pod's restart epoch.

Both now go through common/file (AtomicWriteReader / AtomicWrite): os.CreateTemp
for a per-writer name, and the flush-before-rename that PR #779 is adding there,
which both sites then inherit for free.

S25 REFUTED as a defect, and annotated in place: coordination.go setReady's
plain os.WriteFile on the readiness marker is correct. The marker is a pod-local
emptyDir file whose only reader (//agent/cmd/proxy-ready via readymarker.Check)
tests for existence and never reads a byte — no torn read to prevent, no second
writer, and nothing worth making durable across a crash. An atomic write would
add a temp file and an fsync to the supervisor's hottest path for no observable
gain. Left as is with a comment saying why.

Tests: TestInstallFile gains a concurrent-installs case (8 writers, same
destination, a payload large enough to splice) asserting the published file is
whole and that no staging file of ANY name survives — the previous assertion
only knew to look for the old fixed dest + ".tmp".

Verification: bazel test //agent/internal/cmd/... //agent/internal/proxy/...
passes.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

bpalermo and others added 5 commits September 15, 2026 21:47
…shutdown (#771) (#772)

handleShutdown has exactly one call site — `case <-lp.ctx.Done()` in
restartLoop.run — so the context it is handed is ALWAYS already cancelled by
controller-runtime's signal handler. It passed that context straight into the
epoch-identity probe (adminLiveAtEpoch -> adminServerInfo ->
context.WithTimeout on an already-cancelled parent), so http.Client.Do failed
with "context canceled" in microseconds without ever opening a socket.
`!adminLiveAtEpoch(...)` was therefore true on every SIGTERM regardless of
Envoy's actual state, and the "termination requested mid-handoff; waiting for
successor" branch was taken unconditionally — including when Envoy was LIVE at
our own epoch and no successor existed, in which case Envoy was never drained.

Measured on talos-main (issue #771 reproduction): both sampled pods recorded
`aether_supervisor_admin_probes_total{probe_endpoint="server_info",
result="unreachable"}` exactly once in a 2d21h lifetime — at their SIGTERM —
while `result="live"` was still climbing +10/30s on the same series and
`envoy_server_state` was 0 (LIVE). The mid-handoff line was logged 194ms/195ms
after the delete, 4.3-6.3s before any successor Envoy started.

Fix: run the probe on a context detached from the caller's, keeping its values
but not its cancellation, bounded by shutdownProbeTimeout. This is the same
trap and the same idiom as common/telemetry/setup/lifecycle.go's
DetachedTimeout (issue #662). The branch semantics are unchanged: admin LIVE at
our epoch -> drain; not LIVE at our epoch (a successor has taken the admin
port) -> leave Envoy alone for the successor's parent-shutdown protocol.

Tests (agent/internal/proxy/hotrestart/shutdown_test.go), both driving
handleShutdown with an already-cancelled context against a production-shaped
supervisor (StateDir set, real admin address, a live tracked child at epoch 0):
- LIVE at our own epoch -> drain branch taken, child SIGTERMed and reaped, and
  the fake admin's /server_info hit counter advanced (i.e. the probe really
  reached the network).
- LIVE at epoch 1 -> the genuine mid-handoff case: still blocks, child
  untouched, and the decision was again made off a real probe.
Reverting the WithoutCancel makes the first test fail with "handleShutdown
blocked: the drain branch was not taken", which is the production bug verbatim.

Verification: bazel test //agent/internal/proxy/... passes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
…own grace period (#771) (#772)

awaitProtocolTermination was a bare `<-s.childExited` loop with no deadline and
no context, so a termination where no successor can ever appear — graceful node
shutdown, node deletion / scale-down, `kubectl delete daemonset` or a chart
uninstall, or a replacement stuck Pending/ImagePullBackOff/unschedulable —
blocked until the kubelet's SIGKILL at terminationGracePeriodSeconds with Envoy
never SIGTERMed and connections still open. With #771's ctx fix that branch is
now entered only when admin really answers at another epoch, but the residual
exposure is real, and it is precisely the case a `kubectl delete pod` cannot
reproduce (the DaemonSet's replacement hot-restarts the parent within ~1s, so a
delete self-rescues into the surge path).

The fix is deliberately NOT a blind timer. The function's own comment explains
why there wasn't one: the successor's parent-shutdown timer starts only after
its xDS-gated, unbounded init, and it keeps using the parent socket for stat
merges right up to protocol-terminate, so cutting a healthy handoff short
aborts the successor with errno 111 (the 2026-06-11 node data-plane gap). The
only non-arbitrary bound is the pod's own death sentence, so the supervisor is
now told what it is:

- Config.TerminationGrace / --termination-grace, passed by the chart from the
  same value it sets on terminationGracePeriodSeconds (0 = unknown = wait
  indefinitely, i.e. the previous behavior, which is what every older chart
  and every unit-test supervisor gets).
- successorWaitBudget = TerminationGrace - (DrainTime + shutdownGrace) -
  terminationFallbackMargin(10s): wait as long as the pod has, minus what the
  drain will then cost, minus head-room. Deployed values give 155s of 180s. A
  grace period too small to fit a drain yields 0 and keeps waiting rather than
  guaranteeing an errno-111 abort.
- On expiry: log at WARN with the epoch state observed at that moment (a fresh
  probe, again on a detached context), then s.shutdown() — SIGTERM every
  tracked epoch and reap, so Envoy drains and exits 0 before the SIGKILL.

Also fixes the stale comment at the top of handleShutdown, which promised "a
deadline fallback" that did not exist; the function comment on
awaitProtocolTermination said the opposite. Both now describe the same thing.

Chart: proxy.terminationGracePeriodSeconds (default 180, unchanged behavior)
replaces the hard-coded literal and feeds both the pod spec and the new flag.
charts/aether bumped 0.92.19 -> 0.92.20.

Tests:
- TestSuccessorWaitBudget pins the arithmetic at the deployed values, at an
  unset grace, and at a grace too small to fit a drain.
- TestHandleShutdownFallsBackToDrainWhenNoSuccessorComes: admin LIVE at a newer
  epoch (mid-handoff branch correctly entered) with nothing ever terminating
  our Envoy — the wait expires at the budget, not before it, and the child is
  drained and reaped.

Verification: bazel test //agent/internal/proxy/... //agent/internal/cmd/...
passes; `helm template` renders terminationGracePeriodSeconds: 180 and
--termination-grace=180s.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
…p before fork, atomic gate publish, readiness held across retries (#772)

The four epoch findings from the 2026-09-15 race review (S14-S17), all four
confirmed from the code and all four reachable only through the bind-collision
retry path, which is why none of them shows up in a normal roll.

S14 (supervisor.go, hotRestart): `s.children[epoch] = cmd` could reuse a key
whose child is still tracked. resetEpochForRetry rewinds nextEpoch to 0 on every
retry and initStartEpoch leaves it there when the heartbeat is stale, so a
relaunch overwrote the *exec.Cmd of a still-draining epoch-0 Envoy. The draining
process was then orphaned (signalEpoch resolves epoch 0 to the new cmd, so
shutdown() never signals it), awaitProtocolTermination's pending count
undercounted it, and its eventual exit could take the container down non-zero
while the new Envoy was healthy. Fix: reserveEpoch() advances past any epoch
still present in children and logs when it does. A tracked child at E also means
E's base-id domain socket is still held, so E+1 is both the safe map key and the
correct hot-restart epoch to attach at — no restructuring of the children map.

S15 (same function): nextEpoch was incremented BEFORE cmd.Start(), with no
rollback. A fork failure is non-fatal on the handleDebounce path ("keeping
current epoch"), so currentEpoch() was left naming an epoch with no child — and
both wedge watchdogs and the readiness hold are gated on childTracked(epoch), so
none of them could fire again: pod NotReady forever, no watchdog, old Envoy
still serving. Fix: publish nextEpoch only after Start() succeeds.

S16 (coordination.go, initStartEpoch): the successor readiness gate was set by a
separate gateReadinessIfSuccessor() call AFTER nextEpoch was published. A
watchLiveness tick landing in that window reads the successor epoch E and finds
the PREDECESSOR's Envoy answering LIVE at exactly E, so it marks the pod Ready
before this pod's Envoy has been forked — #132's hazard re-entering through the
retry path, where the previous gate is certainly stale (retries run up to 4.5min
against a 15s parent-shutdown-time). Fix: nextEpoch and readyGate are now
published in one critical section; gateReadinessIfSuccessor and setReadyGate are
gone.

S17 (coordination.go, onNotLiveEpoch): the readiness hold asked
childTracked(currentEpoch()). Between resetEpochForRetry and the relaunch —
which includes initStartEpoch's up-to-8s re-probe loop — currentEpoch() is -1,
an epoch that never had a child, so a supervisor that was Ready on epoch 0 and
lost a just-forked epoch 1 to a bind collision cleared its ready marker (and
recorded ready_transitions{ready=false}) for the whole retry while its epoch-0
Envoy was still serving every request on the node. Fix: hold on
anyChildTracked() — "is one of our Envoy processes still serving this node?" —
which is the question the hold was always documented to be asking. This is a
candidate mechanism for the still-open proxy readiness-marker flap seen on
w01/w05 in the 2026-09-03 soak.

Tests (agent/internal/proxy/hotrestart/epoch_test.go), one per finding:
- TestReserveEpochNeverReusesATrackedEpoch: relaunch with epoch 0 still tracked
  lands on epoch 1, both children stay independently addressable.
- TestHotRestartDoesNotAdvanceEpochWhenStartFails: after a failed fork,
  currentEpoch() still names a tracked child.
- TestInitStartEpochPublishesEpochAndGateTogether (+ a no-predecessor control):
  initStartEpoch alone must leave the gate in the future.
- TestReadinessHeldWhileAnEarlierEpochStillServes: hold at epoch -1 with epoch 0
  tracked; clear once nothing of ours is left.

Verification: bazel test //agent/internal/proxy/... passes, including the
existing #132 hold test (TestReadinessHeldWhileServingParentMidHandoff) and the
bind-collision retry test.

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

S24/S25 from the 2026-09-15 race review.

S24 CONFIRMED, two sites, both bypassing common/file with a FIXED temp filename
and no fsync:

- agent/internal/cmd/supervisor.go installFile staged at `dest + ".tmp"` and
  renamed without flushing. What it publishes is an EXECUTABLE that the proxy
  container then runs as its entrypoint, so an un-fsynced rename can survive a
  node crash as a directory entry pointing at data that was never written, and
  a fixed temp path is a collision waiting for any second writer.
- agent/internal/proxy/hotrestart/coordination.go writeState staged at
  `<statePath>.tmp` on the SHARED hostPath StateDir. The flock around the
  read-check-write is explicitly best-effort ("a lock failure falls back to the
  unlocked behavior"), and on that fallback two overlapping supervisor pods
  write the same temp path — so the rename can publish the other process's
  half-written bytes into the file that decides the next pod's restart epoch.

Both now go through common/file (AtomicWriteReader / AtomicWrite): os.CreateTemp
for a per-writer name, and the flush-before-rename that PR #779 is adding there,
which both sites then inherit for free.

S25 REFUTED as a defect, and annotated in place: coordination.go setReady's
plain os.WriteFile on the readiness marker is correct. The marker is a pod-local
emptyDir file whose only reader (//agent/cmd/proxy-ready via readymarker.Check)
tests for existence and never reads a byte — no torn read to prevent, no second
writer, and nothing worth making durable across a crash. An atomic write would
add a temp file and an fsync to the supervisor's hottest path for no observable
gain. Left as is with a comment saying why.

Tests: TestInstallFile gains a concurrent-installs case (8 writers, same
destination, a payload large enough to splice) asserting the published file is
whole and that no staging file of ANY name survives — the previous assertion
only knew to look for the old fixed `dest + ".tmp"`.

Verification: bazel test //agent/internal/cmd/... //agent/internal/proxy/...
passes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo force-pushed the fix/772-a5-supervisor-shutdown branch from c078cc8 to f3f83bc Compare September 16, 2026 00:48
@bpalermo
bpalermo merged commit 7af2da5 into main Sep 16, 2026
20 checks passed
@bpalermo
bpalermo deleted the fix/772-a5-supervisor-shutdown branch September 16, 2026 00:56
bpalermo added a commit that referenced this pull request Sep 16, 2026
…fore draining; graceful drain fallback (#795) (#797)

#785 fixed the epoch-identity probe at shutdown (it had been running on an
already-cancelled context and failing in microseconds without opening a socket),
and in doing so removed the accident that had been keeping pod termination
hitless. With the probe working, "admin LIVE at our own epoch" now correctly
routed to s.shutdown() — a bare SIGTERM, which Envoy does not drain on. The
supervisor then WON the race against its own DaemonSet surge replacement:
rev214, two samples on worker-04/05, termination 2.27s/1.55s, the replacement
logging "no live predecessor; starting fresh at epoch 0", 7.95s/8.11s with no
Envoy on the node and 130/126 prober connection_errors, AetherProberLivenessErrors
paging CRITICAL. Pre-#785 on rev213 the same delete took 21-23s, drained Envoy
and cost zero prober errors. `kubectl delete pod` is also the code path of node
drain, eviction and preemption.

The design error is the premise that "no handoff in progress" means "nobody is
coming". For a DaemonSet with maxSurge and a transparent-capture node proxy the
replacement is created within ~1s of the deletionTimestamp and hot-restarts us.
So the pre-#785 behaviour becomes deliberate and bounded, and the fallback
becomes a real drain.

handleShutdown now resolves a SIGTERM onto exactly one of four branches, off one
authoritative /server_info probe (still on a detached ctx — #785's fix is kept,
and it is now also what tells "answered at another epoch" apart from "did not
answer at all"):

  admin LIVE at a NEWER epoch   genuine mid-handoff -> wait for the successor's
                                parent-shutdown protocol, bounded by #785's
                                successorWaitBudget.            -> handoff
  admin LIVE at OUR epoch       no handoff yet -> keep the child SERVING and
                                wait for the surge successor on the same budget
                                (155s at the chart default).    -> successor_wait
  admin unreachable             child dead or main thread wedged; nothing to
                                drain.                          -> child_dead
  budget expired, or
  --shutdown-drain-immediately  POST /drain_listeners?graceful, wait
                                --drain-time (10s as deployed), then SIGTERM
                                and reap.                       -> drain_fallback

A serving Envoy is never bare-SIGTERMed again: shutdown() is split into
terminateChildren() plus the histogram, drainThenShutdown() wraps it with the
graceful drain, and shutdown()'s doc now says where it is and is not correct.
--shutdown-drain-immediately (default false, documented in docs/configuration.md,
NOT set by the chart) is the escape hatch for a deployment where no replacement
can overlap the pod; StateDir == "" takes the same path, since a supervisor with
no cross-pod coordination can have no successor either.

Observability (the drain path had none — "closing and draining listeners" is
Envoy's line, not ours, and aether_supervisor_drain_duration_* has never reached
Prometheus):
- aether.supervisor.shutdown.branch counter, attribute
  aether.supervisor.shutdown.branch in {handoff, successor_wait, drain_fallback,
  child_dead}, SEEDED AT ZERO for all four (#717: the OTel SDK exports a counter
  only after its first Add, and this one is incremented exactly once per pod
  lifetime, so unseeded "never taken" and "never registered" are the same empty
  query).
- aether.supervisor.drain.duration now spans the WHOLE fallback — the graceful
  drain window included — and is recorded even when Envoy exits during its own
  drain sequence, which is the case terminateChildren then has nothing to report.
- INFO lines: "waiting for a successor before draining" (with the budget),
  "successor took over during shutdown wait", "no successor within budget;
  draining listeners", "listeners drained; stopping envoy". The existing WARN
  fallback line and every existing counter are kept.

Tests (agent/internal/proxy/hotrestart/shutdown_test.go, extending #785's;
fakeAdminServer gains a /drain_listeners handler recording hits and the query
string):
- TestHandleShutdownWaitsForTheSurgeSuccessor — LIVE at our epoch, budget 14s,
  successor arrives at 2s: the child is still tracked and undrained at 1s, the
  wait ends on the successor and not at the budget, zero drain calls, and the
  probe really reached the admin (#771's assertion, carried over).
- TestHandleShutdownDrainsGracefullyWhenNoSuccessorArrives — LIVE at our epoch,
  budget 2s, nobody comes: /drain_listeners?graceful hit exactly once, the
  budget plus DrainTime is spent, then SIGTERM and reap.
- TestHandleShutdownDrainsImmediatelyWhenToldTo — the escape hatch drains at
  once, still gracefully, without spending the budget.
- TestHandleShutdownStopsADeadChildWithoutDraining — an unreachable admin is not
  asked to drain and does not enter a successor wait.
- TestHandleShutdownWaitsForGenuineSuccessor and
  TestHandleShutdownFallsBackToDrainWhenNoSuccessorComes (the mid-handoff branch)
  are unchanged in behaviour; the latter now also asserts the fallback is the
  graceful drain.
- TestShutdownBranchesSeededAtZero / TestShutdownBranchRecording.

Proof the first test catches the production regression: with handleShutdown's
body replaced by main's, TestHandleShutdownWaitsForTheSurgeSuccessor fails at
shutdown_test.go:94 — "envoy was stopped while a surge successor could still have
hot-restarted it" after 1.03s — because main takes the drain branch immediately
and the child is already SIGTERMed and reaped. The two drain tests fail on main
at 33ms with zero /drain_listeners hits.

#785's TestHandleShutdownProbesOnDetachedCtxAndDrains asserted the very behaviour
this issue reverses (drain immediately when LIVE at our own epoch), so it is
rewritten rather than removed: its #771 assertion — that the branch decision was
made off a probe that really reached the network — is carried into the new test
above, which is also what still fails if the WithoutCancel is reverted.

Docs: docs/runbook.md gains a supervisor/termination section with the four-branch
table, what to expect on `kubectl delete pod` (~20-25s, zero data-plane cost, the
log lines to grep, and why a 1-2s termination is the alarming outcome), and the
PromQL for the seeded branch counter; docs/configuration.md documents
--shutdown-drain-immediately and --termination-grace. No chart change.

Verification: bazel build //... //test/e2e:e2e_test; bazel test //...
(105 pass); bazel test --config=race --runs_per_test=3 on
//agent/internal/proxy/hotrestart, //agent/internal/supervisorcmd and
//agent/cmd/proxy-supervisor:deps_test; scripts/check-proxy-supervisor-deps.sh OK
(the supervisor links none of the forbidden packages); //test/envoy_validate
pass; bazel run //:format.check clean; bazel build --config=lint
--@aspect_rules_lint//lint:fail_on_violation //... clean; bazel run //:gazelle no
churn; bazel mod tidy idempotent; scripts/go-deps-audit.sh OK.

Refs #771, #785, #772.


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.

proxy-supervisor: shutdown admin probe runs on the already-cancelled ctx, so SIGTERM may never drain Envoy (needs reproduction)

1 participant