fix(daemon): shut down on SIGTERM instead of being killed

The daemon is PID 1 in its container and the loop watched only ctrl-c.
SIGTERM is what a rollout, a `kubectl delete` and a node drain send, and
the kernel drops a signal whose init has no handler: `kill -TERM 1`
inside the pod left the daemon running. So nothing ever asked the live
turns to stop, and however the process ended, it ended with them
mid-step: the client's stream dead without an end frame, the record
holding a dangling call for the next boot to repair.

The loop watches SIGTERM beside ctrl-c now, and the signal can land
mid-pass: the pass is a future the loop holds across the select instead
of awaiting it bare, so the shutdown arm answers while a turn is still
running. It cuts every live turn through the abort registry, which all
three handlers listen on, so each turn closes its dangling calls and
writes its session back before releasing, the same end the abort route
gives it. The pass then has ten seconds to return, and the forge and
jobs lanes, which run as tasks off the tick, share that deadline.

The binary takes both signals: SIGTERM and SIGINT exit 0 in 25 ms with
"shutting down" in the log. The registry's new signal_all is
unit-tested across two live keys.
This commit is contained in:
vhaudiquet committed 2026-12-02 12:36:59 +01:00
1 parent 5504c6a91b
commit b5ecc1268c
2 files changed
+145 -8

No files matched your search

