Skip to main content

agentmux_common/
srv_estart_wait.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Waiting for srv's readiness line (`AGENTMUXSRV-ESTART`), shared by the launcher and the CEF host.
5//!
6//! The caller reads srv's stderr, parses each line with [`crate::srv_stderr`], and feeds four channels; this waits
7//! on them. A `MIGRATING` line extends the deadline from 30 seconds to 30 minutes: a shorter cap risks killing srv
8//! mid-migration, and 0011_shared_store_backfill's skip-guards check for non-empty shared tables, so a partial copy
9//! followed by a kill would strand rows on the next retry.
10
11use std::time::Duration;
12
13use tokio::sync::mpsc;
14use tokio::time::{sleep_until, Instant};
15
16/// How long srv has to say it is ready.
17pub const NORMAL_TIMEOUT: Duration = Duration::from_secs(30);
18/// The deadline once srv says it is migrating.
19pub const MIGRATION_TIMEOUT: Duration = Duration::from_secs(1800);
20
21/// How the wait ended.
22pub enum EstartWait<T> {
23    /// srv is ready (`Some`), or the ready channel closed without it (`None`): srv died before ESTART.
24    Ready(Option<T>),
25    Timeout,
26    /// srv reported a fatal migration failure and exits 1 without ESTART.
27    MigrationFailed(String),
28    /// srv's data needs `migrate --prepare`; srv exits right after the line.
29    NeedsPrepare(String),
30}
31
32/// What the stderr reader sends. `needs_prepare` is `None` for a caller that does not run the prepare step.
33pub struct EstartChannels<T> {
34    pub ready: mpsc::Receiver<T>,
35    pub migrating: mpsc::Receiver<()>,
36    pub failed: mpsc::Receiver<String>,
37    pub needs_prepare: Option<mpsc::Receiver<String>>,
38}
39
40async fn recv_prepare(rx: &mut Option<mpsc::Receiver<String>>) -> Option<String> {
41    match rx {
42        Some(rx) => rx.recv().await,
43        None => std::future::pending().await,
44    }
45}
46
47/// Second guard for the ESTART-vs-failure race (#3043). The stderr reader sends the
48/// migration-failure reason and then drops every sender as srv exits, so by the time the waiter's `select!` runs,
49/// BOTH "failure buffered" and "ready channel closed" are ready. `biased;` makes the failure arm win when both are
50/// seen in one poll; this covers the remaining shape, where the closed channel was observed first and the reason is
51/// sitting in `failed` unread. Every other outcome passes through unchanged.
52fn prefer_buffered_failure<T>(outcome: EstartWait<T>, failed: &mut mpsc::Receiver<String>) -> EstartWait<T> {
53    match outcome {
54        EstartWait::Ready(None) => match failed.try_recv() {
55            Ok(reason) => EstartWait::MigrationFailed(reason),
56            Err(_) => EstartWait::Ready(None),
57        },
58        other => other,
59    }
60}
61
62/// Wait for srv to be ready, fail, or run out of time. `on_extend` runs when a `MIGRATING` line pushes the
63/// deadline out, for the caller's log line. The caller kills srv on every outcome but `Ready(Some(_))`.
64pub async fn wait_for_estart<T>(ch: &mut EstartChannels<T>, mut on_extend: impl FnMut()) -> EstartWait<T> {
65    let mut deadline = Instant::now() + NORMAL_TIMEOUT;
66    let sleep = sleep_until(deadline);
67    tokio::pin!(sleep);
68    let outcome = loop {
69        tokio::select! {
70            // `biased;` polls the arms in order, failure first: the reader sends the reason and then hits EOF
71            // (srv exits 1 right after the line), dropping every sender before this is next polled. Unbiased,
72            // `ready` resolving to None could win over the buffered reason and degrade to the generic
73            // "channel closed". `prefer_buffered_failure` is the second guard.
74            biased;
75            Some(reason) = ch.failed.recv() => break EstartWait::MigrationFailed(reason),
76            Some(reason) = recv_prepare(&mut ch.needs_prepare) => break EstartWait::NeedsPrepare(reason),
77            result = ch.ready.recv() => break EstartWait::Ready(result),
78            _ = &mut sleep => break EstartWait::Timeout,
79            Some(()) = ch.migrating.recv() => {
80                let new_deadline = Instant::now() + MIGRATION_TIMEOUT;
81                if new_deadline > deadline {
82                    deadline = new_deadline;
83                    sleep.as_mut().reset(deadline);
84                    on_extend();
85                }
86            }
87        }
88    };
89    prefer_buffered_failure(outcome, &mut ch.failed)
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    type Senders<T> = (mpsc::Sender<T>, mpsc::Sender<String>, mpsc::Sender<()>);
97
98    fn channels<T>() -> (EstartChannels<T>, Senders<T>) {
99        let (ready_tx, ready) = mpsc::channel(1);
100        let (migrating_tx, migrating) = mpsc::channel(4);
101        let (failed_tx, failed) = mpsc::channel(1);
102        (EstartChannels { ready, migrating, failed, needs_prepare: None }, (ready_tx, failed_tx, migrating_tx))
103    }
104
105    #[test]
106    fn closed_ready_channel_with_buffered_failure_becomes_migration_failed() {
107        let (tx, mut rx) = mpsc::channel::<String>(1);
108        // The reader's exact sequence: send the reason, then drop the sender.
109        tx.try_send("migration 0007 failed: disk I/O error".into()).unwrap();
110        drop(tx);
111        match prefer_buffered_failure(EstartWait::<u8>::Ready(None), &mut rx) {
112            EstartWait::MigrationFailed(r) => assert_eq!(r, "migration 0007 failed: disk I/O error"),
113            _ => panic!("buffered failure reason must win over a closed ready channel"),
114        }
115    }
116
117    #[test]
118    fn closed_ready_channel_without_failure_stays_channel_closed() {
119        let (tx, mut rx) = mpsc::channel::<String>(1);
120        drop(tx); // srv died before ESTART for some other reason: no failure line
121        assert!(matches!(prefer_buffered_failure(EstartWait::<u8>::Ready(None), &mut rx), EstartWait::Ready(None)));
122    }
123
124    #[test]
125    fn other_outcomes_pass_through_untouched() {
126        let (tx, mut rx) = mpsc::channel::<String>(1);
127        tx.try_send("should not be consumed".into()).unwrap();
128        assert!(matches!(prefer_buffered_failure(EstartWait::<u8>::Timeout, &mut rx), EstartWait::Timeout));
129        assert!(matches!(
130            prefer_buffered_failure(EstartWait::<u8>::MigrationFailed("x".into()), &mut rx),
131            EstartWait::MigrationFailed(_)
132        ));
133    }
134
135    #[tokio::test]
136    async fn a_ready_line_ends_the_wait() {
137        let (mut ch, (ready_tx, _failed_tx, _migrating_tx)) = channels::<u8>();
138        ready_tx.send(7).await.unwrap();
139        assert!(matches!(wait_for_estart(&mut ch, || {}).await, EstartWait::Ready(Some(7))));
140    }
141
142    #[tokio::test]
143    async fn a_failure_then_a_closed_reader_is_the_failure() {
144        let (mut ch, (ready_tx, failed_tx, migrating_tx)) = channels::<u8>();
145        failed_tx.send("disk full".into()).await.unwrap();
146        drop((ready_tx, failed_tx, migrating_tx));
147        match wait_for_estart(&mut ch, || {}).await {
148            EstartWait::MigrationFailed(r) => assert_eq!(r, "disk full"),
149            _ => panic!("the reason must win over the closed channels"),
150        }
151    }
152
153    #[tokio::test]
154    async fn a_closed_reader_with_nothing_buffered_is_a_closed_channel() {
155        let (mut ch, senders) = channels::<u8>();
156        drop(senders);
157        assert!(matches!(wait_for_estart(&mut ch, || {}).await, EstartWait::Ready(None)));
158    }
159
160    #[tokio::test]
161    async fn a_prepare_line_ends_the_wait_when_the_caller_listens_for_it() {
162        let (mut ch, _senders) = channels::<u8>();
163        let (prepare_tx, prepare_rx) = mpsc::channel(1);
164        ch.needs_prepare = Some(prepare_rx);
165        prepare_tx.send("old schema".into()).await.unwrap();
166        match wait_for_estart(&mut ch, || {}).await {
167            EstartWait::NeedsPrepare(r) => assert_eq!(r, "old schema"),
168            _ => panic!("expected NeedsPrepare"),
169        }
170    }
171
172    #[tokio::test]
173    async fn a_migrating_line_extends_the_deadline_only_once_per_push() {
174        let (mut ch, (ready_tx, _failed_tx, migrating_tx)) = channels::<u8>();
175        migrating_tx.send(()).await.unwrap();
176        ready_tx.send(1).await.unwrap();
177        let mut extended = 0;
178        // The ready value is already buffered, so the wait ends at once; it extends at most once for the one ping.
179        let outcome = wait_for_estart(&mut ch, || extended += 1).await;
180        assert!(matches!(outcome, EstartWait::Ready(Some(1))));
181        assert!(extended <= 1);
182    }
183}