Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(personhog): ordered shutdown phases for the lifecycle manager (#71244)

Zach Brown5bb18c0c4778
diff --git a/rust/common/lifecycle/src/handle.rs b/rust/common/lifecycle/src/handle.rs
index 4b310b5b5cf1..4fa345a79383 100644
--- a/rust/common/lifecycle/src/handle.rs
+++ b/rust/common/lifecycle/src/handle.rs
@@ -61,7 +61,9 @@ pub(crate) struct HandleInner {
impl Handle {
/// Future that resolves when shutdown begins for this handle's tier.
- /// Standard handles: resolves when global shutdown begins.
+ /// Standard handles: resolves when global shutdown begins — or, for a
+ /// component registered with `with_shutdown_phase(n)` for n > 0, once
+ /// every earlier phase's components have finished.
/// Observability handles: resolves after all standard components finish.
/// Use in `tokio::select!` to break out of work loops.
pub fn shutdown_recv(&self) -> tokio_util::sync::WaitForCancellationFuture<'_> {
diff --git a/rust/common/lifecycle/src/manager.rs b/rust/common/lifecycle/src/manager.rs
index 90ecbe49cf36..7c94d5e8afea 100644
--- a/rust/common/lifecycle/src/manager.rs
+++ b/rust/common/lifecycle/src/manager.rs
@@ -88,6 +88,7 @@ impl ManagerBuilder {
health_poll_interval: self.health_poll_interval,
shutdown_token: self.external_shutdown_token.unwrap_or_default(),
observability_shutdown_token: CancellationToken::new(),
+ phase_tokens: HashMap::new(),
event_tx_slot: Arc::new(OnceLock::new()),
components: HashMap::new(),
observability_components: HashMap::new(),
@@ -102,18 +103,21 @@ pub struct ComponentOptions {
graceful_shutdown: Option<Duration>,
liveness_deadline: Option<Duration>,
stall_threshold: u32,
+ shutdown_phase: u8,
pub(crate) is_observability: bool,
pub(crate) is_advisory: bool,
config_errors: Vec<String>,
}
impl ComponentOptions {
- /// No graceful shutdown timeout, no liveness deadline, stall threshold 1.
+ /// No graceful shutdown timeout, no liveness deadline, stall threshold 1,
+ /// shutdown phase 0.
pub fn new() -> Self {
Self {
graceful_shutdown: None,
liveness_deadline: None,
stall_threshold: 1,
+ shutdown_phase: 0,
is_observability: false,
is_advisory: false,
config_errors: Vec::new(),
@@ -185,6 +189,27 @@ impl ComponentOptions {
self.stall_threshold = n.max(1);
self
}
+
+ /// Order this component within graceful shutdown. Phases drain in
+ /// ascending order: a component in phase N+1 is not signalled — its
+ /// shutdown token stays uncancelled — until every phase ≤ N component
+ /// has finished (completed, died, or timed out its graceful window).
+ /// Components within one phase drain concurrently. Default: 0, which is
+ /// signalled the moment shutdown begins, exactly as before this option
+ /// existed.
+ ///
+ /// Use this when one component's cleanup depends on another still
+ /// serving: e.g. a coordination drain (phase 0) that must complete
+ /// requests through the gRPC server and producer (phase 1) before they
+ /// stop. The component's graceful window is measured from when its
+ /// phase begins, not from the start of shutdown; the global shutdown
+ /// timeout bounds the whole sequence. Observability components remain a
+ /// final implicit stage after every standard phase.
+ /// (see test `later_phase_not_signalled_until_earlier_phase_completes`)
+ pub fn with_shutdown_phase(mut self, phase: u8) -> Self {
+ self.shutdown_phase = phase;
+ self
+ }
}
impl Default for ComponentOptions {
@@ -194,7 +219,7 @@ impl Default for ComponentOptions {
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-enum ShutdownPhase {
+enum ComponentStatus {
Running,
ShuttingDown,
Completed,
@@ -204,7 +229,8 @@ enum ShutdownPhase {
struct ComponentState {
graceful_shutdown: Option<Duration>,
- phase: ShutdownPhase,
+ status: ComponentStatus,
+ shutdown_phase: u8,
}
/// Lifecycle manager: registers components, runs monitor on a dedicated OS thread, provides readiness/liveness handlers and shutdown signal.
@@ -217,6 +243,13 @@ pub struct Manager {
health_poll_interval: Duration,
shutdown_token: CancellationToken,
observability_shutdown_token: CancellationToken,
+ /// Tokens for shutdown phases above 0, cancelled in ascending phase
+ /// order once every earlier phase's components have finished. Phase 0
+ /// components share the root `shutdown_token` so the default behavior
+ /// (everything signalled at shutdown start, no monitor hop) is
+ /// unchanged. Independent tokens, not children of the root — a child
+ /// would cancel with its parent and defeat the ordering.
+ phase_tokens: HashMap<u8, CancellationToken>,
event_tx_slot: Arc<OnceLock<mpsc::Sender<ComponentEvent>>>,
components: HashMap<String, ComponentState>,
observability_components: HashMap<String, ComponentState>,
@@ -278,6 +311,18 @@ impl Manager {
"component '{}': observability handles cannot use liveness_deadline",
tag
);
+ assert!(
+ !(options.is_observability && options.shutdown_phase != 0),
+ "component '{}': observability handles are already the final shutdown stage; \
+ with_shutdown_phase has no effect",
+ tag
+ );
+ assert!(
+ !(options.is_advisory && options.shutdown_phase != 0),
+ "component '{}': advisory handles are not waited on during shutdown; \
+ with_shutdown_phase has no effect",
+ tag
+ );
let healthy_until_ms = Arc::new(AtomicI64::new(HEALTH_STARTING));
let health_flag = Arc::new(std::sync::atomic::AtomicBool::new(true));
@@ -327,15 +372,21 @@ impl Manager {
tag_owned.clone(),
ComponentState {
graceful_shutdown: options.graceful_shutdown,
- phase: ShutdownPhase::Running,
+ status: ComponentStatus::Running,
+ shutdown_phase: options.shutdown_phase,
},
);
}
let shutdown_token = if is_obs {
self.observability_shutdown_token.clone()
- } else {
+ } else if options.shutdown_phase == 0 {
self.shutdown_token.clone()
+ } else {
+ self.phase_tokens
+ .entry(options.shutdown_phase)
+ .or_default()
+ .clone()
};
let inner = Arc::new(HandleInner {
@@ -526,7 +577,7 @@ impl Manager {
let mut first_failure: Option<LifecycleError> = None;
- // --- Phase 1: Normal operation ---
+ // --- Stage 1: Normal operation ---
// Events from both standard and observability components trigger shutdown.
loop {
tokio::select! {
@@ -540,7 +591,7 @@ impl Manager {
"Lifecycle: shutdown initiated: {reason:#}");
shutdown_token.cancel();
if let Some(s) = self.get_component_mut(&tag) {
- s.phase = ShutdownPhase::Died;
+ s.status = ComponentStatus::Died;
}
first_failure = first_failure.or(Some(LifecycleError::ComponentFailure { tag, reason }));
break;
@@ -551,7 +602,7 @@ impl Manager {
"Lifecycle: shutdown initiated, component died unexpectedly");
shutdown_token.cancel();
if let Some(s) = self.get_component_mut(&tag) {
- s.phase = ShutdownPhase::Died;
+ s.status = ComponentStatus::Died;
}
first_failure = first_failure.or(Some(LifecycleError::ComponentDied { tag }));
break;
@@ -565,7 +616,7 @@ impl Manager {
}
ComponentEvent::WorkCompleted { tag } => {
if let Some(s) = self.get_component_mut(&tag) {
- s.phase = ShutdownPhase::Completed;
+ s.status = ComponentStatus::Completed;
}
if self.all_finished() {
return self.finalize(Instant::now(), first_failure);
@@ -581,139 +632,55 @@ impl Manager {
}
}
- // --- Phase 2: Standard component drain ---
+ // --- Stage 2: Standard component drain, in shutdown-phase order ---
let shutdown_clock = Instant::now();
let global_deadline = shutdown_clock + global_timeout;
- for s in self.components.values_mut() {
- if s.phase == ShutdownPhase::Running {
- s.phase = ShutdownPhase::ShuttingDown;
+ // Standard components drain in ascending shutdown-phase order: each
+ // phase's components are signalled and waited for together, and the
+ // next phase's token is only cancelled once the current phase has
+ // fully finished. Phase 0 shares the root token, so it is already
+ // signalled by the time this loop starts.
+ let mut phases: Vec<u8> = self.components.values().map(|s| s.shutdown_phase).collect();
+ phases.sort_unstable();
+ phases.dedup();
+
+ for phase in phases {
+ if phase != 0 {
+ info!(
+ shutdown_phase = phase,
+ "Lifecycle: advancing to shutdown phase"
+ );
+ if let Some(token) = self.phase_tokens.get(&phase) {
+ token.cancel();
+ }
}
- }
-
- if !self.all_standard_finished() {
- let mut component_deadlines: Vec<(String, Instant)> = self
+ let phase_clock = Instant::now();
+ for s in self
.components
- .iter()
- .filter_map(|(tag, s)| {
- s.graceful_shutdown
- .map(|d| (tag.clone(), shutdown_clock + d))
- })
- .collect();
- component_deadlines.sort_by(|a, b| a.1.cmp(&b.1));
-
- loop {
- let now = Instant::now();
- if now >= global_deadline {
- return self.emit_global_timeout(&name, global_timeout);
- }
-
- let next_component_timeout = component_deadlines
- .iter()
- .find(|(tag, _)| {
- self.components
- .get(tag)
- .map(|s| s.phase == ShutdownPhase::ShuttingDown)
- == Some(true)
- })
- .map(|(_, t)| *t);
-
- let wait_duration = [
- next_component_timeout.map(|t| t.saturating_duration_since(now)),
- Some(global_deadline.saturating_duration_since(now)),
- ]
- .into_iter()
- .flatten()
- .min()
- .unwrap_or(Duration::from_secs(1));
-
- tokio::select! {
- biased;
-
- Some(event) = event_rx.recv() => {
- match event {
- ComponentEvent::WorkCompleted { tag } => {
- if let Some(s) = self.get_component_mut(&tag) {
- if s.phase == ShutdownPhase::ShuttingDown {
- s.phase = ShutdownPhase::Completed;
- if !self.is_observability_tag(&tag) {
- let elapsed = shutdown_clock.elapsed();
- metrics::emit_component_shutdown_duration(&name, &tag, "completed", elapsed.as_secs_f64());
- metrics::emit_component_shutdown_result(&name, &tag, "completed");
- info!(component = %tag,
- duration_secs = elapsed.as_secs_f64(),
- result = "completed",
- "Lifecycle: component completed shutdown");
- }
- } else {
- debug!(component = %tag, phase = ?s.phase,
- "Lifecycle: late WorkCompleted for already-finished component");
- }
- }
- }
- ComponentEvent::Died { tag } => {
- if let Some(s) = self.get_component_mut(&tag) {
- s.phase = ShutdownPhase::Died;
- if !self.is_observability_tag(&tag) {
- let elapsed = shutdown_clock.elapsed();
- metrics::emit_component_shutdown_duration(&name, &tag, "died", elapsed.as_secs_f64());
- metrics::emit_component_shutdown_result(&name, &tag, "died");
- warn!(component = %tag,
- duration_secs = elapsed.as_secs_f64(),
- result = "died",
- "Lifecycle: component died during shutdown");
- }
- }
- }
- ComponentEvent::Failure { tag, reason } => {
- if let Some(s) = self.get_component_mut(&tag) {
- s.phase = ShutdownPhase::Died;
- if !self.is_observability_tag(&tag) {
- let elapsed = shutdown_clock.elapsed();
- metrics::emit_component_shutdown_duration(&name, &tag, "died", elapsed.as_secs_f64());
- metrics::emit_component_shutdown_result(&name, &tag, "died");
- warn!(component = %tag,
- duration_secs = elapsed.as_secs_f64(),
- result = "died",
- "Lifecycle: component failed during shutdown");
- }
- }
- first_failure = first_failure.or(Some(LifecycleError::ComponentFailure { tag, reason }));
- }
- ComponentEvent::ShutdownRequested { .. } => {}
- }
- if self.all_standard_finished() {
- break;
- }
- }
- _ = tokio::time::sleep(wait_duration) => {
- let now = Instant::now();
- for (tag, deadline) in &component_deadlines {
- if now >= *deadline {
- if let Some(s) = self.components.get_mut(tag) {
- if s.phase == ShutdownPhase::ShuttingDown {
- s.phase = ShutdownPhase::TimedOut;
- if let Some(d) = s.graceful_shutdown {
- metrics::emit_component_shutdown_duration(&name, tag, "timeout", d.as_secs_f64());
- }
- metrics::emit_component_shutdown_result(&name, tag, "timeout");
- warn!(component = %tag,
- duration_secs = s.graceful_shutdown.unwrap_or_default().as_secs_f64(),
- result = "timeout",
- "Lifecycle: component timed out during graceful shutdown");
- }
- }
- }
- }
- if self.all_standard_finished() {
- break;
- }
- }
+ .values_mut()
+ .filter(|s| s.shutdown_phase == phase)
+ {
+ if s.status == ComponentStatus::Running {
+ s.status = ComponentStatus::ShuttingDown;
}
}
+ if !self.phase_finished(phase) {
+ self.drain_standard_phase(
+ phase,
+ phase_clock,
+ shutdown_clock,
+ global_deadline,
+ global_timeout,
+ &mut event_rx,
+ &name,
+ &mut first_failure,
+ )
+ .await?;
+ }
}
- // --- Phase 3: Observability component drain ---
+ // --- Stage 3: Observability component drain ---
if self.observability_components.is_empty() {
return self.finalize_all(first_failure);
}
@@ -722,8 +689,8 @@ impl Manager {
self.observability_shutdown_token.cancel();
for s in self.observability_components.values_mut() {
- if s.phase == ShutdownPhase::Running {
- s.phase = ShutdownPhase::ShuttingDown;
+ if s.status == ComponentStatus::Running {
+ s.status = ComponentStatus::ShuttingDown;
}
}
@@ -753,7 +720,7 @@ impl Manager {
.find(|(tag, _)| {
self.observability_components
.get(tag)
- .map(|s| s.phase == ShutdownPhase::ShuttingDown)
+ .map(|s| s.status == ComponentStatus::ShuttingDown)
== Some(true)
})
.map(|(_, t)| *t);
@@ -774,20 +741,20 @@ impl Manager {
match event {
ComponentEvent::WorkCompleted { tag } => {
if let Some(s) = self.observability_components.get_mut(&tag) {
- if s.phase == ShutdownPhase::ShuttingDown {
- s.phase = ShutdownPhase::Completed;
+ if s.status == ComponentStatus::ShuttingDown {
+ s.status = ComponentStatus::Completed;
info!(component = %tag,
result = "completed",
"Lifecycle: observability component completed shutdown");
} else {
- debug!(component = %tag, phase = ?s.phase,
+ debug!(component = %tag, status = ?s.status,
"Lifecycle: late WorkCompleted for already-finished observability component");
}
}
}
ComponentEvent::Died { tag } => {
if let Some(s) = self.observability_components.get_mut(&tag) {
- s.phase = ShutdownPhase::Died;
+ s.status = ComponentStatus::Died;
warn!(component = %tag,
result = "died",
"Lifecycle: observability component died during shutdown");
@@ -795,7 +762,7 @@ impl Manager {
}
ComponentEvent::Failure { tag, reason } => {
if let Some(s) = self.observability_components.get_mut(&tag) {
- s.phase = ShutdownPhase::Died;
+ s.status = ComponentStatus::Died;
warn!(component = %tag,
result = "died",
"Lifecycle: observability component failed during shutdown: {reason}");
@@ -813,8 +780,8 @@ impl Manager {
for (tag, deadline) in &obs_deadlines {
if now >= *deadline {
if let Some(s) = self.observability_components.get_mut(tag) {
- if s.phase == ShutdownPhase::ShuttingDown {
- s.phase = ShutdownPhase::TimedOut;
+ if s.status == ComponentStatus::ShuttingDown {
+ s.status = ComponentStatus::TimedOut;
warn!(component = %tag,
duration_secs = s.graceful_shutdown
.unwrap_or(DEFAULT_OBSERVABILITY_SHUTDOWN_TIMEOUT)
@@ -836,11 +803,166 @@ impl Manager {
self.finalize_all(first_failure)
}
+ /// Wait until every component in `phase` finishes: completes, dies, or
+ /// times out its graceful window (measured from `phase_clock`, when the
+ /// phase was signalled). Events for components outside the phase — an
+ /// early exit or death of a later-phase component, or an observability
+ /// handle — still update that component's state so its own phase finds
+ /// it already finished. Errors only when the global deadline passes.
+ #[allow(clippy::too_many_arguments)]
+ async fn drain_standard_phase(
+ &mut self,
+ phase: u8,
+ phase_clock: Instant,
+ shutdown_clock: Instant,
+ global_deadline: Instant,
+ global_timeout: Duration,
+ event_rx: &mut mpsc::Receiver<ComponentEvent>,
+ name: &str,
+ first_failure: &mut Option<LifecycleError>,
+ ) -> Result<(), LifecycleError> {
+ let mut component_deadlines: Vec<(String, Instant)> = self
+ .components
+ .iter()
+ .filter(|(_, s)| s.shutdown_phase == phase)
+ .filter_map(|(tag, s)| s.graceful_shutdown.map(|d| (tag.clone(), phase_clock + d)))
+ .collect();
+ component_deadlines.sort_by(|a, b| a.1.cmp(&b.1));
+
+ loop {
+ let now = Instant::now();
+ if now >= global_deadline {
+ return self.emit_global_timeout(name, global_timeout);
+ }
+
+ let next_component_timeout = component_deadlines
+ .iter()
+ .find(|(tag, _)| {
+ self.components
+ .get(tag)
+ .map(|s| s.status == ComponentStatus::ShuttingDown)
+ == Some(true)
+ })
+ .map(|(_, t)| *t);
+
+ let wait_duration = [
+ next_component_timeout.map(|t| t.saturating_duration_since(now)),
+ Some(global_deadline.saturating_duration_since(now)),
+ ]
+ .into_iter()
+ .flatten()
+ .min()
+ .unwrap_or(Duration::from_secs(1));
+
+ tokio::select! {
+ biased;
+
+ Some(event) = event_rx.recv() => {
+ match event {
+ ComponentEvent::WorkCompleted { tag } => {
+ if let Some(s) = self.get_component_mut(&tag) {
+ // Running components can complete here too: a
+ // later-phase component may finish its work
+ // before its phase is ever signalled.
+ if matches!(
+ s.status,
+ ComponentStatus::ShuttingDown | ComponentStatus::Running
+ ) {
+ s.status = ComponentStatus::Completed;
+ if !self.is_observability_tag(&tag) {
+ let elapsed = shutdown_clock.elapsed();
+ metrics::emit_component_shutdown_duration(name, &tag, "completed", elapsed.as_secs_f64());
+ metrics::emit_component_shutdown_result(name, &tag, "completed");
+ info!(component = %tag,
+ duration_secs = elapsed.as_secs_f64(),
+ result = "completed",
+ "Lifecycle: component completed shutdown");
+ }
+ } else {
+ debug!(component = %tag, status = ?s.status,
+ "Lifecycle: late WorkCompleted for already-finished component");
+ }
+ }
+ }
+ ComponentEvent::Died { tag } => {
+ if let Some(s) = self.get_component_mut(&tag) {
+ s.status = ComponentStatus::Died;
+ if !self.is_observability_tag(&tag) {
+ let elapsed = shutdown_clock.elapsed();
+ metrics::emit_component_shutdown_duration(name, &tag, "died", elapsed.as_secs_f64());
+ metrics::emit_component_shutdown_result(name, &tag, "died");
+ warn!(component = %tag,
+ duration_secs = elapsed.as_secs_f64(),
+ result = "died",
+ "Lifecycle: component died during shutdown");
+ }
+ }
+ }
+ ComponentEvent::Failure { tag, reason } => {
+ if let Some(s) = self.get_component_mut(&tag) {
+ s.status = ComponentStatus::Died;
+ if !self.is_observability_tag(&tag) {
+ let elapsed = shutdown_clock.elapsed();
+ metrics::emit_component_shutdown_duration(name, &tag, "died", elapsed.as_secs_f64());
+ metrics::emit_component_shutdown_result(name, &tag, "died");
+ warn!(component = %tag,
+ duration_secs = elapsed.as_secs_f64(),
+ result = "died",
+ "Lifecycle: component failed during shutdown");
+ }
+ }
+ *first_failure = first_failure.take().or(Some(LifecycleError::ComponentFailure { tag, reason }));
+ }
+ ComponentEvent::ShutdownRequested { .. } => {}
+ }
+ if self.phase_finished(phase) {
+ return Ok(());
+ }
+ }
+ _ = tokio::time::sleep(wait_duration) => {
+ let now = Instant::now();
+ for (tag, deadline) in &component_deadlines {
+ if now >= *deadline {
+ if let Some(s) = self.components.get_mut(tag) {
+ if s.status == ComponentStatus::ShuttingDown {
+ s.status = ComponentStatus::TimedOut;
+ if let Some(d) = s.graceful_shutdown {
+ metrics::emit_component_shutdown_duration(name, tag, "timeout", d.as_secs_f64());
+ }
+ metrics::emit_component_shutdown_result(name, tag, "timeout");
+ warn!(component = %tag,
+ duration_secs = s.graceful_shutdown.unwrap_or_default().as_secs_f64(),
+ result = "timeout",
+ "Lifecycle: component timed out during graceful shutdown");
+ }
+ }
+ }
+ }
+ if self.phase_finished(phase) {
+ return Ok(());
+ }
+ }
+ }
+ }
+ }
+
+ fn phase_finished(&self, phase: u8) -> bool {
+ self.components
+ .values()
+ .filter(|s| s.shutdown_phase == phase)
+ .all(|s| {
+ matches!(
+ s.status,
+ ComponentStatus::Completed | ComponentStatus::Died | ComponentStatus::TimedOut
+ )
+ })
+ }
+
fn all_standard_finished(&self) -> bool {
self.components.values().all(|s| {
matches!(
- s.phase,
- ShutdownPhase::Completed | ShutdownPhase::Died | ShutdownPhase::TimedOut
+ s.status,
+ ComponentStatus::Completed | ComponentStatus::Died | ComponentStatus::TimedOut
)
})
}
@@ -848,8 +970,8 @@ impl Manager {
fn all_observability_finished(&self) -> bool {
self.observability_components.values().all(|s| {
matches!(
- s.phase,
- ShutdownPhase::Completed | ShutdownPhase::Died | ShutdownPhase::TimedOut
+ s.status,
+ ComponentStatus::Completed | ComponentStatus::Died | ComponentStatus::TimedOut
)
})
}
@@ -864,8 +986,8 @@ impl Manager {
.chain(self.observability_components.iter())
.filter(|(_, s)| {
!matches!(
- s.phase,
- ShutdownPhase::Completed | ShutdownPhase::TimedOut | ShutdownPhase::Died
+ s.status,
+ ComponentStatus::Completed | ComponentStatus::TimedOut | ComponentStatus::Died
)
})
.map(|(t, _)| t.clone())
@@ -908,7 +1030,7 @@ impl Manager {
.components
.values()
.chain(self.observability_components.values())
- .all(|s| s.phase == ShutdownPhase::Completed);
+ .all(|s| s.status == ComponentStatus::Completed);
metrics::emit_shutdown_completed(&self.name, clean);
if clean {
info!(
diff --git a/rust/common/lifecycle/tests/lifecycle_tests.rs b/rust/common/lifecycle/tests/lifecycle_tests.rs
index 550f9aa5ae1a..877a5b7762d2 100644
--- a/rust/common/lifecycle/tests/lifecycle_tests.rs
+++ b/rust/common/lifecycle/tests/lifecycle_tests.rs
@@ -1584,3 +1584,210 @@ async fn advisory_handle_stall_threshold_gates_is_healthy() {
.expect("timed out");
assert!(result.is_ok());
}
+
+// ---------------------------------------------------------------------------
+// Shutdown phases
+// ---------------------------------------------------------------------------
+
+/// A phase-1 component must not see shutdown until every phase-0 component
+/// has finished — the ordering that lets a coordination drain complete its
+/// handoffs through a still-serving gRPC server and producer.
+#[tokio::test]
+async fn later_phase_not_signalled_until_earlier_phase_completes() {
+ let shutdown_token = CancellationToken::new();
+ let mut manager = Manager::builder("test")
+ .with_trap_signals(false)
+ .with_prestop_check(false)
+ .with_global_shutdown_timeout(Duration::from_secs(5))
+ .with_shutdown_token(shutdown_token.clone())
+ .build();
+
+ let early = manager.register("early", ComponentOptions::new());
+ let late = manager.register("late", ComponentOptions::new().with_shutdown_phase(1));
+ let guard = manager.monitor_background();
+
+ let early_exited = Arc::new(AtomicBool::new(false));
+ let ordering_held = Arc::new(AtomicBool::new(false));
+ let early_exited_writer = early_exited.clone();
+ let early_exited_reader = early_exited.clone();
+ let ordering_held_writer = ordering_held.clone();
+
+ tokio::spawn(async move {
+ let _guard = early.process_scope();
+ early.shutdown_recv().await;
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ early_exited_writer.store(true, Ordering::SeqCst);
+ });
+
+ tokio::spawn(async move {
+ let _guard = late.process_scope();
+ late.shutdown_recv().await;
+ ordering_held_writer.store(early_exited_reader.load(Ordering::SeqCst), Ordering::SeqCst);
+ });
+
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ shutdown_token.cancel();
+
+ let result = tokio::time::timeout(Duration::from_secs(10), guard.wait())
+ .await
+ .expect("timed out");
+ assert!(result.is_ok());
+ assert!(
+ ordering_held.load(Ordering::SeqCst),
+ "phase 1 was signalled before phase 0 finished"
+ );
+}
+
+/// A later-phase component that reports work_completed during an earlier
+/// phase's drain (the one-shot pattern: finish, then idle holding the
+/// handle) must be recorded then — otherwise its own phase waits forever
+/// for a component that already finished.
+#[tokio::test]
+async fn later_phase_completion_during_earlier_drain_does_not_wedge() {
+ let shutdown_token = CancellationToken::new();
+ let mut manager = Manager::builder("test")
+ .with_trap_signals(false)
+ .with_prestop_check(false)
+ .with_global_shutdown_timeout(Duration::from_secs(5))
+ .with_shutdown_token(shutdown_token.clone())
+ .build();
+
+ let early = manager.register("early", ComponentOptions::new());
+ let late = manager.register("late", ComponentOptions::new().with_shutdown_phase(1));
+ let guard = manager.monitor_background();
+
+ tokio::spawn(async move {
+ let _guard = early.process_scope();
+ early.shutdown_recv().await;
+ // Hold phase 0 open long enough for the phase-1 completion to
+ // arrive mid-drain.
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ });
+
+ let root = shutdown_token.clone();
+ tokio::spawn(async move {
+ let _guard = late.process_scope();
+ root.cancelled().await;
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ late.work_completed();
+ // Idle forever: completion must come from the event above, not
+ // from this task exiting.
+ std::future::pending::<()>().await;
+ });
+
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ shutdown_token.cancel();
+
+ let start = std::time::Instant::now();
+ let result = tokio::time::timeout(Duration::from_secs(10), guard.wait())
+ .await
+ .expect("timed out");
+ assert!(result.is_ok());
+ assert!(
+ start.elapsed() < Duration::from_secs(3),
+ "shutdown waited on an already-completed phase-1 component"
+ );
+}
+
+/// A phase that times out its graceful window still advances the sequence:
+/// later phases must be signalled rather than wedging behind it.
+#[tokio::test]
+async fn phase_timeout_advances_to_next_phase() {
+ let shutdown_token = CancellationToken::new();
+ let mut manager = Manager::builder("test")
+ .with_trap_signals(false)
+ .with_prestop_check(false)
+ .with_global_shutdown_timeout(Duration::from_secs(5))
+ .with_shutdown_token(shutdown_token.clone())
+ .build();
+
+ let stuck = manager.register(
+ "stuck",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_millis(100)),
+ );
+ let late = manager.register("late", ComponentOptions::new().with_shutdown_phase(1));
+ let guard = manager.monitor_background();
+
+ let late_signalled = Arc::new(AtomicBool::new(false));
+ let late_signalled_writer = late_signalled.clone();
+
+ tokio::spawn(async move {
+ let _guard = stuck.process_scope();
+ std::future::pending::<()>().await;
+ });
+
+ tokio::spawn(async move {
+ let _guard = late.process_scope();
+ late.shutdown_recv().await;
+ late_signalled_writer.store(true, Ordering::SeqCst);
+ });
+
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ shutdown_token.cancel();
+
+ let result = tokio::time::timeout(Duration::from_secs(10), guard.wait())
+ .await
+ .expect("timed out");
+ // A graceful-window timeout is not a failure, matching single-phase
+ // semantics; the sequence must have reached and drained phase 1.
+ assert!(result.is_ok());
+ assert!(
+ late_signalled.load(Ordering::SeqCst),
+ "phase 1 was never signalled after phase 0 timed out"
+ );
+}
+
+/// A later-phase component's graceful window is measured from when its
+/// phase begins, not from the start of shutdown — so windows do not need
+/// to be successively reduced to survive being enqueued behind earlier
+/// phases. If the deadline were computed from the shutdown clock, phase
+/// 0's 300ms drain would exhaust the phase-1 component's 200ms window
+/// before it was ever signalled, and shutdown would finish without it.
+#[tokio::test]
+async fn later_phase_graceful_window_starts_at_its_phase() {
+ let shutdown_token = CancellationToken::new();
+ let mut manager = Manager::builder("test")
+ .with_trap_signals(false)
+ .with_prestop_check(false)
+ .with_global_shutdown_timeout(Duration::from_secs(5))
+ .with_shutdown_token(shutdown_token.clone())
+ .build();
+
+ let early = manager.register("early", ComponentOptions::new());
+ let late = manager.register(
+ "late",
+ ComponentOptions::new()
+ .with_shutdown_phase(1)
+ .with_graceful_shutdown(Duration::from_millis(200)),
+ );
+ let guard = manager.monitor_background();
+
+ tokio::spawn(async move {
+ let _guard = early.process_scope();
+ early.shutdown_recv().await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ });
+
+ let late_finished = Arc::new(AtomicBool::new(false));
+ let late_finished_writer = late_finished.clone();
+ tokio::spawn(async move {
+ let _guard = late.process_scope();
+ late.shutdown_recv().await;
+ // Well inside the 200ms window relative to the phase-1 signal,
+ // far outside it relative to shutdown start.
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ late_finished_writer.store(true, Ordering::SeqCst);
+ });
+
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ shutdown_token.cancel();
+
+ let result = tokio::time::timeout(Duration::from_secs(10), guard.wait())
+ .await
+ .expect("timed out");
+ assert!(result.is_ok());
+ assert!(
+ late_finished.load(Ordering::SeqCst),
+ "phase-1 component was timed out against a window measured from shutdown start"
+ );
+}
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index cc4c94f7b350..eeda26012364 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -59,13 +59,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!("Pod name: {}", config.pod_name);
tracing::info!("Kafka changelog topic: {}", config.kafka_person_state_topic);
+ // Shutdown order matters: the coordination drain (phase 0) hands this
+ // pod's partitions off, which requires the gRPC server to keep serving
+ // reads and completing in-flight writes and the producer to keep
+ // delivering their changelog records. Server and producer therefore
+ // stop in phase 1, only after the drain finishes — signalling them
+ // together with coordination black-holed every partition for the whole
+ // drain (dead server, still the registered owner). The coordination
+ // graceful window must exceed the pod's drain timeout (30s), and the
+ // global timeout must fit both phases.
let mut manager = Manager::builder("personhog-leader")
- .with_global_shutdown_timeout(Duration::from_secs(30))
+ .with_global_shutdown_timeout(Duration::from_secs(60))
.build();
let grpc_handle = manager.register(
"grpc-server",
- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(15))
+ .with_shutdown_phase(1),
);
let metrics_handle = manager.register(
"metrics-server",
@@ -73,9 +84,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
let coordination_handle = manager.register(
"coordination",
- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(35)),
+ );
+ let kafka_handle = manager.register(
+ "kafka-producer",
+ ComponentOptions::new().with_shutdown_phase(1),
);
- let kafka_handle = manager.register("kafka-producer", ComponentOptions::new());
let readiness = manager.readiness_handler();
let liveness = manager.liveness_handler();
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
index 7c869a15fdef..e394ce61260e 100644
--- a/rust/personhog-test-harness/README.md
+++ b/rust/personhog-test-harness/README.md
@@ -103,40 +103,33 @@ target/debug/personhog-test-harness gate --persons 50 --cache-capacity 10 --dura
Fix direction: pin dirty entries until the writer's committed offset passes their produce offset (see the TODO in `personhog-leader/src/cache/persons.rs`).
-**Graceful shutdown black-holes the leader's partitions — elevated Failed count, gate stays green.**
-The leader's lifecycle manager signals every component at SIGTERM simultaneously, so the gRPC server and Kafka producer finish shutting down (~160ms) long before the coordination drain hands partitions off (~2s: Draining status → 1s coordinator rebalance debounce → freeze → stash → fence → release).
-For most of that window the pod is still the registered owner with a dead server: writes get UNAVAILABLE, the router retries against the same owner (the stash only engages once it observes Freezing), and callers fail.
+**Graceful shutdown black-holes the leader's partitions — FIXED via lifecycle shutdown phases.**
+The leader's lifecycle manager used to signal every component at SIGTERM simultaneously, so the gRPC server and Kafka producer finished shutting down (~160ms) long before the coordination drain handed partitions off, leaving the pod a registered owner with a dead server for the whole drain (~1% failed writes per drain).
+The lifecycle crate now supports ordered shutdown phases (`ComponentOptions::with_shutdown_phase`): coordination drains in phase 0 while the server keeps serving and the producer keeps delivering, and both stop in phase 1 once the partitions are handed off.
```bash
-# Expect ~1% failed writes. All are unacked, so the invariant holds and the
-# gate passes — the signature is the Failed column, not violations.
+# Expect zero failed writes through the drain.
target/debug/personhog-test-harness gate --leaders 3 --duration 15s --shutdown-after 5s
```
-Fix direction: ordered shutdown — drain the coordination component before stopping the gRPC server and producer (the lifecycle crate currently has no phase/ordering primitive).
-Once fixed, this run's Failed count should drop to ~0, matching the zombie scenario's.
-
**A crashed coordinator blocks all handoffs for 10–20s — currently masked in the gate.**
The coordinator election is a lease-backed CAS (15s TTL, 5s keepalives, 5s campaign retry); a crash of the router holding it leaves the key in place until the lease expires, and no handoff can start until a survivor wins.
Leader crashes are usually unaffected (their own 30s registration lease gates discovery anyway), but a leader *drain* during the window stalls — which today, combined with the unordered-shutdown defect above, black-holes the draining pod's partitions for the whole gap (observed: 731 failed writes in ~10s at harness scale; one served strong read also returned NotFound for a person with acked writes, unreproduced and unexplained).
The gate's coordinator-kill scenario deliberately revokes the election lease to stay deterministic, so it does NOT exercise this window; the slow-failover variant is worth adding once the shutdown ordering is fixed and traffic survives the wait.
Fix direction: release the election on graceful exit reliably (the best-effort revoke can be dropped by the surrounding `select!` before it runs), and/or tune the election lease and retry intervals against the drain grace budget.
-**A drain overlapping a pod death wedges convergence for the drained pod's full lifecycle timeout — the gate waits it out.**
-The rebalance a drain triggers can race a concurrent pod death and create handoffs targeting the dead pod (self-healing: stale-handoff cleanup deletes them within a tick), but the re-drive rebalance still counts the *draining* pod as an assignment target — nothing marks it as leaving — and hands partitions back to it.
-Its gRPC server is already dead (the unordered-shutdown defect above) and its coordination component gets only a 5s grace, so those handoffs stall in Draining with no DrainedAck; rebalancing is globally deferred while any handoff is in flight, so nothing can converge until the pod's 30s lifecycle timeout force-exits it, deregistration fires, and cleanup plus a fresh rebalance finally move everything to survivors (observed: ~36s end to end, with the affected partitions black-holed throughout).
+**A drain overlapping a pod death wedged convergence for the drained pod's full lifecycle timeout — MOSTLY FIXED by the shutdown phases above.**
+The rebalance a drain triggers can race a concurrent pod death and create handoffs targeting the dead pod (self-healing: stale-handoff cleanup deletes them within a tick), and the re-drive rebalance still counts the *draining* pod as an assignment target — nothing marks it as leaving — handing partitions back to it.
+Before ordered shutdown, that wedged everything: the draining pod's coordination component was cancelled after a 5s grace, so those handoffs stalled with no DrainedAck until the pod's lifecycle timeout force-exited it (observed: ~36s end to end, partitions black-holed throughout).
+With phased shutdown, coordination survives the whole drain and acks promptly — the composite below now settles in ~0s with only the killed pod's own crash window as failures.
```bash
-# Nondeterministic: wedges only when the mid-drain rebalance picks the
-# draining pod as a target. The signature is a large "settled in Ns" line
-# and an elevated Failed count.
target/debug/personhog-test-harness gate --routers 2 --leaders 3 --duration 18s \
--router-kill-after 4s --shutdown-after 8s --kill-handoff-target
```
-Verification waits for convergence (bounded at 90s) before asserting strong reads, so the gate stays green through the wedge; red here means convergence itself failed.
-Fix direction: the ordered-shutdown fix removes both halves (the server survives the drain, and coordination lives to write DrainedAck, collapsing "settled in" to near-zero — at which point the convergence deadline can tighten to re-gate on recovery time).
-Independently worth fixing: draining pods should be excluded as rebalance targets, and one stuck handoff should not defer all rebalancing.
+Verification still waits for convergence (bounded at 90s) before asserting strong reads; red here means convergence itself failed.
+Remaining scope: draining pods should be excluded as rebalance targets (now mere churn rather than a black hole — a mid-drain rebalance can hand partitions to a pod that immediately re-drains them), and one stuck handoff should not defer all rebalancing.
## `seed` / `cleanup` — manage traffic targets