Skip to main content

agentmux_srv_core/backend/transcript/
migrate.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The upgrade's reduce step: one zone's `output` is rewritten into the compact form
5//! (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 9, checks L1 to L4).
6//!
7//! The old file is never edited. The worker reads it through snapshots in windows that end at a turn
8//! boundary, runs [`compact::compact_lines`] on each, checks the result with [`compact::verify`],
9//! and appends it to `output.next` (with `output.next.tsidx`, the receive times of the lines that
10//! were kept, translated to the new offsets). When it has read to the old file's end, one
11//! transaction ([`FileStore::swap_in_next`]) checks the old file is still what was read, copies the
12//! few lines appended since, and renames the new rows over the old. A crash at any point leaves the
13//! old file; a leftover `output.next` is discarded and the zone starts again.
14//!
15//! What is written to `output.consol` is counts, hashes and the line map, never conversation text:
16//! the map is the dropped runs, so that a position in the old file translates exactly to the new one.
17//!
18//! This module does not decide when to run (the background pass does) and does not translate
19//! positions for readers (the readers' piece does). Nothing here is on by default.
20
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::Arc;
23use std::time::Duration;
24
25use serde_json::{json, Value};
26use sha2::{Digest, Sha256};
27
28use super::compact::{self, WindowEnd};
29pub use super::consol::{ByteRun, Map, Run, CONSOL};
30use crate::backend::storage::filestore::swap::{SwapBase, SwapOutcome, SwapPlan, SwapRename, SwapStamps};
31use crate::backend::storage::error::StoreError;
32use crate::backend::storage::filestore::{is_blank_line, FileMeta, FileOpts, FileStore};
33
34/// The pane's snapshot, in the zone of the transcript it counts lines of.
35const SNAPSHOT: &str = "output.state.json";
36/// The file the compact transcript is built in, beside `output`.
37pub const NEXT: &str = "output.next";
38/// Its receive-time sidecar.
39pub const NEXT_TSIDX: &str = "output.next.tsidx";
40
41/// What a pass does and how fast.
42#[derive(Debug, Clone)]
43pub struct Options {
44    /// The size of one window read from the old file; a window is cut to whole lines and extended to
45    /// the next turn boundary, up to `max_window_bytes`.
46    pub window_bytes: i64,
47    pub max_window_bytes: i64,
48    /// A window that has grown to this and holds no turn boundary is cut after the last line where no reply is in
49    /// flight (`compact::last_quiet_line`) instead of growing to `max_window_bytes`.
50    pub quiet_after_bytes: i64,
51    /// The most the swap copies across from the end of the old file, as it is.
52    pub max_tail: i64,
53    /// Read, plan and check everything; write nothing. The report has the counts.
54    pub dry_run: bool,
55    /// Between windows, so the pass is polite to what else uses the store.
56    pub pause: Duration,
57    /// How many times a swap that found the old file moved on is tried again before the pass gives up.
58    pub swap_attempts: u32,
59    /// A half-built file written to within this many ms belongs to a pass that is still running (in
60    /// another srv on the same store); an older one is a crash's leftover and is discarded.
61    pub busy_ms: i64,
62    /// An old file that has not been written to for this many ms and ends in an unterminated line ends in
63    /// a torn write nobody will finish (the process died mid-line): the swap leaves that fragment out
64    /// instead of waiting for it for ever. 0 or less: never.
65    pub settle_ms: i64,
66}
67
68impl Default for Options {
69    fn default() -> Self {
70        Self {
71            window_bytes: 16 << 20,
72            max_window_bytes: 256 << 20,
73            quiet_after_bytes: 64 << 20,
74            max_tail: 8 << 20,
75            dry_run: false,
76            pause: Duration::from_millis(50),
77            swap_attempts: 5,
78            busy_ms: 10 * 60 * 1000,
79            settle_ms: 60 * 60 * 1000,
80        }
81    }
82}
83
84/// How a zone's pass ended.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum Outcome {
87    /// No `output`, or an empty one.
88    Empty,
89    /// A pass already made this file compact and nothing has been appended with a fragment since.
90    AlreadyCompact,
91    /// Dry run: everything was read and checked, nothing written.
92    DryRun,
93    /// The compact file is `output` now.
94    Swapped { new_gen: String },
95    /// The file changed under the pass (rewritten, repaired, trimmed); the build was thrown away and
96    /// the zone is tried again at the next pass.
97    Stale,
98    /// A check failed or the file could not be read; nothing changed. Counts and positions only.
99    Failed(String),
100    /// Asked to stop; the half-built file was thrown away.
101    Stopped,
102    /// Another pass (another srv on the same store) is building this zone's file now.
103    Busy,
104}
105
106
107/// Counts for one zone. No content.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Report {
110    pub zone: String,
111    pub outcome: Outcome,
112    pub bytes_before: i64,
113    pub bytes_after: i64,
114    pub lines_before: u64,
115    pub lines_after: u64,
116    pub windows: u32,
117    pub stats: compact::Stats,
118    /// This pass made `output.next` (so it, and only it, deletes it if the pass does not finish).
119    pub created_next: bool,
120}
121
122impl Report {
123    fn new(zone: &str) -> Self {
124        Self {
125            zone: zone.to_string(),
126            outcome: Outcome::Empty,
127            bytes_before: 0,
128            bytes_after: 0,
129            lines_before: 0,
130            lines_after: 0,
131            windows: 0,
132            stats: compact::Stats::default(),
133            created_next: false,
134        }
135    }
136}
137
138
139/// Whether a stop was asked for.
140fn stopped(stop: &AtomicBool) -> bool {
141    stop.load(Ordering::Relaxed)
142}
143
144/// The old file's state in one snapshot: `(size, gen)`; `None` for no file. A legacy file that was never counted
145/// has an empty generation: a dry run plans it all the same, a real pass counts it first.
146fn old_state(fs: &FileStore, zone: &str) -> Result<Option<(i64, String)>, String> {
147    let file = fs.read_snapshot(|s| s.file(zone, "output")).map_err(|e| format!("read: {e}"))?;
148    Ok(file.map(|f| (f.size, f.gen.unwrap_or_default())))
149}
150
151/// The bytes `[pos, pos + len)` of `output`, only if it is still generation `gen`.
152fn read_old(fs: &FileStore, zone: &str, gen: &str, pos: i64, len: i64) -> Result<Option<Vec<u8>>, String> {
153    fs.read_snapshot(|s| {
154        let Some(file) = s.file(zone, "output")? else { return Ok(None) };
155        if file.gen.as_deref().unwrap_or("") != gen || file.size < pos + len {
156            return Ok(None);
157        }
158        s.bytes(zone, "output", pos, len)
159    })
160    .map_err(|e| format!("read: {e}"))
161}
162
163/// One receive-time record of the old sidecar: the line at byte `off` was seen at `ms`.
164/// Each is `(off, ms, at)`, where `at` is the byte of the sidecar the record starts at. `raw` is whole
165/// lines read from byte `from` of the sidecar.
166fn parse_stamps(raw: &[u8], from: i64) -> Vec<(i64, i64, i64)> {
167    let mut out: Vec<(i64, i64, i64)> = Vec::new();
168    let mut at = from;
169    for line in String::from_utf8_lossy(raw).split_inclusive('\n') {
170        if let Ok(v) = serde_json::from_str::<Value>(line.trim_end()) {
171            if let (Some(off), Some(ms)) = (v.get("off").and_then(Value::as_i64), v.get("ms").and_then(Value::as_i64)) {
172                out.push((off, ms, at));
173            }
174        }
175        at += line.len() as i64;
176    }
177    out
178}
179
180/// The state of one pass over one zone.
181struct Build<'a> {
182    fs: &'a FileStore,
183    zone: &'a str,
184    opts: &'a Options,
185    gen: String,
186    /// The old file's bytes covered so far (a line boundary).
187    pos: i64,
188    /// The old file's counted lines covered so far.
189    old_lines: u64,
190    /// The new file's size and counted lines so far.
191    new_size: i64,
192    new_lines: u64,
193    /// Old receive-time records not yet translated, oldest first.
194    stamps: std::collections::VecDeque<(i64, i64, i64)>,
195    /// The old sidecar's bytes read so far.
196    stamps_read_to: i64,
197    stamps_out: Vec<(i64, i64)>,
198    hash: Sha256,
199    runs: Vec<Run>,
200    byte_runs: Vec<ByteRun>,
201    report: Report,
202}
203
204impl Build<'_> {
205    /// Read the old sidecar's records appended since the last read. A sidecar that shrank was replaced;
206    /// its records no longer say anything about this file and are dropped.
207    fn pull_stamps(&mut self) {
208        let Ok(Some(state)) = self.fs.line_state(self.zone, "output.tsidx") else { return };
209        if state.size < self.stamps_read_to {
210            self.stamps.clear();
211            self.stamps_read_to = state.size;
212            return;
213        }
214        let Ok(raw) = self.fs.read_bytes_db(self.zone, "output.tsidx", self.stamps_read_to, state.size - self.stamps_read_to) else { return };
215        let whole = raw.iter().rposition(|c| *c == b'\n').map_or(0, |p| p + 1);
216        self.stamps.extend(parse_stamps(&raw[..whole], self.stamps_read_to));
217        self.stamps_read_to += whole as i64;
218    }
219
220    /// Where the swap reads the old sidecar from: the first record not yet turned into one of the new
221    /// file's (those are for the lines the swap copies), or the end of what was read.
222    fn stamps_from(&self) -> i64 {
223        self.stamps.front().map_or(self.stamps_read_to, |s| s.2)
224    }
225
226    /// Plan, check and append one window of whole lines (the last of them a turn boundary, or the
227    /// window is the open end of the file: `end`).
228    fn window(&mut self, chunk: &[u8], end: WindowEnd) -> Result<(), String> {
229        if let Ok(text) = std::str::from_utf8(chunk) {
230            return self.window_text(text, end);
231        }
232        // A line that is not UTF-8 (a stray byte in a captured line) is kept as it is, byte for byte. The lines
233        // around it are planned as windows of their own, with `Open` so that no fragment whose message may
234        // continue past the line is dropped.
235        let (mut at, mut from) = (0usize, 0usize);
236        for raw in chunk.split_inclusive(|c| *c == b'\n') {
237            let to = at + raw.len();
238            if std::str::from_utf8(raw).is_err() {
239                if from < at {
240                    self.window_text(utf8(&chunk[from..at], self.pos)?, WindowEnd::Open)?;
241                }
242                self.window_raw(raw)?;
243                from = to;
244            }
245            at = to;
246        }
247        if from < chunk.len() {
248            self.window_text(utf8(&chunk[from..], self.pos)?, end)?;
249        }
250        Ok(())
251    }
252
253    /// One line that is not UTF-8, appended as it is. It is kept (never planned), hashed, and given the receive
254    /// times its offset has.
255    fn window_raw(&mut self, raw: &[u8]) -> Result<(), String> {
256        self.pull_stamps();
257        let window_end = self.pos + raw.len() as i64;
258        while let Some(&(off, ms, _)) = self.stamps.front() {
259            if off >= window_end {
260                break;
261            }
262            self.stamps.pop_front();
263            match self.stamps_out.last_mut() {
264                Some(last) if last.0 == self.new_size => last.1 = ms,
265                _ => self.stamps_out.push((self.new_size, ms)),
266            }
267        }
268        self.hash.update(raw.strip_suffix(b"\n").unwrap_or(raw));
269        self.hash.update(b"\n");
270        if !self.opts.dry_run {
271            self.fs.append_lines(self.zone, NEXT, raw).map_err(|e| format!("write: {e}"))?;
272            if !self.stamps_out.is_empty() {
273                let stamps: String = self.stamps_out.iter().map(|(off, ms)| format!("{{\"off\":{off},\"ms\":{ms}}}\n")).collect();
274                self.fs.append_lines(self.zone, NEXT_TSIDX, stamps.as_bytes()).map_err(|e| format!("write: {e}"))?;
275            }
276        }
277        self.stamps_out.clear();
278        self.pos = window_end;
279        self.old_lines += 1;
280        self.new_size += raw.len() as i64;
281        self.new_lines += 1;
282        self.report.windows += 1;
283        self.report.stats.lines += 1;
284        self.report.stats.kept += 1;
285        Ok(())
286    }
287
288    /// Plan, check and append the whole lines of `text`, valid UTF-8.
289    fn window_text(&mut self, text: &str, end: WindowEnd) -> Result<(), String> {
290        // Counted lines only, each with the byte offset it starts at.
291        let mut lines: Vec<&str> = Vec::new();
292        let mut starts: Vec<i64> = Vec::new();
293        let mut at = self.pos;
294        for raw in text.split_inclusive('\n') {
295            let line = raw.strip_suffix('\n').unwrap_or(raw);
296            if !is_blank_line(line.as_bytes()) {
297                lines.push(line);
298                starts.push(at);
299            }
300            at += raw.len() as i64;
301        }
302        // The records of the lines just read were written with them (one transaction), so reading the
303        // sidecar now, after the window, has every one of them.
304        self.pull_stamps();
305        let (new_lines, plan) = compact::compact_lines(&lines, end);
306        compact::verify(&lines, &new_lines).map_err(|f| format!("window at byte {}: check {f}", self.pos))?;
307        // The map: where each old line lands in the new bytes, for the receive times, and the dropped runs.
308        let mut new_starts: Vec<i64> = Vec::with_capacity(lines.len());
309        let mut cursor = self.new_size;
310        let mut synth = plan.synth.iter().peekable();
311        let mut run: Option<Run> = None;
312        for (i, line) in lines.iter().enumerate() {
313            new_starts.push(cursor);
314            if plan.actions[i] == compact::Action::Keep {
315                if let Some(r) = run.take() {
316                    self.runs.push(r);
317                }
318                cursor += line.len() as i64 + 1;
319            } else {
320                let r = run.get_or_insert(Run { old_line: self.old_lines + i as u64, dropped: 0, synthesized: 0 });
321                r.dropped += 1;
322            }
323            while let Some(s) = synth.next_if(|s| s.after == i) {
324                cursor += s.line.len() as i64 + 1;
325                if let Some(r) = run.as_mut() {
326                    r.synthesized += 1;
327                }
328            }
329        }
330        if let Some(r) = run.take() {
331            self.runs.push(r);
332        }
333        self.byte_runs.extend(byte_runs_of(&lines, &starts, self.pos, self.pos + text.len() as i64, &plan));
334        // Receive times of the lines in this window, at their new offsets (the last record per new offset).
335        let window_end = at;
336        while let Some(&(off, ms, _)) = self.stamps.front() {
337            if off >= window_end {
338                break;
339            }
340            self.stamps.pop_front();
341            let idx = starts.partition_point(|s| *s <= off).saturating_sub(1);
342            let new_off = new_starts.get(idx).copied().unwrap_or(self.new_size);
343            match self.stamps_out.last_mut() {
344                // Same new offset as the record before it: the later one is the nearer to the line.
345                Some(last) if last.0 == new_off => last.1 = ms,
346                _ => self.stamps_out.push((new_off, ms)),
347            }
348        }
349        // Append, hashing what is kept (the conversation sequence, the record's evidence).
350        let mut out = String::with_capacity(text.len());
351        for l in &new_lines {
352            out.push_str(l);
353            out.push('\n');
354        }
355        for (i, l) in lines.iter().enumerate() {
356            if plan.actions[i] == compact::Action::Keep {
357                self.hash.update(l.as_bytes());
358                self.hash.update(b"\n");
359            }
360        }
361        if !self.opts.dry_run && !out.is_empty() {
362            self.fs.append_lines(self.zone, NEXT, out.as_bytes()).map_err(|e| format!("write: {e}"))?;
363            if !self.stamps_out.is_empty() {
364                let raw: String = self.stamps_out.iter().map(|(off, ms)| format!("{{\"off\":{off},\"ms\":{ms}}}
365")).collect();
366                self.fs.append_lines(self.zone, NEXT_TSIDX, raw.as_bytes()).map_err(|e| format!("write: {e}"))?;
367            }
368        }
369        self.stamps_out.clear();
370        self.pos += text.len() as i64;
371        self.old_lines += lines.len() as u64;
372        self.new_size += out.len() as i64;
373        self.new_lines += new_lines.len() as u64;
374        self.report.windows += 1;
375        self.report.stats.absorb(&plan.stats);
376        Ok(())
377    }
378
379    /// The record of this pass, as the lines appended to `output.consol`: the map, then the summary
380    /// (small, so that its reader can take the file's last few KiB).
381    fn record(&self, old: &SwapBase, new_gen: &str, old_size: i64, tail: &TailCopy) -> Vec<u8> {
382        let mut byte_runs = self.byte_runs.clone();
383        byte_runs.extend(tail.dropped.iter().copied());
384        let map = Map { gen_before: old.gen.clone(), gen_after: new_gen.to_string(), runs: self.runs.clone(), byte_runs }.to_json();
385        let done = json!({
386            "k": "done", "v": 1, "at": agentmux_common::time::now_ms(),
387            "gen_before": old.gen, "gen_after": new_gen,
388            "bytes_before": old_size, "bytes_after": self.new_size, "tail_bytes": tail.bytes,
389            "lines_before": self.old_lines, "lines_after": self.new_lines,
390            "dropped_fragments": self.report.stats.dropped_fragments,
391            "interrupted_lines": self.report.stats.interrupted_lines,
392            "unproven_fragments": self.report.stats.unproven_fragments,
393            "pending_fragments": self.report.stats.pending_fragments,
394            "orphan_fragments": self.report.stats.orphan_fragments,
395            "sequence_sha256": hex::encode(self.hash.clone().finalize()),
396            "ok": true,
397        });
398        format!("{map}\n{done}\n").into_bytes()
399    }
400}
401
402/// The bytes of one window that the compact form did not carry over, as runs: dropped fragment lines,
403/// blank lines, and the interrupted lines written in place of fragments. `from..to` is the window.
404fn byte_runs_of(lines: &[&str], starts: &[i64], from: i64, to: i64, plan: &compact::Plan) -> Vec<ByteRun> {
405    let mut out = Vec::new();
406    let mut cur: Option<ByteRun> = None;
407    let mut at = from;
408    let mut synth = plan.synth.iter().peekable();
409    for (i, line) in lines.iter().enumerate() {
410        if starts[i] > at {
411            cur.get_or_insert(ByteRun { old_at: at, old_len: 0, new_len: 0 }).old_len += starts[i] - at;
412        }
413        let len = line.len() as i64 + 1;
414        if plan.actions[i] == compact::Action::Keep {
415            out.extend(cur.take());
416        } else {
417            cur.get_or_insert(ByteRun { old_at: starts[i], old_len: 0, new_len: 0 }).old_len += len;
418        }
419        while let Some(s) = synth.next_if(|s| s.after == i) {
420            cur.get_or_insert(ByteRun { old_at: starts[i] + len, old_len: 0, new_len: 0 }).new_len += s.line.len() as i64 + 1;
421        }
422        at = starts[i] + len;
423    }
424    if to > at {
425        cur.get_or_insert(ByteRun { old_at: at, old_len: 0, new_len: 0 }).old_len += to - at;
426    }
427    out.extend(cur);
428    out
429}
430
431/// The last summary line of `output.consol` (a `"k":"done"` entry), if there is one.
432fn last_done(fs: &FileStore, zone: &str) -> Option<Value> {
433    let size = fs.line_state(zone, CONSOL).ok()??.size;
434    let from = (size - 8192).max(0);
435    let raw = fs.read_bytes_db(zone, CONSOL, from, size - from).ok()?;
436    String::from_utf8_lossy(&raw)
437        .lines()
438        .rev()
439        .filter_map(|l| serde_json::from_str::<Value>(l).ok())
440        .find(|v| v.get("k").and_then(Value::as_str) == Some("done"))
441}
442
443/// Whether the zone's `output` was made compact by an earlier pass and nothing with a fragment has
444/// been appended since. A cheap check: the file's generation and the bytes past the recorded size.
445fn already_compact(fs: &FileStore, zone: &str, gen: &str, size: i64) -> bool {
446    let Some(done) = last_done(fs, zone) else { return false };
447    if done.get("gen_after").and_then(Value::as_str) != Some(gen) || done.get("ok") != Some(&Value::Bool(true)) {
448        return false;
449    }
450    // The file the pass produced ends where it recorded (plus the lines copied from the old end,
451    // which it counted in `bytes_after`); what has been appended since must hold no fragment.
452    let covered = done.get("bytes_after").and_then(Value::as_i64).unwrap_or(-1);
453    if covered < 0 || covered > size || done.get("pending_fragments").and_then(Value::as_u64).unwrap_or(1) != 0 {
454        return false;
455    }
456    let tail = size - covered;
457    if tail == 0 {
458        return true;
459    }
460    if tail > 64 << 20 {
461        return false;
462    }
463    match fs.read_bytes_db(zone, "output", covered, tail) {
464        Ok(bytes) => !bytes.windows(14).any(|w| w == b"\"stream_event\""),
465        Err(_) => false,
466    }
467}
468
469/// Throw away a half-built file and its sidecar.
470fn discard(fs: &FileStore, zone: &str) {
471    if let Err(e) = fs.delete_files(zone, &[NEXT, NEXT_TSIDX]) {
472        tracing::warn!(zone = %zone, error = %e, "history migrate: could not remove the half-built file");
473    }
474}
475
476/// Make one zone's `output` compact. See the module doc. Safe to call again at any time.
477pub fn migrate_zone(fs: &Arc<FileStore>, zone: &str, opts: &Options, stop: &AtomicBool) -> Report {
478    let mut report = Report::new(zone);
479    report.outcome = match run_zone(fs, zone, opts, stop, &mut report) {
480        Ok(o) => o,
481        Err(e) => Outcome::Failed(e),
482    };
483    // Only a build this pass made is this pass's to throw away.
484    if report.created_next && !matches!(report.outcome, Outcome::Swapped { .. }) {
485        discard(fs, zone);
486    }
487    report
488}
489
490/// `part` as text, or why it is not.
491fn utf8(part: &[u8], pos: i64) -> Result<&str, String> {
492    std::str::from_utf8(part).map_err(|e| format!("window at byte {pos}: not UTF-8 ({e})"))
493}
494
495/// The next window of the old file: whole lines, ending at the last turn boundary in what was read.
496/// It grows until it holds one or reaches the end of the file; the end of the file with none is a
497/// reply in progress (`false`).
498fn next_window(fs: &FileStore, zone: &str, gen: &str, pos: i64, remaining: i64, opts: &Options) -> Result<(Vec<u8>, bool), String> {
499    let mut want = opts.window_bytes.min(remaining);
500    loop {
501        if want == 0 {
502            return Ok((Vec::new(), false));
503        }
504        let bytes = read_old(fs, zone, gen, pos, want)?.ok_or("the file changed while it was read")?;
505        let whole = &bytes[..bytes.iter().rposition(|c| *c == b'\n').map_or(0, |p| p + 1)];
506        // A line that is not UTF-8 is never a turn boundary: it is kept as it is.
507        let (mut cut, mut at) = (None, 0usize);
508        for raw in whole.split_inclusive(|c| *c == b'\n') {
509            at += raw.len();
510            if std::str::from_utf8(raw).is_ok_and(|t| compact::is_turn_boundary(t.trim_end_matches('\n'))) {
511                cut = Some(at);
512            }
513        }
514        if let Some(cut) = cut {
515            return Ok((bytes[..cut].to_vec(), true));
516        }
517        if want >= remaining {
518            return Ok((whole.to_vec(), false));
519        }
520        if want >= opts.quiet_after_bytes {
521            if let Some(cut) = quiet_cut(whole) {
522                return Ok((bytes[..cut].to_vec(), true));
523            }
524        }
525        if want >= opts.max_window_bytes {
526            return Err(format!("no turn boundary and no quiet line within {want} bytes after byte {pos}"));
527        }
528        want = (want * 2).min(remaining).min(opts.max_window_bytes);
529    }
530}
531
532/// The byte just past the last line of `whole` after which no reply is in flight, for a stretch with no turn
533/// boundary. A line that is not UTF-8 is read as a line of no meaning.
534fn quiet_cut(whole: &[u8]) -> Option<usize> {
535    let mut lines: Vec<&str> = Vec::new();
536    let mut ends: Vec<usize> = Vec::new();
537    let mut at = 0usize;
538    for raw in whole.split_inclusive(|c| *c == b'\n') {
539        at += raw.len();
540        ends.push(at);
541        lines.push(std::str::from_utf8(raw).map_or("", |t| t.trim_end_matches('\n')));
542    }
543    compact::last_quiet_line(&lines).map(|i| ends[i])
544}
545
546fn run_zone(fs: &Arc<FileStore>, zone: &str, opts: &Options, stop: &AtomicBool, report: &mut Report) -> Result<Outcome, String> {
547    // A leftover older than a pass takes between two windows is a crash's; a newer one is another
548    // pass's, and this zone is left to it. One transaction, so two passes cannot both delete it.
549    if !opts.dry_run && !fs.discard_unless_fresh(zone, &[NEXT, NEXT_TSIDX], opts.busy_ms).map_err(|e| format!("discard: {e}"))? {
550        return Ok(Outcome::Busy);
551    }
552    let Some(stat) = fs.stat(zone, "output").map_err(|e| format!("stat: {e}"))? else { return Ok(Outcome::Empty) };
553    if stat.size == 0 {
554        return Ok(Outcome::Empty);
555    }
556    // A preview writes nothing, and counting a legacy file writes its epoch: a preview plans a legacy file
557    // without counting it (its generation is empty), and a real pass counts it first.
558    if !opts.dry_run && !super::counting::ensure_counted(fs, zone, Duration::from_secs(30)) {
559        return Err("the file has no line count yet".to_string());
560    }
561    let Some((size0, gen)) = old_state(fs, zone)? else { return Err("the file has no line count".to_string()) };
562    if gen.is_empty() && !opts.dry_run {
563        return Err("the file has no line count".to_string());
564    }
565    report.bytes_before = size0;
566    if already_compact(fs, zone, &gen, size0) {
567        return Ok(Outcome::AlreadyCompact);
568    }
569    if !opts.dry_run {
570        // Another pass that got here first made it: it is theirs, and not this pass's to delete.
571        match fs.make_file(zone, NEXT, FileMeta::new(), FileOpts::default()) {
572            Ok(()) => report.created_next = true,
573            Err(StoreError::AlreadyExists) => return Ok(Outcome::Busy),
574            Err(e) => return Err(format!("create: {e}")),
575        }
576        fs.make_file(zone, NEXT_TSIDX, FileMeta::new(), FileOpts::default()).map_err(|e| format!("create: {e}"))?;
577    }
578    let mut b = Build {
579        fs,
580        zone,
581        opts,
582        gen: gen.clone(),
583        pos: 0,
584        old_lines: 0,
585        new_size: 0,
586        new_lines: 0,
587        stamps: Default::default(),
588        stamps_read_to: 0,
589        stamps_out: Vec::new(),
590        hash: Sha256::new(),
591        runs: Vec::new(),
592        byte_runs: Vec::new(),
593        report: report.clone(),
594    };
595    let mut swaps = 0;
596    let out = loop {
597        if stopped(stop) {
598            break Outcome::Stopped;
599        }
600        let Some((size, now_gen)) = old_state(fs, zone)? else { break Outcome::Stale };
601        if now_gen != b.gen || size < b.pos {
602            break Outcome::Stale;
603        }
604        let remaining = size - b.pos;
605        let (chunk, has_boundary) = next_window(fs, zone, &b.gen, b.pos, remaining, opts)?;
606        if !has_boundary && remaining <= opts.max_tail {
607            // Everything that holds a finished turn is read: what is left is the live window.
608            if opts.dry_run {
609                break Outcome::DryRun;
610            }
611            let base = SwapBase { gen: b.gen.clone(), size: b.pos };
612            match swap_with_record(fs, zone, &base, &b, size, opts)? {
613                SwapOutcome::Swapped { new_gen, .. } => break Outcome::Swapped { new_gen },
614                SwapOutcome::Stale => break Outcome::Stale,
615                SwapOutcome::NotBuilt => return Err("the built file is not counted".to_string()),
616                SwapOutcome::Behind { .. } => {
617                    swaps += 1;
618                    if swaps >= opts.swap_attempts {
619                        return Err("the file keeps growing under the swap".to_string());
620                    }
621                    std::thread::sleep(opts.pause);
622                    continue;
623                }
624            }
625        }
626        if chunk.is_empty() {
627            return Err(format!("no whole line at byte {} (a line longer than the window, or an unterminated end)", b.pos));
628        }
629        b.window(&chunk, WindowEnd::Open)?;
630        if !opts.pause.is_zero() {
631            std::thread::sleep(opts.pause);
632        }
633    };
634    *report = b.report.clone();
635    report.bytes_after = b.new_size;
636    report.lines_before = b.old_lines;
637    report.lines_after = b.new_lines;
638    // L4: nothing but the live window's own fragments remains.
639    Ok(out)
640}
641
642/// The live tail the swap copies as it is, but through the line rule of an append: a blank line in it
643/// is not carried over, so the map says where those bytes were.
644struct TailCopy {
645    bytes: i64,
646    dropped: Vec<ByteRun>,
647}
648
649/// The blank lines of the old file's end, `base.size..old_size`, as the runs the copy leaves out. A
650/// tail the swap will not take (longer than `max_tail`, or not readable under `base.gen`) has none:
651/// the swap answers `Behind` or `Stale` and the record is not written.
652fn tail_copy(fs: &FileStore, zone: &str, base: &SwapBase, old_size: i64, opts: &Options) -> Result<TailCopy, String> {
653    let bytes = old_size - base.size;
654    let mut dropped = Vec::new();
655    if bytes > 0 && bytes <= opts.max_tail {
656        if let Some(tail) = read_old(fs, zone, &base.gen, base.size, bytes)? {
657            let mut at = base.size;
658            for raw in tail.split_inclusive(|b| *b == b'\n') {
659                if (raw.ends_with(b"\n") && is_blank_line(raw)) || !raw.ends_with(b"\n") {
660                    // A blank line is not carried over; neither is a torn last line the swap leaves out (it
661                    // does that only for a file idle for `settle_ms`; otherwise the swap is `Behind`).
662                    dropped.push(ByteRun { old_at: at, old_len: raw.len() as i64, new_len: 0 });
663                }
664                at += raw.len() as i64;
665            }
666        }
667    }
668    Ok(TailCopy { bytes, dropped })
669}
670
671/// The swap with its record. The record names the new generation, which the new file already has
672/// (it was minted when the file was made), so it is read first.
673fn swap_with_record(fs: &FileStore, zone: &str, base: &SwapBase, b: &Build<'_>, old_size: i64, opts: &Options) -> Result<SwapOutcome, String> {
674    let new_gen = fs
675        .line_state(zone, NEXT)
676        .map_err(|e| format!("read: {e}"))?
677        .and_then(|s| s.counted)
678        .map(|c| c.gen)
679        .ok_or("the built file is not counted")?;
680    let tail = tail_copy(fs, zone, base, old_size, opts)?;
681    // The pane's snapshot counts lines of the old file: its position moves through the same map.
682    let map = Map { gen_before: base.gen.clone(), gen_after: new_gen.clone(), runs: b.runs.clone(), byte_runs: b.byte_runs.clone() };
683    let snapshot = move |bytes: &[u8]| -> Option<Vec<u8>> {
684        let mut v: Value = serde_json::from_slice(bytes).ok()?;
685        let hwm = v.get("highWaterMark")?.as_u64()?;
686        v["highWaterMark"] = json!(map.line(hwm));
687        serde_json::to_vec(&v).ok()
688    };
689    let plan = SwapPlan {
690        next: NEXT,
691        name: "output",
692        renames: vec![SwapRename { from: NEXT_TSIDX, to: "output.tsidx" }],
693        drop: vec!["output.idx"],
694        records: vec![(CONSOL, b.record(base, &new_gen, old_size, &tail))],
695        rewrite: vec![(SNAPSHOT, &snapshot)],
696        max_tail: opts.max_tail,
697        settle_ms: opts.settle_ms,
698        stamps: Some(SwapStamps { old: "output.tsidx", read_to: b.stamps_from() }),
699    };
700    fs.swap_in_next(zone, base, &plan).map_err(|e| format!("swap: {e}"))
701}
702
703/// Run the pass over every zone of the store under `prefix` (`agent:`), one at a time. Returns the
704/// reports; a zone's failure never stops the next.
705pub fn migrate_all(fs: &Arc<FileStore>, prefix: &str, opts: &Options, stop: &AtomicBool) -> Vec<Report> {
706    let mut zones = fs.zone_ids_with_prefix(prefix).unwrap_or_default();
707    zones.sort();
708    let mut reports = Vec::new();
709    for zone in zones {
710        if stopped(stop) {
711            break;
712        }
713        if fs.stat(&zone, "output").ok().flatten().is_none() {
714            continue;
715        }
716        reports.push(migrate_zone(fs, &zone, opts, stop));
717    }
718    reports
719}
720
721#[cfg(test)]
722#[path = "migrate_tests.rs"]
723mod tests;