Skip to main content

agentmux_srv/bootstrap/
shutdown.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Split out of the single-file bootstrap module unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.3).
5
6use super::*;
7
8/// Step 6: Emit AGENTMUXSRV-ESTART on stderr (exact format from cmd/server/main-server.go:617)
9/// pending_migrations reflects any migrations that failed during the in-process
10/// run above. Non-zero causes the status-bar to show a "Migration failed —
11/// restart to retry" message. Zero is the expected steady-state.
12pub fn emit_estart(ws_port: u16, web_port: u16, version: &str, build_time: &str, instance_id: &str) {
13    // Under the launcher srv got here only because the boot gate found
14    // nothing pending (it exits for `migrate --prepare` otherwise), so don't
15    // reopen every store read-write just to count to zero.
16    let supervised =
17        std::env::var(agentmux_common::srv_stderr::SUPERVISOR_PREPARES_ENV).as_deref() == Ok("1");
18    let pending_migrations = if supervised {
19        0
20    } else {
21        crate::boot_timing::time("estart_pending_count", || migrations::count_pending_migrations(&base::get_mux_data_dir()))
22    };
23    eprintln!(
24        "{}",
25        agentmux_common::srv_stderr::estart_line(&agentmux_common::srv_stderr::Estart {
26            ws_endpoint: format!("127.0.0.1:{ws_port}"),
27            web_endpoint: format!("127.0.0.1:{web_port}"),
28            version: version.to_string(),
29            build_time: build_time.to_string(),
30            instance_id: instance_id.to_string(),
31            pending_migrations,
32        })
33    );
34}
35
36/// Steps 8 & 9: spawn the stdin-watch thread (exit on EOF — matching Go's
37/// stdinReadWatch) and the SIGINT/SIGTERM handler. Both cancel the returned
38/// token, which the WAL checkpoint loop and the final server select! also
39/// watch for graceful shutdown.
40pub fn install_shutdown_handlers(watch_stdin: bool) -> tokio_util::sync::CancellationToken {
41    // 8. Spawn stdin watch thread (exit on EOF — matching Go's stdinReadWatch).
42    //    Not in headless mode: nothing owns srv's stdin there (a container's
43    //    is /dev/null), so EOF would mean "shut down now".
44    let stdin_token = tokio_util::sync::CancellationToken::new();
45    let stdin_shutdown = stdin_token.clone();
46    if watch_stdin {
47        std::thread::spawn(move || {
48            use std::io::Read;
49            let mut stdin = std::io::stdin().lock();
50            let mut buf = [0u8; 1024];
51            loop {
52                match stdin.read(&mut buf) {
53                    Ok(0) => {
54                        eprintln_lossy!("stdin closed, shutting down");
55                        stdin_shutdown.cancel();
56                        break;
57                    }
58                    Ok(_) => {}
59                    Err(e) => {
60                        eprintln_lossy!("stdin read error: {}, shutting down", e);
61                        stdin_shutdown.cancel();
62                        break;
63                    }
64                }
65            }
66        });
67    }
68
69    // 9. Spawn signal handler (SIGINT/SIGTERM → graceful shutdown)
70    let signal_token = stdin_token.clone();
71    tokio::spawn(async move {
72        let ctrl_c = tokio::signal::ctrl_c();
73        #[cfg(unix)]
74        {
75            let mut sigterm =
76                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).unwrap();
77            tokio::select! {
78                _ = ctrl_c => {
79                    tracing::info!("received SIGINT, shutting down");
80                }
81                _ = sigterm.recv() => {
82                    tracing::info!("received SIGTERM, shutting down");
83                }
84            }
85        }
86        #[cfg(not(unix))]
87        {
88            ctrl_c.await.ok();
89            tracing::info!("received Ctrl+C, shutting down");
90        }
91        signal_token.cancel();
92    });
93
94    stdin_token
95}
96
97/// Periodic WAL checkpoint — prevents unbounded WAL file growth during
98/// long-running sessions. Runs every 30 minutes while the srv is up.
99/// busy_timeout=5000 (set at DB open) handles transient reader contention;
100/// partial truncate on contention is safe — the remainder is picked up on
101/// the next pass. (SPEC_WINDOWS_LIFECYCLE_ROBUSTNESS_2026_06_26 §4.E)
102pub fn spawn_wal_checkpoint_loop(
103    token: tokio_util::sync::CancellationToken,
104    wal_mstore: Arc<Store>,
105    wal_filestore: Arc<FileStore>,
106) {
107    tokio::spawn(async move {
108        const INTERVAL: std::time::Duration = std::time::Duration::from_secs(30 * 60);
109        loop {
110            tokio::select! {
111                _ = tokio::time::sleep(INTERVAL) => {}
112                _ = token.cancelled() => break,
113            }
114            if let Err(e) = wal_mstore.checkpoint() {
115                tracing::warn!(error = %e, "wal_checkpoint(TRUNCATE) on objects.db failed");
116            } else {
117                tracing::debug!("wal_checkpoint(TRUNCATE): objects.db ok");
118            }
119            if let Err(e) = wal_filestore.checkpoint() {
120                tracing::warn!(error = %e, "wal_checkpoint(TRUNCATE) on filestore.db failed");
121            } else {
122                tracing::debug!("wal_checkpoint(TRUNCATE): filestore.db ok");
123            }
124        }
125    });
126}
127
128/// Looking after the shared transcript store.
129///
130/// - **Its WAL is cut back** by one srv on the machine, the owner of
131///   `filestore.db.owner` ([`TruncateOwner`]): a first look two minutes after
132///   start, then every half hour. The PASSIVE checkpoints
133///   (`filestore/checkpointer.rs`) keep the WAL's content copied back; this
134///   gives the disk back and starts the log afresh. The TRUNCATE runs on its
135///   own connection, so this srv's appends don't wait behind it.
136/// - **Its finished transcripts are compressed** (`transcript::framer`) by
137///   every srv whose own `agent:transcriptframes` is on, owner or not:
138///   settings are per channel, so the owner's alone can't speak for the
139///   machine. Each frame is written in one transaction that checks its parts
140///   first, so two srvs framing at once never conflict; the later one finds
141///   the parts framed. A pass of at most [`framer::PASS_FRAMES`] frames each
142///   minute, or every few seconds while there is work.
143pub fn spawn_global_transcripts_truncate_loop(token: tokio_util::sync::CancellationToken, store: Option<Arc<FileStore>>) {
144    use crate::backend::transcript::{framer, kinds};
145    let Some(store) = store else { return };
146    let Some(mut owner) = crate::backend::storage::filestore::TruncateOwner::for_store(&store) else { return };
147    let Some(dir) = store.path().and_then(|p| p.parent()).map(|p| p.to_path_buf()) else { return };
148    tokio::spawn(async move {
149        const TRUNCATE_EVERY: std::time::Duration = std::time::Duration::from_secs(30 * 60);
150        let mut wait = std::time::Duration::from_secs(2 * 60);
151        let mut last_truncate: Option<std::time::Instant> = None;
152        let skip = Arc::new(std::sync::Mutex::new(std::collections::HashSet::new()));
153        let mut last_waiting: Option<String> = None;
154        loop {
155            tokio::select! {
156                _ = tokio::time::sleep(wait) => {}
157                // An append put a group behind a live tail: frame it now, after a short wait so the appends that
158                // follow it share the pass.
159                _ = framer::woken() => {
160                    tokio::select! {
161                        _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {}
162                        _ = token.cancelled() => break,
163                    }
164                }
165                _ = token.cancelled() => break,
166            }
167            wait = std::time::Duration::from_secs(60);
168            if owner.is_owner() && last_truncate.is_none_or(|t| t.elapsed() >= TRUNCATE_EVERY) {
169                last_truncate = Some(std::time::Instant::now());
170                let store = Arc::clone(&store);
171                match tokio::task::spawn_blocking(move || store.checkpoint_truncate_apart()).await {
172                    Ok(Ok(true)) => tracing::debug!("wal_checkpoint(TRUNCATE): global transcripts ok"),
173                    Ok(Ok(false)) => tracing::debug!("wal_checkpoint(TRUNCATE): global transcripts busy; the next pass finishes"),
174                    Ok(Err(e)) => tracing::warn!(error = %e, "wal_checkpoint(TRUNCATE) on the global transcript store failed"),
175                    Err(e) => tracing::warn!(error = %e, "global transcript store truncate task failed"),
176                }
177            }
178            // Give freed pages back in short steps, once the store is
179            // `auto_vacuum=INCREMENTAL` (a reclaim made it so): the frames the
180            // last pass wrote freed their parts' pages. One srv does it, the
181            // owner; the file shrinks at its next TRUNCATE above.
182            if owner.is_owner() {
183                let store = Arc::clone(&store);
184                match tokio::task::spawn_blocking(move || store.reclaim_free_pages()).await {
185                    Ok(Ok(pages)) if pages > 0 => tracing::info!(pages, "history store: gave freed pages back"),
186                    Ok(Err(e)) => tracing::warn!(error = %e, "history store: giving freed pages back failed"),
187                    _ => {}
188                }
189            }
190            // What the history is made of (`transcript::kinds`): the owner counts a budget of bytes
191            // each pass, a file once and then only what is appended, and goes on every few seconds
192            // until every file is counted.
193            let mut kinds_left = false;
194            if owner.is_owner() {
195                let store = Arc::clone(&store);
196                match tokio::task::spawn_blocking(move || kinds::step(&store, kinds::STEP_BYTES)).await {
197                    Ok(report) => kinds_left = !report.done,
198                    Err(e) => tracing::warn!(error = %e, "history kinds: the counting task failed"),
199                }
200            }
201            if !framer::enabled() {
202                if kinds_left {
203                    wait = std::time::Duration::from_secs(5);
204                }
205                continue;
206            }
207            let (store, dir, skip) = (Arc::clone(&store), dir.clone(), Arc::clone(&skip));
208            let pass = tokio::task::spawn_blocking(move || {
209                let mut skip = skip.lock().unwrap_or_else(|e| e.into_inner());
210                framer::pass(&store, &dir, framer::PASS_FRAMES, &mut skip, agentmux_common::time::now_ms())
211            })
212            .await;
213            match pass {
214                Ok(Ok(report)) => {
215                    framer::note_pass(report.frames, report.done);
216                    if report.waiting != last_waiting {
217                        if let Some(who) = &report.waiting {
218                            tracing::info!(who = %who, "framer: waiting");
219                        }
220                        last_waiting = report.waiting.clone();
221                    }
222                    if report.frames > 0 {
223                        tracing::info!(
224                            frames = report.frames,
225                            codec2 = report.codec2,
226                            raw_bytes = report.raw_bytes,
227                            stored_bytes = report.stored_bytes,
228                            skipped = report.skipped,
229                            "framer: compressed"
230                        );
231                    }
232                    if (!report.done && report.waiting.is_none()) || kinds_left {
233                        wait = std::time::Duration::from_secs(5);
234                    }
235                }
236                Ok(Err(e)) => framer::note_pass_failed(&e),
237                Err(e) => tracing::warn!(error = %e, "framer: pass task failed"),
238            }
239        }
240    });
241}