Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
stamps.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Receive-time stamps for a range of transcript lines, from the
5//! `output.tsidx` sidecar — without loading the sidecar whole.
6//!
7//! The sidecar holds one record per append, `{"off":<byte offset>,"ms":<unix
8//! ms>}\n`, in append order, so `off` rises through the file. A line's stamp is
9//! the newest record at or before the line's own byte offset (`0` = unknown).
10//!
11//! `blockfile:read_range` used to read the whole sidecar and parse every
12//! record to stamp ~200 lines: 38 MB and ~1.1M records on a long-lived agent,
13//! about 0.6 s per read. Instead, a binary search over the sidecar's bytes
14//! finds the record the first line needs, and only a window around the
15//! requested range is read and parsed.
16//!
17//! Records a little out of order (two srv instances mirroring into one global
18//! zone, older builds stamping outside the append's transaction) are
19//! tolerated: the window reaches [`MARGIN`] bytes past both ends of the range
20//! and its records are sorted. A record further out of place than that can be
21//! missed, so a line may get an earlier stamp — stamps are best-effort display
22//! times, and a miss that far out would need thousands of records out of
23//! order.
24
25use crate::backend::storage::error::StoreError;
26
27/// Bytes read before the range's first record and past its last, for
28/// out-of-order records (~2,000 records at ~30 bytes each).
29pub(crate) const MARGIN: i64 = 64 * 1024;
30/// Bytes read at each binary-search probe; a record is ~30 bytes.
31const PROBE: i64 = 512;
32/// Once the search interval is this small, the window just covers it.
33const SEARCH_STOP: i64 = 4096;
34/// Chunk size for the window read.
35const CHUNK: i64 = 64 * 1024;
36
37#[derive(serde::Deserialize)]
38struct Record {
39    off: u64,
40    ms: i64,
41}
42
43fn parse(line: &[u8]) -> Option<(u64, i64)> {
44    let line = line.strip_suffix(b"\r").unwrap_or(line);
45    serde_json::from_slice::<Record>(line).ok().map(|r| (r.off, r.ms))
46}
47
48/// Stamps for `line_offsets` (ascending byte offsets in `output`), read from a
49/// sidecar of `size` bytes through `read(offset, len)` — `None` from `read`
50/// means those bytes aren't all stored (a writer mid-append), and so no stamps.
51/// `Ok(None)`: no sidecar records near the range at all.
52pub fn stamps_for(
53    read: &dyn Fn(i64, i64) -> Result<Option<Vec<u8>>, StoreError>,
54    size: i64,
55    line_offsets: &[u64],
56) -> Result<Option<Vec<i64>>, StoreError> {
57    let (Some(&first), Some(&last)) = (line_offsets.first(), line_offsets.last()) else {
58        return Ok(Some(Vec::new()));
59    };
60    if size <= 0 {
61        return Ok(None);
62    }
63
64    // The latest record boundary whose record is at or before `first`.
65    let (mut lo, mut hi) = (0i64, size);
66    while hi - lo > SEARCH_STOP {
67        let mid = lo + (hi - lo) / 2;
68        match first_record_after(read, mid, hi)? {
69            Probe::Found { start, off, .. } if off <= first => lo = start,
70            Probe::Found { .. } | Probe::NoneBefore => hi = mid,
71            Probe::Unreadable => return Ok(None),
72        }
73    }
74
75    // Everything from MARGIN before that record to MARGIN past the first
76    // record beyond `last`.
77    let from = (lo - MARGIN).max(0);
78    let mut records: Vec<(u64, i64)> = Vec::new();
79    let mut pos = from;
80    let mut carry: Vec<u8> = Vec::new();
81    let mut at_line_start = from == 0;
82    let mut stop_at: Option<i64> = None;
83    while pos < size && stop_at.map_or(true, |s| pos < s) {
84        let len = CHUNK.min(size - pos);
85        let Some(chunk) = read(pos, len)? else { return Ok(None) };
86        carry.extend_from_slice(&chunk);
87        pos += len;
88        let Some(last_nl) = carry.iter().rposition(|&b| b == b'\n') else { continue };
89        let complete: Vec<u8> = carry.drain(..=last_nl).collect();
90        let mut lines = complete.split(|&b| b == b'\n');
91        if !at_line_start {
92            // The window began mid-record: skip to the first boundary.
93            lines.next();
94            at_line_start = true;
95        }
96        for line in lines {
97            if let Some((off, ms)) = parse(line) {
98                records.push((off, ms));
99                if off > last && stop_at.is_none() {
100                    stop_at = Some(pos + MARGIN);
101                }
102            }
103        }
104    }
105    // An unterminated last record (a stamp mid-write) still counts if whole.
106    if pos >= size && at_line_start {
107        if let Some(rec) = parse(&carry) {
108            records.push(rec);
109        }
110    }
111    if records.is_empty() {
112        return Ok(None);
113    }
114    records.sort_by_key(|&(off, _)| off);
115    Ok(Some(
116        line_offsets
117            .iter()
118            .map(|&line_off| match records.partition_point(|&(off, _)| off <= line_off) {
119                0 => 0,
120                p => records[p - 1].1,
121            })
122            .collect(),
123    ))
124}
125
126/// The byte offset in `output` of the first line received after `at_ms`:
127/// where a reader showing the transcript up to that time stops. `Ok(Some(None))`
128/// when every record is at or before it; `Ok(None)` when bytes it needs aren't
129/// stored. Records rise in time as they do in offset, so a binary search finds
130/// the region; a scan from there finds the record.
131pub fn byte_after_time(
132    read: &dyn Fn(i64, i64) -> Result<Option<Vec<u8>>, StoreError>,
133    size: i64,
134    at_ms: i64,
135) -> Result<Option<Option<u64>>, StoreError> {
136    let (mut lo, mut hi) = (0i64, size);
137    while hi - lo > SEARCH_STOP {
138        let mid = lo + (hi - lo) / 2;
139        match first_record_after(read, mid, hi)? {
140            Probe::Found { start, ms, .. } if ms <= at_ms => lo = start,
141            Probe::Found { .. } | Probe::NoneBefore => hi = mid,
142            Probe::Unreadable => return Ok(None),
143        }
144    }
145    let mut pos = lo;
146    let mut carry: Vec<u8> = Vec::new();
147    while pos < size {
148        let len = CHUNK.min(size - pos);
149        let Some(chunk) = read(pos, len)? else { return Ok(None) };
150        carry.extend_from_slice(&chunk);
151        pos += len;
152        while let Some(nl) = carry.iter().position(|&b| b == b'\n') {
153            if let Some((off, ms)) = parse(&carry[..nl]) {
154                if ms > at_ms {
155                    return Ok(Some(Some(off)));
156                }
157            }
158            carry.drain(..=nl);
159        }
160    }
161    Ok(Some(parse(&carry).filter(|&(_, ms)| ms > at_ms).map(|(off, _)| off)))
162}
163
164/// The byte length of the sidecar's part that stamps `output` bytes before
165/// `end`: the start of the first record at or past `end`, or `size` when every
166/// record is before it. Read through `read` like [`stamps_for`]; `Ok(None)` when
167/// bytes it needs aren't stored. A copy of a transcript's first `end` bytes
168/// takes this much of its sidecar. Records out of order across the cut land on
169/// whichever side the scan finds them.
170pub(crate) fn cut_before(
171    read: &dyn Fn(i64, i64) -> Result<Option<Vec<u8>>, StoreError>,
172    size: i64,
173    end: u64,
174) -> Result<Option<i64>, StoreError> {
175    // The latest record boundary whose record is before `end`.
176    let (mut lo, mut hi) = (0i64, size);
177    while hi - lo > SEARCH_STOP {
178        let mid = lo + (hi - lo) / 2;
179        match first_record_after(read, mid, hi)? {
180            Probe::Found { start, off, .. } if off < end => lo = start,
181            Probe::Found { .. } | Probe::NoneBefore => hi = mid,
182            Probe::Unreadable => return Ok(None),
183        }
184    }
185    // From there, the first record at or past `end`.
186    let mut pos = lo;
187    let mut carry: Vec<u8> = Vec::new();
188    let mut carry_start = lo;
189    while pos < size {
190        let len = CHUNK.min(size - pos);
191        let Some(chunk) = read(pos, len)? else { return Ok(None) };
192        carry.extend_from_slice(&chunk);
193        pos += len;
194        while let Some(nl) = carry.iter().position(|&b| b == b'\n') {
195            if parse(&carry[..nl]).is_some_and(|(off, _)| off >= end) {
196                return Ok(Some(carry_start));
197            }
198            carry.drain(..=nl);
199            carry_start += nl as i64 + 1;
200        }
201    }
202    if parse(&carry).is_some_and(|(off, _)| off >= end) {
203        return Ok(Some(carry_start));
204    }
205    Ok(Some(size))
206}
207
208/// The sidecar for a copy of `output`'s bytes `[cut, end)`: the records from the first one at or past
209/// `cut` to the last before `end`, with their offsets lowered by `cut`, led by a record at 0 that
210/// carries the newest time before the cut so the copy's first line has one. Read through `read` like
211/// [`stamps_for`]; `Ok(None)` when bytes it needs aren't stored. Empty when the sidecar holds no
212/// record near the cut.
213pub(crate) fn rebase_range(
214    read: &dyn Fn(i64, i64) -> Result<Option<Vec<u8>>, StoreError>,
215    size: i64,
216    cut: u64,
217    end: u64,
218) -> Result<Option<Vec<u8>>, StoreError> {
219    let Some(from) = cut_before(read, size, cut)? else { return Ok(None) };
220    // The record just before the cut: the last whole line of the window ahead of `from`.
221    let back = from.min(MARGIN);
222    let lead = if back > 0 {
223        let Some(bytes) = read(from - back, back)? else { return Ok(None) };
224        let whole = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
225        whole.rsplit(|&b| b == b'\n').next().and_then(parse).map(|(_, ms)| ms)
226    } else {
227        None
228    };
229    let mut records: Vec<(u64, i64)> = Vec::new();
230    let (mut pos, mut carry) = (from, Vec::new());
231    'read: while pos < size {
232        let len = CHUNK.min(size - pos);
233        let Some(chunk) = read(pos, len)? else { return Ok(None) };
234        carry.extend_from_slice(&chunk);
235        pos += len;
236        while let Some(nl) = carry.iter().position(|&b| b == b'\n') {
237            if let Some((off, ms)) = parse(&carry[..nl]) {
238                if off >= end {
239                    carry.clear();
240                    break 'read;
241                }
242                records.push((off.saturating_sub(cut), ms));
243            }
244            carry.drain(..=nl);
245        }
246    }
247    if let Some(rec) = parse(&carry).filter(|r| r.0 < end) {
248        records.push((rec.0.saturating_sub(cut), rec.1));
249    }
250    let mut out = Vec::new();
251    if let Some(ms) = lead.filter(|_| records.first().map_or(true, |&(off, _)| off > 0)) {
252        out.extend_from_slice(format!("{{\"off\":0,\"ms\":{ms}}}\n").as_bytes());
253    }
254    for (off, ms) in records {
255        out.extend_from_slice(format!("{{\"off\":{off},\"ms\":{ms}}}\n").as_bytes());
256    }
257    Ok(Some(out))
258}
259
260enum Probe {
261    /// The first parsable record starting after `pos`.
262    Found { start: i64, off: u64, ms: i64 },
263    /// No parsable record starts in `[pos, hi)`.
264    NoneBefore,
265    /// Bytes not stored.
266    Unreadable,
267}
268
269/// The first parsable record that starts after `pos` (at a line boundary
270/// strictly past it) and before `hi`.
271fn first_record_after(
272    read: &dyn Fn(i64, i64) -> Result<Option<Vec<u8>>, StoreError>,
273    pos: i64,
274    hi: i64,
275) -> Result<Probe, StoreError> {
276    let mut at = pos;
277    let mut buf: Vec<u8> = Vec::new();
278    let mut boundary: Option<i64> = None;
279    while at < hi {
280        let len = PROBE.min(hi - at);
281        let Some(chunk) = read(at, len)? else { return Ok(Probe::Unreadable) };
282        buf.extend_from_slice(&chunk);
283        at += len;
284        let base = pos;
285        if boundary.is_none() {
286            let Some(nl) = buf.iter().position(|&b| b == b'\n') else { continue };
287            boundary = Some(base + nl as i64 + 1);
288        }
289        // Parse complete records from the boundary on.
290        let mut start = boundary.unwrap();
291        loop {
292            let rel = (start - base) as usize;
293            if rel >= buf.len() || start >= hi {
294                break;
295            }
296            let Some(len) = buf[rel..].iter().position(|&b| b == b'\n') else { break };
297            if let Some((off, ms)) = parse(&buf[rel..rel + len]) {
298                return Ok(Probe::Found { start, off, ms });
299            }
300            start += len as i64 + 1;
301        }
302        boundary = Some(start);
303    }
304    Ok(Probe::NoneBefore)
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use proptest::prelude::*;
311
312    /// What `read_range` computed before: every record, sorted.
313    fn reference(sidecar: &[u8], line_offsets: &[u64]) -> Option<Vec<i64>> {
314        let mut entries: Vec<(u64, i64)> = sidecar.split(|&b| b == b'\n').filter_map(parse).collect();
315        if entries.is_empty() {
316            return None;
317        }
318        entries.sort_by_key(|&(off, _)| off);
319        Some(
320            line_offsets
321                .iter()
322                .map(|&l| match entries.partition_point(|&(off, _)| off <= l) {
323                    0 => 0,
324                    p => entries[p - 1].1,
325                })
326                .collect(),
327        )
328    }
329
330    fn windowed(sidecar: &[u8], line_offsets: &[u64]) -> Option<Vec<i64>> {
331        let read = |off: i64, len: i64| -> Result<Option<Vec<u8>>, StoreError> {
332            let (a, b) = (off as usize, ((off + len) as usize).min(sidecar.len()));
333            Ok(Some(sidecar[a..b].to_vec()))
334        };
335        stamps_for(&read, sidecar.len() as i64, line_offsets).unwrap()
336    }
337
338    fn sidecar(records: &[(u64, i64)]) -> Vec<u8> {
339        records.iter().map(|(o, m)| format!("{{\"off\":{o},\"ms\":{m}}}\n")).collect::<String>().into_bytes()
340    }
341
342    #[test]
343    fn a_large_sidecar_gives_the_same_stamps_reading_a_small_window() {
344        let records: Vec<(u64, i64)> = (0..200_000u64).map(|i| (i * 300, 1_700_000_000_000 + i as i64)).collect();
345        let bytes = sidecar(&records);
346        let lines: Vec<u64> = (0..200u64).map(|k| 45_000_000 + k * 150).collect();
347        let read_bytes = std::cell::Cell::new(0i64);
348        let read = |off: i64, len: i64| -> Result<Option<Vec<u8>>, StoreError> {
349            read_bytes.set(read_bytes.get() + len);
350            let (a, b) = (off as usize, ((off + len) as usize).min(bytes.len()));
351            Ok(Some(bytes[a..b].to_vec()))
352        };
353        let got = stamps_for(&read, bytes.len() as i64, &lines).unwrap();
354        assert_eq!(got, reference(&bytes, &lines));
355        assert!(read_bytes.get() < 400 * 1024, "read {} of {} bytes", read_bytes.get(), bytes.len());
356    }
357
358    #[test]
359    fn a_cut_is_where_the_first_record_at_or_past_the_end_starts() {
360        let records: Vec<(u64, i64)> = (0..200_000u64).map(|i| (i * 300, 1_700_000_000_000 + i as i64)).collect();
361        let bytes = sidecar(&records);
362        let read = |off: i64, len: i64| -> Result<Option<Vec<u8>>, StoreError> {
363            let (a, b) = (off as usize, ((off + len) as usize).min(bytes.len()));
364            Ok(Some(bytes[a..b].to_vec()))
365        };
366        let size = bytes.len() as i64;
367        // The expected cut: the bytes of every record before `end`.
368        let expect = |end: u64| -> i64 {
369            let keep = records.partition_point(|&(off, _)| off < end);
370            records[..keep].iter().map(|(o, m)| format!("{{\"off\":{o},\"ms\":{m}}}
371").len() as i64).sum()
372        };
373        for end in [0u64, 1, 299, 300, 301, 45_000_000, 45_000_001, 59_999_700, 60_000_000] {
374            assert_eq!(cut_before(&read, size, end).unwrap(), Some(expect(end)), "end {end}");
375        }
376        assert_eq!(cut_before(&read, size, 0).unwrap(), Some(0));
377        assert_eq!(cut_before(&read, size, u64::MAX).unwrap(), Some(size));
378        assert_eq!(cut_before(&read, 0, 10).unwrap(), Some(0));
379        let unreadable = |_: i64, _: i64| -> Result<Option<Vec<u8>>, StoreError> { Ok(None) };
380        assert_eq!(cut_before(&unreadable, size, 45_000_000).unwrap(), None);
381    }
382
383    #[test]
384    fn a_copy_that_starts_at_a_cut_gets_the_records_after_it_moved_to_zero() {
385        let records: Vec<(u64, i64)> = (0..200_000u64).map(|i| (i * 300, 1_700_000_000_000 + i as i64)).collect();
386        let bytes = sidecar(&records);
387        let read = |off: i64, len: i64| -> Result<Option<Vec<u8>>, StoreError> {
388            let (a, b) = (off as usize, ((off + len) as usize).min(bytes.len()));
389            Ok(Some(bytes[a..b].to_vec()))
390        };
391        let size = bytes.len() as i64;
392        // A cut between records: the lead is the record before it, at 0; the rest follow, lowered.
393        let cut = 45_000_150u64;
394        let got = rebase_range(&read, size, cut, u64::MAX).unwrap().unwrap();
395        let parsed: Vec<(u64, i64)> = got.split(|&b| b == b'\n').filter_map(parse).collect();
396        assert_eq!(parsed[0], (0, 1_700_000_000_000 + 150_000), "the record before the cut leads, at 0");
397        assert_eq!(parsed[1], (150, 1_700_000_000_000 + 150_001), "the first record past the cut");
398        assert_eq!(parsed.len(), 1 + (200_000 - 150_001), "every later record");
399        assert!(parsed.windows(2).all(|w| w[0].0 <= w[1].0));
400        // A cut on a record: no lead is added over it.
401        let on = rebase_range(&read, size, 45_000_000, u64::MAX).unwrap().unwrap();
402        let first = on.split(|&b| b == b'\n').filter_map(parse).next().unwrap();
403        assert_eq!(first, (0, 1_700_000_000_000 + 150_000));
404        // At the very start, and past the end.
405        assert_eq!(rebase_range(&read, size, 0, u64::MAX).unwrap().unwrap(), bytes);
406        assert!(rebase_range(&read, size, u64::MAX, u64::MAX).unwrap().unwrap().len() < 40, "only the lead");
407        assert!(rebase_range(&read, 0, 10, u64::MAX).unwrap().unwrap().is_empty());
408        // A copy that stops at an end: no record at or past it.
409        let bounded = rebase_range(&read, size, 45_000_150, 45_001_000).unwrap().unwrap();
410        let offs: Vec<u64> = bounded.split(|&b| b == b'\n').filter_map(parse).map(|r| r.0).collect();
411        assert_eq!(offs, vec![0, 150, 450, 750], "the lead, then the records below the end, lowered");
412        let unreadable = |_: i64, _: i64| -> Result<Option<Vec<u8>>, StoreError> { Ok(None) };
413        assert_eq!(rebase_range(&unreadable, size, 45_000_000, u64::MAX).unwrap(), None);
414    }
415
416    #[test]
417    fn lines_before_every_record_are_unknown_and_an_empty_sidecar_has_none() {
418        let bytes = sidecar(&[(100, 7), (200, 8)]);
419        assert_eq!(windowed(&bytes, &[0, 99, 100, 250]), Some(vec![0, 0, 7, 8]));
420        assert_eq!(windowed(b"", &[1]), None);
421        assert_eq!(windowed(b"garbage\n", &[1]), None);
422        assert_eq!(windowed(&bytes, &[]), Some(vec![]));
423    }
424
425    #[test]
426    fn bytes_not_stored_mean_no_stamps() {
427        let bytes = sidecar(&(0..5000u64).map(|i| (i * 10, i as i64)).collect::<Vec<_>>());
428        let read = |off: i64, len: i64| -> Result<Option<Vec<u8>>, StoreError> {
429            Ok((off + len < 60_000).then(|| bytes[off as usize..(off + len) as usize].to_vec()))
430        };
431        assert_eq!(stamps_for(&read, bytes.len() as i64, &[49_000]).unwrap(), None);
432    }
433
434    proptest! {
435        /// Sorted sidecars with local disorder, garbage lines, CRLF and an
436        /// unterminated last record: the windowed read matches the full parse.
437        #[test]
438        fn windowed_stamps_equal_the_full_parse(
439            n in 1usize..6000,
440            gaps in prop::collection::vec(0u64..400, 1..64),
441            swaps in prop::collection::vec(0usize..6000, 0..40),
442            garbage in prop::collection::vec(0usize..6000, 0..10),
443            crlf in any::<bool>(),
444            unterminated in any::<bool>(),
445            picks in prop::collection::vec(0u64..2_500_000, 1..60),
446        ) {
447            let mut off = 0u64;
448            let mut records: Vec<(u64, i64)> = (0..n).map(|i| { off += gaps[i % gaps.len()]; (off, i as i64 + 1) }).collect();
449            // Local disorder: neighbours swapped.
450            for s in swaps { if s + 1 < records.len() { records.swap(s, s + 1); } }
451            let mut text = String::new();
452            for (i, (o, m)) in records.iter().enumerate() {
453                if garbage.contains(&i) { text.push_str("{\"off\":oops\n"); }
454                text.push_str(&format!("{{\"off\":{o},\"ms\":{m}}}"));
455                text.push_str(if crlf { "\r\n" } else { "\n" });
456            }
457            if unterminated { let t = text.trim_end().len(); text.truncate(t); }
458            let bytes = text.into_bytes();
459            let mut lines = picks.clone();
460            lines.sort_unstable();
461            // A read_range asks for one contiguous run of lines: bound the span.
462            let lo = lines[0];
463            let lines: Vec<u64> = lines.into_iter().filter(|&l| l - lo < 20_000).collect();
464            prop_assert_eq!(windowed(&bytes, &lines), reference(&bytes, &lines));
465        }
466    }
467}