Skip to main content

agentmux_srv_core/backend/
record_carry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What older builds kept of the record, brought into the folder it lives in now
5//! (docs/specs/SPEC_LONG_RUNNING_ZERO_DEGRADATION_2026_11_16.md ยง6, task #47820).
6//!
7//! The record first lived in the data folder. An installed AgentMux has a data folder per version, so every
8//! upgrade began a new, empty record, and the old one went with the old version's folder: a record that must
9//! outlast weeks never held more than the days between two upgrades. It lives in the channel's folder now
10//! ([`agentmux_common::record_events::record_dir`]), which an upgrade keeps.
11//!
12//! [`bring_over`] moves what the data folders still hold into it, once: a file the record does not have is
13//! moved, and where both have a file of the same name (the day of an upgrade, the month's rollups and events)
14//! their lines are put together in time order. A file is taken from the old folder only after its lines are in
15//! the new one, so a failure part of the way leaves the rest to the next start.
16
17use std::path::{Path, PathBuf};
18
19const EXT: &str = "jsonl";
20const ROLLUP_PREFIX: &str = "rollup-";
21/// How often a merge is read again because a line was appended to the record's file meanwhile (the window host
22/// and srv's stall watch write events whenever they see one).
23const TRIES: usize = 3;
24
25/// What [`bring_over`] did.
26#[derive(Debug, Default, PartialEq, Eq)]
27pub struct Brought {
28    /// Files moved whole.
29    pub moved: usize,
30    /// Files whose lines were merged into one the record already had.
31    pub merged: usize,
32    /// Files that could not be brought; they stay where they were.
33    pub failed: usize,
34}
35
36/// The folders an older build kept its record in, under `instance_dir` (the channel's folder, or a dev build's
37/// own): `data/record`, and `versions/<version>/data/record` of every version, oldest name first.
38pub fn old_dirs(instance_dir: &Path) -> Vec<PathBuf> {
39    let mut dirs = vec![instance_dir.join("data").join("record")];
40    if let Ok(entries) = std::fs::read_dir(instance_dir.join("versions")) {
41        let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("data").join("record")).collect();
42        versions.sort();
43        dirs.extend(versions);
44    }
45    dirs.retain(|d| d.is_dir());
46    dirs
47}
48
49/// The time a line is ordered by: the hour of a rollup, the time of a sample or an event.
50fn time_of(line: &str, field: &str) -> Option<u64> {
51    serde_json::from_str::<serde_json::Value>(line).ok()?.get(field)?.as_u64()
52}
53
54/// The lines of `ours` and `theirs` in time order, each ending in a newline. A line of `theirs` that `ours`
55/// already has is left out (a merge that was cut short before the old file was removed is run again). A line
56/// that cannot be read stays behind the line it followed.
57fn merged(ours: &str, theirs: &str, field: &str) -> String {
58    let have: std::collections::HashSet<&str> = ours.lines().collect();
59    let mut lines: Vec<(u64, &str)> = Vec::new();
60    for (text, is_theirs) in [(ours, false), (theirs, true)] {
61        let mut last = 0;
62        for line in text.lines().filter(|l| !l.trim().is_empty()) {
63            if is_theirs && have.contains(line) {
64                continue;
65            }
66            if let Some(t) = time_of(line, field) {
67                last = t;
68            }
69            lines.push((last, line));
70        }
71    }
72    // Stable: lines of the same time keep the order they were written in.
73    lines.sort_by_key(|(t, _)| *t);
74    let mut out = String::with_capacity(ours.len() + theirs.len());
75    for (_, line) in lines {
76        out.push_str(line);
77        out.push('\n');
78    }
79    out
80}
81
82fn len_of(path: &Path) -> Option<u64> {
83    std::fs::metadata(path).ok().map(|m| m.len())
84}
85
86/// Bring the file `from` into the record as `to`. `Ok(true)` when it was moved whole, `Ok(false)` when its lines
87/// were merged into the file already there.
88fn bring_file(from: &Path, to: &Path, name: &str) -> std::io::Result<bool> {
89    if !to.exists() && std::fs::rename(from, to).is_ok() {
90        return Ok(true);
91    }
92    let field = if name.starts_with(ROLLUP_PREFIX) { "h" } else { "t" };
93    let theirs = std::fs::read_to_string(from)?;
94    let tmp = to.with_file_name(format!("{name}.tmp"));
95    for _ in 0..TRIES {
96        let before = len_of(to);
97        let ours = match std::fs::read_to_string(to) {
98            Ok(text) => text,
99            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
100            Err(e) => return Err(e),
101        };
102        std::fs::write(&tmp, merged(&ours, &theirs, field))?;
103        if len_of(to) != before {
104            // A line was appended while the two were put together: read it again.
105            continue;
106        }
107        std::fs::rename(&tmp, to)?;
108        std::fs::remove_file(from)?;
109        return Ok(false);
110    }
111    let _ = std::fs::remove_file(&tmp);
112    Err(std::io::Error::other("the record's file kept changing"))
113}
114
115/// Move what the folders of [`old_dirs`] hold into `dest`, the record's folder. BLOCKING (file reads and
116/// writes); call it once at start, before the first line is written. A file that cannot be brought is logged
117/// and left where it is: the record is never a reason for anything else to fail.
118pub fn bring_over(instance_dir: &Path, dest: &Path) -> Brought {
119    let mut brought = Brought::default();
120    for dir in old_dirs(instance_dir) {
121        if dir == dest {
122            continue;
123        }
124        let Ok(entries) = std::fs::read_dir(&dir) else { continue };
125        let mut names: Vec<String> = entries
126            .flatten()
127            .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
128            .filter_map(|e| e.file_name().to_str().map(str::to_string))
129            .filter(|n| n.ends_with(&format!(".{EXT}")))
130            .collect();
131        names.sort();
132        if names.is_empty() {
133            continue;
134        }
135        if let Err(e) = std::fs::create_dir_all(dest) {
136            tracing::warn!(error = %e, "[record] the record's folder could not be made");
137            brought.failed += names.len();
138            continue;
139        }
140        for name in names {
141            match bring_file(&dir.join(&name), &dest.join(&name), &name) {
142                Ok(true) => brought.moved += 1,
143                Ok(false) => brought.merged += 1,
144                Err(e) => {
145                    brought.failed += 1;
146                    tracing::warn!(error = %e, file = %name, "[record] an older build's file could not be brought into the record");
147                }
148            }
149        }
150        // Gone only when nothing is left in it.
151        let _ = std::fs::remove_dir(&dir);
152    }
153    if brought != Brought::default() {
154        tracing::info!(moved = brought.moved, merged = brought.merged, failed = brought.failed, "[record] brought over what older builds kept");
155    }
156    brought
157}
158
159/// [`bring_over`] for this process: from the folders under its channel into its record. Nothing when the
160/// launcher gave it no folders.
161pub fn bring_over_here() -> Brought {
162    let Some(paths) = agentmux_common::data_paths::DataPaths::from_env() else { return Brought::default() };
163    let Some(dest) = agentmux_common::record_events::record_dir() else { return Brought::default() };
164    bring_over(&paths.instance_dir, &dest)
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use crate::backend::record;
171    use serde_json::json;
172
173    /// 2026-11-16 12:00 UTC.
174    const NOON: u64 = 1_794_830_400_000;
175    const HOUR: u64 = 3_600_000;
176
177    fn write(path: &Path, lines: &[serde_json::Value]) {
178        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
179        let text: String = lines.iter().map(|l| format!("{l}\n")).collect();
180        std::fs::write(path, text).unwrap();
181    }
182
183    fn times(path: &Path, field: &str) -> Vec<u64> {
184        std::fs::read_to_string(path).unwrap().lines().map(|l| time_of(l, field).unwrap()).collect()
185    }
186
187    fn old(home: &Path, version: &str) -> PathBuf {
188        home.join("versions").join(version).join("data").join("record")
189    }
190
191    #[test]
192    fn the_old_folders_are_each_versions_and_a_dev_builds_own() {
193        let tmp = tempfile::tempdir().unwrap();
194        let home = tmp.path();
195        assert!(old_dirs(home).is_empty());
196        std::fs::create_dir_all(old(home, "0.60.34")).unwrap();
197        std::fs::create_dir_all(old(home, "0.60.35")).unwrap();
198        // A version that never kept a record, and a file where a folder is expected.
199        std::fs::create_dir_all(home.join("versions").join("0.60.30").join("data")).unwrap();
200        std::fs::write(home.join("versions").join("notes.txt"), "x").unwrap();
201        std::fs::create_dir_all(home.join("data").join("record")).unwrap();
202        assert_eq!(old_dirs(home), vec![home.join("data").join("record"), old(home, "0.60.34"), old(home, "0.60.35")]);
203    }
204
205    #[test]
206    fn lines_are_put_in_time_order_and_one_already_there_is_not_added_twice() {
207        let a = format!("{}\n{}\n", json!({ "t": 10, "kind": "x" }), json!({ "t": 30, "kind": "x" }));
208        let b = format!("{}\n{}\n\n{}\n", json!({ "t": 20, "kind": "y" }), json!({ "t": 30, "kind": "x" }), json!({ "t": 5, "kind": "y" }));
209        let out = merged(&a, &b, "t");
210        let got: Vec<(u64, String)> =
211            out.lines().map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap()).map(|v| (v["t"].as_u64().unwrap(), v["kind"].as_str().unwrap().to_string())).collect();
212        assert_eq!(got, [(5, "y".into()), (10, "x".into()), (20, "y".into()), (30, "x".into())]);
213        assert!(out.ends_with('\n'));
214        // A line cut short by a crash stays behind the line it followed.
215        let torn = format!("{}\n{{\"t\": 4\n{}\n", json!({ "t": 40 }), json!({ "t": 50 }));
216        let out = merged(&a, &torn, "t");
217        let lines: Vec<&str> = out.lines().collect();
218        assert_eq!(lines.len(), 5);
219        assert_eq!(lines[3], "{\"t\": 4");
220        // Rollups are ordered by their hour.
221        let out = merged(&format!("{}\n", json!({ "h": 7, "last_t": 1 })), &format!("{}\n", json!({ "h": 3, "last_t": 9 })), "h");
222        assert!(out.starts_with("{\"h\":3"));
223    }
224
225    #[test]
226    fn each_versions_record_becomes_one_record_in_time_order() {
227        let tmp = tempfile::tempdir().unwrap();
228        let home = tmp.path();
229        let dest = home.join("record");
230        // The older version: a day of its own, the morning of the day of the upgrade, and the month's files.
231        let v34 = old(home, "0.60.34");
232        write(&v34.join("2026-11-15.jsonl"), &[json!({ "t": NOON - 24 * HOUR })]);
233        write(&v34.join("2026-11-16.jsonl"), &[json!({ "t": NOON - 3 * HOUR }), json!({ "t": NOON - 2 * HOUR })]);
234        write(&v34.join("rollup-2026-11.jsonl"), &[json!({ "h": NOON - 24 * HOUR }), json!({ "h": NOON - 3 * HOUR })]);
235        write(&v34.join("events-2026-11.jsonl"), &[json!({ "t": NOON - 2 * HOUR, "kind": "ui_stall", "ms": 6_000 })]);
236        // The newer one: the afternoon of the same day.
237        let v35 = old(home, "0.60.35");
238        write(&v35.join("2026-11-16.jsonl"), &[json!({ "t": NOON + HOUR })]);
239        write(&v35.join("rollup-2026-11.jsonl"), &[json!({ "h": NOON })]);
240        // What is not the record's stays.
241        std::fs::write(v35.join("notes.txt"), "x").unwrap();
242        // The record already holds a line written since this start.
243        write(&dest.join("events-2026-11.jsonl"), &[json!({ "t": NOON + 2 * HOUR, "kind": "srv_stall", "ms": 5_500 })]);
244
245        assert_eq!(bring_over(home, &dest), Brought { moved: 3, merged: 3, failed: 0 });
246
247        assert_eq!(times(&dest.join("2026-11-15.jsonl"), "t"), [NOON - 24 * HOUR]);
248        assert_eq!(times(&dest.join("2026-11-16.jsonl"), "t"), [NOON - 3 * HOUR, NOON - 2 * HOUR, NOON + HOUR]);
249        assert_eq!(times(&dest.join("rollup-2026-11.jsonl"), "h"), [NOON - 24 * HOUR, NOON - 3 * HOUR, NOON]);
250        assert_eq!(times(&dest.join("events-2026-11.jsonl"), "t"), [NOON - 2 * HOUR, NOON + 2 * HOUR]);
251        // Nothing is left behind but what was never the record's, and no half-written file.
252        assert!(!v34.exists());
253        assert_eq!(std::fs::read_dir(&v35).unwrap().count(), 1);
254        assert!(std::fs::read_dir(&dest).unwrap().flatten().all(|e| e.file_name().to_str().unwrap().ends_with(".jsonl")));
255        // The record reads it back as one: both stalls, oldest first.
256        let (total, events) = record::read_events(&dest, 0, u64::MAX, 10);
257        assert_eq!(total, 2);
258        assert_eq!(events[0]["kind"], "ui_stall");
259        // A second start finds nothing to bring.
260        assert_eq!(bring_over(home, &dest), Brought::default());
261    }
262
263    #[test]
264    fn a_dev_builds_record_moves_out_of_its_data_folder_and_no_old_record_is_nothing() {
265        let tmp = tempfile::tempdir().unwrap();
266        let home = tmp.path();
267        let dest = home.join("record");
268        assert_eq!(bring_over(home, &dest), Brought::default());
269        assert!(!dest.exists());
270        write(&home.join("data").join("record").join("2026-11-16.jsonl"), &[json!({ "t": NOON })]);
271        assert_eq!(bring_over(home, &dest), Brought { moved: 1, merged: 0, failed: 0 });
272        assert_eq!(times(&dest.join("2026-11-16.jsonl"), "t"), [NOON]);
273        assert!(!home.join("data").join("record").exists());
274    }
275
276    #[test]
277    fn a_merge_run_again_after_being_cut_short_adds_nothing_twice() {
278        let tmp = tempfile::tempdir().unwrap();
279        let home = tmp.path();
280        let dest = home.join("record");
281        let lines = [json!({ "t": NOON }), json!({ "t": NOON + HOUR })];
282        // The lines are in the record already, and the old file was not removed.
283        write(&dest.join("2026-11-16.jsonl"), &lines);
284        write(&old(home, "0.60.34").join("2026-11-16.jsonl"), &lines);
285        assert_eq!(bring_over(home, &dest), Brought { moved: 0, merged: 1, failed: 0 });
286        assert_eq!(times(&dest.join("2026-11-16.jsonl"), "t"), [NOON, NOON + HOUR]);
287    }
288}