+35
View File
@@ -57,6 +57,25 @@ impl AbortRegistry {
} }
} }
/// Cuts every live dispatch, `n` of them: what the daemon's shutdown
/// does so each running turn ends the way the abort route ends it —
/// dangling calls closed, session written back, released — instead
/// of vanishing with the process. The count is the listeners that
/// took the signal.
pub fn signal_all(&self) -> usize {
let senders: Vec<mpsc::Sender<()>> = self
.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.values()
.cloned()
.collect();
senders
.iter()
.filter(|sender| sender.try_send(()).is_ok())
.count()
}
/// Arms a listener for `key`. The guard is the dispatch's side: hold /// Arms a listener for `key`. The guard is the dispatch's side: hold
/// it across the whole dispatch chain, drop it to unregister. /// it across the whole dispatch chain, drop it to unregister.
pub fn listen(self: &Arc<Self>, key: &str) -> AbortGuard { pub fn listen(self: &Arc<Self>, key: &str) -> AbortGuard {
@@ -165,6 +184,22 @@ mod tests {
assert!(!registry.signal("job:rhema#7"), "the entry is gone"); assert!(!registry.signal("job:rhema#7"), "the entry is gone");
} }
#[test]
fn signal_all_cuts_every_live_dispatch() {
let registry = Arc::new(AbortRegistry::new());
let mut interactive = registry.listen("interactive:web");
let mut forge = registry.listen("github:issue:acme/widgets#7");
assert_eq!(registry.signal_all(), 2);
assert!(interactive.take(), "the chat turn is cut");
assert!(forge.take(), "the forge turn is cut too");
// With nothing live the count is zero, not an error.
drop(interactive);
drop(forge);
assert_eq!(registry.signal_all(), 0);
}
#[test] #[test]
fn keys_abort_independently() { fn keys_abort_independently() {
let registry = Arc::new(AbortRegistry::new()); let registry = Arc::new(AbortRegistry::new());
+110 -8
View File
@@ -760,9 +760,16 @@ impl Daemon {
/// The resident loop: the HTTP surface comes up first (a resident is /// The resident loop: the HTTP surface comes up first (a resident is
/// talked to), then detect, hand the long lanes to their own tasks, /// talked to), then detect, hand the long lanes to their own tasks,
/// sleep, until ctrl-c. A failed pass is logged, not fatal — a forge /// sleep, until a shutdown signal. A failed pass is logged, not
/// outage or a dead backend must not end a daemon whose next pass may /// fatal — a forge outage or a dead backend must not end a daemon
/// simply succeed. /// whose next pass may simply succeed.
///
/// Shutting down is graceful because the alternative is losing a
/// turn to the kernel: the daemon is PID 1 in its container, and a
/// signal it has no handler for is dropped, so the kubelet waits out
/// the grace period and SIGKILLs the process wherever its turn
/// happens to be. [`shutdown_signal`] watches SIGTERM, the signal a
/// rollout and a `kubectl delete` send, alongside ctrl-c.
pub async fn run(&self) -> Result<(), ClawError> { pub async fn run(&self) -> Result<(), ClawError> {
self.bootstrap().await?; self.bootstrap().await?;
let listener = tokio::net::TcpListener::bind(&self.listen).await?; let listener = tokio::net::TcpListener::bind(&self.listen).await?;
@@ -774,18 +781,113 @@ impl Daemon {
} }
}); });
eprintln!("[claw] http listening on {addr}"); eprintln!("[claw] http listening on {addr}");
let mut shutdown = std::pin::pin!(shutdown_signal());
loop { loop {
if let Err(err) = self.resident_tick().await { // The pass is a future the loop keeps across the signal
// rather than await it bare: a rollout lands mid-turn more
// often than between turns, and dropping the future there
// would be the SIGKILL this exists to avoid.
let mut pass = std::pin::pin!(self.resident_tick());
let stopping = tokio::select! {
result = &mut pass => {
if let Err(err) = result {
eprintln!("[claw] warning: pass failed: {err}"); eprintln!("[claw] warning: pass failed: {err}");
} }
tokio::select! { false
() = tokio::time::sleep(self.poll_interval) => {} }
_ = tokio::signal::ctrl_c() => { () = &mut shutdown => {
let deadline = self.start_shutdown();
if tokio::time::timeout_at(deadline, &mut pass).await.is_err() {
eprintln!(
"[claw] shutdown: the interactive pass did not return in {SHUTDOWN_DRAIN:?}"
);
}
self.await_off_tick_passes(deadline).await;
true
}
};
if stopping {
break;
}
let stopping = tokio::select! {
() = tokio::time::sleep(self.poll_interval) => false,
() = &mut shutdown => {
let deadline = self.start_shutdown();
self.await_off_tick_passes(deadline).await;
true
}
};
if stopping {
break;
}
}
server.abort(); server.abort();
return Ok(()); Ok(())
}
/// Opens a shutdown: logs it, cuts every live turn, and answers the
/// deadline the drain shares. All three handlers listen on the abort
/// registry, so each running turn ends the way the abort route ends
/// it — dangling calls closed, session written back, released —
/// instead of dying wherever it was.
fn start_shutdown(&self) -> tokio::time::Instant {
eprintln!("[claw] shutting down");
let cut = self.http.aborts().signal_all();
if cut > 0 {
eprintln!("[claw] shutdown: cutting {cut} live turn(s)");
}
tokio::time::Instant::now() + SHUTDOWN_DRAIN
}
/// Waits for the lanes that run off the tick, up to `deadline`. Their
/// passes are tasks this loop spawned, so cutting a turn only asks
/// its task to end; the release that writes the session back lands a
/// moment later.
async fn await_off_tick_passes(&self, deadline: tokio::time::Instant) {
while self.forge_pass_busy.load(Ordering::Acquire)
|| self.jobs_pass_busy.load(Ordering::Acquire)
{
if tokio::time::Instant::now() >= deadline {
eprintln!("[claw] shutdown: a forge or jobs pass is still running");
return;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
}
/// How long a shutdown waits for the work it cut to return: a cut turn
/// closes its dangling calls and writes its session back in well under a
/// second, and a hung one must not hold the process past the pod's grace
/// period.
const SHUTDOWN_DRAIN: Duration = Duration::from_secs(10);
/// Resolves on the first shutdown signal: SIGTERM, which is what a
/// rollout and a `kubectl delete` send, or SIGINT from a shell. Watching
/// only ctrl-c meant the daemon never saw a rollout coming, and the
/// kubelet SIGKILLed it once the grace period ran out.
async fn shutdown_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
match signal(SignalKind::terminate()) {
Ok(mut terminate) => {
tokio::select! {
_ = terminate.recv() => {}
_ = tokio::signal::ctrl_c() => {}
}
}
Err(err) => {
// Without the stream a rollout ends at the grace period
// instead of here; ctrl-c still works.
eprintln!("[claw] warning: cannot watch SIGTERM: {err}");
let _ = tokio::signal::ctrl_c().await;
} }
} }
} }
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
} }
} }