Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
indexing.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `output.idx` rebuild: a lazily-built, self-validating line-offset cache.
5
6use crate::backend::storage::filestore::FileStore;
7
8/// Magic header size for `output.idx`: the first 8 bytes are the `output` byte-size
9/// the index was built for. The index is valid iff this equals `output`'s current
10/// size; otherwise it is stale and must be rebuilt.
11pub(crate) const OUTPUT_IDX_HEADER_LEN: i64 = 8;
12
13/// Key in `output.idx`'s file metadata naming the `output` generation the
14/// index was built for (Phase 5a-2b; `filestore/counter.rs`). Written in the
15/// same transaction as the index, so the label always describes the bytes.
16const IDX_GEN_META: &str = "for_gen";
17
18const IDX: &str = "output.idx";
19
20/// `output`'s size and valid generation, from the database — never this
21/// process's `stat` cache, which another srv instance's append makes stale.
22/// A counter only behind (an older build appended since) is caught up first,
23/// so its generation holds across those appends (`filestore/counter.rs`).
24pub fn output_now(fs: &FileStore, zone: &str) -> Option<(u64, Option<String>)> {
25    let state = match fs.catch_up_line_counter(zone, "output") {
26        Ok(state) => state?,
27        Err(e) => {
28            crate::backend::transcript::damage::note_if_shared(fs, zone, "index read", &e);
29            return None;
30        }
31    };
32    Some((state.size.max(0) as u64, state.counted.map(|c| c.gen)))
33}
34
35/// `output` and its `output.idx` as they were at ONE moment — one database
36/// snapshot (Codex on #3634): separate reads of the index's size, header and
37/// label could each see a different version of an index another srv instance
38/// is rebuilding, and pass an old count off as fresh.
39pub struct OutputIndex {
40    pub output_size: u64,
41    /// `output`'s valid generation; `None` when it is not counted.
42    #[cfg(any(test, feature = "test-support"))]
43    pub output_gen: Option<String>,
44    /// The line count `output.idx` gives, if it describes `output` exactly:
45    /// its covered size is `output_size` and it is labelled with
46    /// `output_gen`. `None`: missing, stale, or another generation's.
47    pub fresh_lines: Option<u64>,
48}
49
50/// See [`OutputIndex`]. `None` when there is no `output`.
51pub fn output_index(fs: &FileStore, zone: &str) -> Option<OutputIndex> {
52    let snap = fs.derived_snapshot(zone, "output", IDX, Some(OUTPUT_IDX_HEADER_LEN)).ok()??;
53    let output_size = snap.output_size.max(0) as u64;
54    let fresh_lines = snap.derived.as_ref().and_then(|idx| {
55        let header = idx.bytes.as_deref()?;
56        let covered = u64::from_le_bytes(header.get(..8)?.try_into().ok()?);
57        (idx.size >= OUTPUT_IDX_HEADER_LEN
58            && covered == output_size
59            && labelled_for(&idx.meta, snap.output_gen.as_deref()))
60        .then_some(((idx.size - OUTPUT_IDX_HEADER_LEN) / 8) as u64)
61    });
62    Some(OutputIndex {
63        output_size,
64        #[cfg(any(test, feature = "test-support"))]
65        output_gen: snap.output_gen,
66        fresh_lines,
67    })
68}
69
70/// Whether an index with metadata `meta` may describe `output` of generation
71/// `output_gen`, apart from its covered size.
72///
73/// A size match alone is not proof: `output` replaced or restored with
74/// content that happens to reach the old covered size would have its lines
75/// read at another file's offsets. When `output` has a valid generation the
76/// index must be labelled with it; any mismatch — unlabelled (older build),
77/// or built for another generation — means rebuild, which is always safe.
78/// An uncounted `output` (legacy or written by an older build) keeps the
79/// covered-size rule alone, as before.
80fn labelled_for(meta: &crate::backend::storage::filestore::FileMeta, output_gen: Option<&str>) -> bool {
81    match output_gen {
82        None => true,
83        Some(gen) => meta.get(IDX_GEN_META).and_then(|v| v.as_str()) == Some(gen),
84    }
85}
86
87/// Lines `[offset, offset + limit)` of `output`, read through `output.idx`.
88pub struct IndexedRead {
89    /// Total line count of `output` in the snapshot.
90    pub total: u64,
91    /// The bytes of the requested lines (from the first line's offset up to
92    /// the next line's, or the end of `output`).
93    pub raw: Vec<u8>,
94    /// Byte offset in `output` of each returned line, in order.
95    pub line_offsets: Vec<u64>,
96    /// Receive-time stamps for the returned lines (unix ms, `0` = unknown),
97    /// from the `output.tsidx` sidecar in the same snapshot, so they are joined
98    /// to the lines they were written for (Codex on #3634). Only a window of
99    /// the sidecar around the lines is read (`stamps.rs`). `None`: no sidecar,
100    /// no records near the lines, or bytes not fully stored.
101    pub stamps: Option<Vec<i64>>,
102}
103
104/// Read lines `[offset, offset + limit)` of `output` through a fresh
105/// `output.idx`, with the freshness check, the index entries and the output
106/// bytes all from ONE database snapshot (Codex on #3634): validating in one
107/// read and fetching entries and bytes in later ones would let another srv
108/// instance replace `output` and rebuild the index in between — the answer
109/// would mix the new file's lines with the old file's total.
110///
111/// `None` when the index doesn't describe `output` in that snapshot (missing,
112/// stale, another generation's) or a read hits bytes not stored yet: the
113/// caller rebuilds the index and retries once, or takes its slow path.
114pub fn read_via_index(fs: &FileStore, zone: &str, offset: u64, limit: u64) -> Option<IndexedRead> {
115    read_indexed(fs, zone, offset, limit, false)
116}
117
118/// [`read_via_index`] from an index that covers only a prefix of `output`:
119/// lines appended since it was built aren't returned (`total` is the
120/// index's count), nor is the last indexed line, whose end the index can't
121/// give. For the read right after extending the index, when an append
122/// landed in between — before this, that read fell back to loading the
123/// whole transcript (1.3 GB, ~15 s, under the store's lock) whenever an
124/// agent's spawn was writing to the transcript its pane was opening
125/// (docs/reports/REPORT_AGENT_OPEN_STALL_RCA_2026_10_05.md). The lines it
126/// leaves out are the newest few, which the pane's live stream delivers.
127/// `None` under the same conditions as [`read_via_index`], and when nothing
128/// requested is within the indexed prefix.
129pub fn read_via_stale_index(fs: &FileStore, zone: &str, offset: u64, limit: u64) -> Option<IndexedRead> {
130    read_indexed(fs, zone, offset, limit, true)
131}
132
133fn read_indexed(fs: &FileStore, zone: &str, offset: u64, limit: u64, stale_ok: bool) -> Option<IndexedRead> {
134    const H: i64 = OUTPUT_IDX_HEADER_LEN;
135    fs.read_snapshot(|snap| {
136        let Some(out) = snap.file(zone, "output")? else { return Ok(None) };
137        let Some(idx) = snap.file(zone, IDX)? else { return Ok(None) };
138        let Some(header) = snap.bytes(zone, IDX, 0, H)? else { return Ok(None) };
139        let covered = u64::from_le_bytes(header.as_slice().try_into().unwrap_or([0; 8]));
140        let output_size = out.size.max(0) as u64;
141        // A prefix only counts for the same generation: a replaced `output`
142        // fails the label check whatever its size.
143        let fresh = covered == output_size;
144        let usable_prefix = stale_ok && covered < output_size && out.gen.is_some();
145        if idx.size < H || !(fresh || usable_prefix) || !labelled_for(&idx.meta, out.gen.as_deref()) {
146            return Ok(None);
147        }
148        let entries_total = ((idx.size - H) / 8) as u64;
149        // From a prefix, the last indexed line may have grown since: serve
150        // only lines whose end is the next entry.
151        let total = if fresh { entries_total } else { entries_total.saturating_sub(1) };
152        if !fresh && (limit == 0 || offset >= total) {
153            return Ok(None);
154        }
155        let mut read = IndexedRead {
156            total,
157            raw: Vec::new(),
158            line_offsets: Vec::new(),
159            stamps: None,
160        };
161        if limit == 0 || offset >= total {
162            return Ok(Some(read));
163        }
164        let count = limit.min(total - offset);
165        // Entries for the returned lines, plus the next line's (the end of
166        // the last returned line) when there is one.
167        let want = count + u64::from(offset + count < entries_total);
168        let Some(entries) = snap.bytes(zone, IDX, H + (offset * 8) as i64, (want * 8) as i64)? else { return Ok(None) };
169        let at = |k: u64| u64::from_le_bytes(entries[(k * 8) as usize..(k * 8 + 8) as usize].try_into().unwrap());
170        let start = at(0);
171        let end = if want > count { at(count) } else { output_size };
172        if start > end || end > output_size {
173            return Ok(None);
174        }
175        let Some(raw) = snap.bytes(zone, "output", start as i64, (end - start) as i64)? else { return Ok(None) };
176        read.raw = raw;
177        read.line_offsets = (0..count).map(at).collect();
178        const TS: &str = crate::backend::agent_session::TSIDX_FILE;
179        read.stamps = match snap.file(zone, TS)? {
180            Some(ts) if ts.size > 0 => {
181                let bytes = |off: i64, len: i64| snap.bytes(zone, TS, off, len);
182                super::stamps::stamps_for(&bytes, ts.size, &read.line_offsets)?
183            }
184            _ => None,
185        };
186        Ok(Some(read))
187    })
188    .map_err(|e| crate::backend::transcript::damage::note_if_shared(fs, zone, "index read", &e))
189    .ok()
190    .flatten()
191}
192
193/// How many lines of `zone`'s `output` start before byte `byte`, and how many
194/// there are: the line a reader loading up to `byte` stops at. A binary
195/// search over `output.idx`, from one snapshot; `None` when the index isn't
196/// fresh for `output` (extend it first, `extend_output_idx`).
197pub fn lines_before_byte(fs: &FileStore, zone: &str, byte: u64) -> Option<(u64, u64)> {
198    const H: i64 = OUTPUT_IDX_HEADER_LEN;
199    fs.read_snapshot(|snap| {
200        let Some(out) = snap.file(zone, "output")? else { return Ok(None) };
201        let Some(idx) = snap.file(zone, IDX)? else { return Ok(None) };
202        let Some(header) = snap.bytes(zone, IDX, 0, H)? else { return Ok(None) };
203        let covered = u64::from_le_bytes(header.as_slice().try_into().unwrap_or([0; 8]));
204        if idx.size < H || covered != out.size.max(0) as u64 || !labelled_for(&idx.meta, out.gen.as_deref()) {
205            return Ok(None);
206        }
207        let total = ((idx.size - H) / 8) as u64;
208        let (mut lo, mut hi) = (0u64, total);
209        while lo < hi {
210            let mid = lo + (hi - lo) / 2;
211            let Some(entry) = snap.bytes(zone, IDX, H + (mid * 8) as i64, 8)? else { return Ok(None) };
212            let start = u64::from_le_bytes(entry.as_slice().try_into().unwrap_or([0; 8]));
213            if start < byte {
214                lo = mid + 1;
215            } else {
216                hi = mid;
217            }
218        }
219        Ok(Some((lo, total)))
220    })
221    .ok()
222    .flatten()
223}
224
225/// Rebuild `output.idx` from `output` in a single streaming scan and atomically
226/// replace it. The index is the byte offset of every **non-blank** line, matching
227/// the reader's line addressing (`String::lines().filter(!trim().is_empty())`).
228///
229/// Layout: `[covered_size: u64-LE][offset_0: u64-LE][offset_1]...`. `covered_size`
230/// records the `output` size this index reflects so the read path can detect
231/// staleness in O(1) and rebuild only when `output` actually grew.
232///
233/// The scan streams `output` in 1 MiB windows so memory stays O(one line + offsets)
234/// rather than loading the whole (potentially multi-GB) file. Line splitting is
235/// done on raw bytes; since UTF-8 continuation bytes never collide with `\n`, lines
236/// are never split mid-codepoint, so per-line `from_utf8_lossy` matches the reader.
237///
238/// `output_size` and `output_gen` must be read together (`output_index`, or
239/// `output_now`): the index is published only if `output` is still
240/// `output_gen`, so a size taken from one file and a generation from its
241/// replacement would publish a partial index under the new generation (Codex
242/// on #3634).
243///
244/// Returns the number of indexed (non-blank) lines on success, or `None` if
245/// `output` is unreadable, was replaced during the scan, or the index write
246/// fails (caller falls back to slow path).
247#[cfg(any(test, feature = "test-support"))]
248pub fn rebuild_output_idx(
249    fs: &FileStore,
250    block_id: &str,
251    output_size: u64,
252    output_gen: Option<String>,
253) -> Option<u64> {
254    build_output_idx_from(fs, block_id, output_size, 0, Vec::new(), 0, output_gen, None)
255}
256
257/// Bring an existing `output.idx` up to `output`'s current size by scanning
258/// ONLY the appended bytes, instead of rescanning from byte zero.
259///
260/// Falls back to a full rebuild whenever the existing index can't be trusted
261/// as a base: missing, header unreadable, no entries yet, built for another
262/// generation, or `output` shrank below what the index already covers
263/// (rotation/truncation).
264///
265/// Why this exists: the index is a pure cache with no incremental mutation, so
266/// a stale one used to mean a full O(file-size) rescan. On a live agent
267/// `output` grows continuously, so "stale" was the steady state — a 30-second
268/// line-count poll drove 37 full rebuilds in 19 minutes on a 759 MB
269/// transcript, mean 3168 ms, ~10% duty cycle
270/// (docs/reports/REPORT_AGENT_PANE_LOAD_RENDER_ARCHITECTURE_2026_08_27.md §5).
271///
272/// Returning the stale count instead was tried and is WRONG: `line_count`
273/// feeds `useHistoryPagination`'s tail window (`offset = total - PAGE_SIZE`),
274/// so an undercount silently drops the most recent history on reopen — codex
275/// P1 on PR #2838. The count has to stay exact; only the cost of keeping it
276/// exact is negotiable.
277pub fn extend_output_idx(fs: &FileStore, block_id: &str) -> Option<u64> {
278    // A counter merely behind (an older build appended) is caught up first:
279    // otherwise the snapshot below sees no generation, the index is published
280    // unlabelled, and the next reader — once the counter has caught up —
281    // rejects it and rebuilds the whole index.
282    let _ = fs.catch_up_line_counter(block_id, "output");
283    // An append that lost a race (the index changed under it, e.g. another
284    // srv instance extended it first) gets one more go from a fresh snapshot,
285    // then a full rebuild — never a failure, which would send a history read
286    // to the whole-file fallback.
287    for _ in 0..2 {
288        match try_extend(fs, block_id) {
289            Extend::Done(lines) => return lines,
290            Extend::Raced => continue,
291        }
292    }
293    let (output_size, output_gen) = output_now(fs, block_id)?;
294    build_output_idx_from(fs, block_id, output_size, 0, Vec::new(), 0, output_gen, None)
295}
296
297enum Extend {
298    Done(Option<u64>),
299    /// The index changed between the snapshot and the append.
300    Raced,
301}
302
303fn try_extend(fs: &FileStore, block_id: &str) -> Extend {
304    const H: i64 = OUTPUT_IDX_HEADER_LEN;
305    // Only what extending needs, in ONE snapshot: `output`'s size and
306    // generation, and the index's size, label, header and last entry. Reading
307    // the whole index here (15 MB for a 1.9 M-line transcript) and rewriting
308    // it was most of the cost of every pane open.
309    let base = fs.read_snapshot(|snap| {
310        let Some(out) = snap.file(block_id, "output")? else { return Ok(None) };
311        let idx = snap.file(block_id, IDX)?;
312        let ends = match &idx {
313            Some(i) if i.size >= H + 8 && (i.size - H) % 8 == 0 => {
314                Some((snap.bytes(block_id, IDX, 0, H)?, snap.bytes(block_id, IDX, i.size - 8, 8)?))
315            }
316            _ => None,
317        };
318        Ok(Some((out, idx, ends)))
319    });
320    if let Err(e) = &base {
321        crate::backend::transcript::damage::note_if_shared(fs, block_id, "index rebuild", e);
322    }
323    let Ok(Some((out, idx, ends))) = base else { return Extend::Done(None) };
324    let output_size = out.size.max(0) as u64;
325    let output_gen = out.gen;
326    let full = || Extend::Done(build_output_idx_from(fs, block_id, output_size, 0, Vec::new(), 0, output_gen.clone(), None));
327
328    let Some(idx) = idx else { return full() };
329    // Extending reuses every entry but the last, so it needs proof that the
330    // index describes a prefix of THIS `output`: a valid generation, and the
331    // index labelled with it. An uncounted `output` has no such proof — an
332    // older build may have rewritten it (its `rev` moved, the epoch with it)
333    // to something longer than the index covers (Codex on #3663) — and an
334    // index built for another generation is no base at all. Both rebuild.
335    if output_gen.is_none() || !labelled_for(&idx.meta, output_gen.as_deref()) {
336        return full();
337    }
338    // No entries, a torn size, or bytes not stored: nothing to anchor on.
339    let Some((Some(header), Some(last))) = ends else { return full() };
340    let entry_count = ((idx.size - H) / 8) as u64;
341    let covered = u64::from_le_bytes(header.as_slice().try_into().unwrap_or([0; 8]));
342
343    if covered == output_size {
344        return Extend::Done(Some(entry_count)); // already current
345    }
346    // Shrank (rotated/truncated): a base we can't trust.
347    if covered > output_size {
348        return full();
349    }
350
351    // Re-scan from the START of the last indexed line, not from `covered`. The
352    // previous build may have indexed a trailing line that had no newline yet;
353    // bytes appended since continue THAT line rather than starting a new one,
354    // so its entry has to be re-derived (it may also have been blank then and
355    // non-blank now). Everything before it is settled and stays as it is.
356    let seed_entries = entry_count - 1;
357    let scan_start = u64::from_le_bytes(last.as_slice().try_into().unwrap_or([0; 8]));
358    if scan_start > output_size {
359        return full();
360    }
361    match build_output_idx_from(fs, block_id, output_size, scan_start, Vec::new(), seed_entries, output_gen.clone(), Some(idx.size)) {
362        Some(lines) => Extend::Done(Some(lines)),
363        None => Extend::Raced,
364    }
365}
366
367/// Shared scanner behind both entry points.
368///
369/// `scan_start` MUST be the byte offset of a line start (0, or an offset read
370/// back out of the index). `seed` is the raw offset bytes for the lines before
371/// it and `seed_count` how many — they are copied through untouched, so the
372/// blank/CRLF rules only ever get applied by the one loop below and the two
373/// paths can't drift apart.
374#[allow(clippy::too_many_arguments)]
375fn build_output_idx_from(
376    fs: &FileStore,
377    block_id: &str,
378    output_size: u64,
379    scan_start: u64,
380    seed: Vec<u8>,
381    seed_count: u64,
382    for_gen: Option<String>,
383    // `Some(index size)`: append to the existing index instead of replacing
384    // it — keep its first `seed_count` entries where they are, write the new
385    // ones after them and the new covered size in its header, only if it is
386    // still that size (`FileStore::patch_derived_if`). `seed` is then empty.
387    append_to: Option<i64>,
388) -> Option<u64> {
389    const WIN: i64 = 1 << 20; // 1 MiB read window
390
391    // Start/duration logging (docs/status/STATUS_CROSS_CHANNEL_AGENT_OPEN_FULL_APP_FREEZE_2026_08_22.md
392    // §7.1): the prior completion-only log recorded a rebuild happened but
393    // not how long it ran for or when it started, so a live incident
394    // couldn't be checked for whether a rebuild's execution window actually
395    // overlapped some other stalled RPC — only that both happened "around
396    // the same time." Kept as a lasting diagnostic, not a one-off debug
397    // print — a slow rebuild is exactly the kind of thing worth being able
398    // to correlate after the fact, the same way `mem_attribution` already is.
399    let started = std::time::Instant::now();
400    // `for_gen`: the generation of `output` this index is built for, taken by
401    // the caller BEFORE anything it builds on (seed entries, scanned bytes)
402    // was read. The write below only lands if it is still current.
403    tracing::info!(
404        block_id = %block_id,
405        covered = output_size,
406        scan_start,
407        scanned_bytes = output_size.saturating_sub(scan_start),
408        incremental = scan_start > 0,
409        "output.idx rebuild starting"
410    );
411
412    // Offsets buffer starts with the covered-size header, then any reused
413    // entries for the region before `scan_start`.
414    let mut buf: Vec<u8> = Vec::new();
415    if append_to.is_none() {
416        buf.extend_from_slice(&output_size.to_le_bytes());
417        buf.extend_from_slice(&seed);
418    }
419
420    let mut line_count: u64 = seed_count;
421    let mut cursor: u64 = scan_start; // byte offset where the current line begins
422    let mut line_buf: Vec<u8> = Vec::new(); // bytes of the current line, excluding '\n'
423    let mut read_pos: i64 = scan_start as i64;
424
425    let flush_line = |line_buf: &mut Vec<u8>,
426                      cursor: &mut u64,
427                      buf: &mut Vec<u8>,
428                      line_count: &mut u64,
429                      had_newline: bool| {
430        // The reader strips a trailing '\r' (CRLF) and treats trim-empty as
431        // blank. Shared with the FileStore line counter, which must agree.
432        let is_blank = crate::backend::storage::filestore::is_blank_line(line_buf);
433        if !is_blank {
434            buf.extend_from_slice(&cursor.to_le_bytes());
435            *line_count += 1;
436        }
437        // Advance cursor past this line's bytes (+1 for the consumed '\n').
438        *cursor += line_buf.len() as u64 + if had_newline { 1 } else { 0 };
439        line_buf.clear();
440    };
441
442    while read_pos < output_size as i64 {
443        // From the database, bounded by `output_size`: `read_at` clamps to
444        // this process's cached size, which another instance's append can
445        // leave behind — the index would then claim lines it never scanned.
446        let len = WIN.min(output_size as i64 - read_pos);
447        let chunk = match fs.read_bytes_db(block_id, "output", read_pos, len) {
448            Ok(v) => v,
449            Err(e) => {
450                crate::backend::transcript::damage::note_if_shared(fs, block_id, "index rebuild", &e);
451                // codex P2 on #2724: every exit path must log a terminal
452                // event (with duration) — an unmatched "starting" event with
453                // no completion reads as "still running," easy to mistake
454                // for a rebuild that was active throughout an incident when
455                // it actually failed fast and returned immediately.
456                tracing::warn!(
457                    block_id = %block_id,
458                    error = %e,
459                    duration_ms = started.elapsed().as_millis() as u64,
460                    "output.idx rebuild failed: read_at error"
461                );
462                return None;
463            }
464        };
465        if chunk.is_empty() {
466            break;
467        }
468        for &b in &chunk {
469            if b == b'\n' {
470                flush_line(&mut line_buf, &mut cursor, &mut buf, &mut line_count, true);
471            } else {
472                line_buf.push(b);
473            }
474        }
475        read_pos += chunk.len() as i64;
476    }
477    // Trailing line with no final '\n'.
478    if !line_buf.is_empty() {
479        flush_line(&mut line_buf, &mut cursor, &mut buf, &mut line_count, false);
480    }
481
482    // Index and its generation label in one transaction (created if missing),
483    // and only if `output` is still that generation (Codex on #3634): a
484    // replace during the scan must neither publish an index of the old bytes
485    // nor hand this caller offsets it would then apply to the new file.
486    let mut label = std::collections::HashMap::new();
487    label.insert(
488        IDX_GEN_META.to_string(),
489        for_gen.clone().map_or(serde_json::Value::Null, serde_json::Value::String),
490    );
491    let written = match (append_to, for_gen.as_deref()) {
492        (None, _) => fs.put_file_with_meta_if(block_id, IDX, &buf, label, "output", for_gen.as_deref()),
493        (Some(idx_size), Some(gen)) => fs.patch_derived_if(
494            block_id,
495            IDX,
496            &output_size.to_le_bytes(),
497            OUTPUT_IDX_HEADER_LEN + seed_count as i64 * 8,
498            &buf,
499            "output",
500            gen,
501            idx_size,
502        ),
503        // Appending needs a generation to guard on (`try_extend` checks).
504        (Some(_), None) => Ok(false),
505    };
506    match written {
507        Ok(false) => {
508            tracing::info!(
509                block_id = %block_id,
510                duration_ms = started.elapsed().as_millis() as u64,
511                "output.idx rebuild discarded: output was replaced, or the index changed, during the scan"
512            );
513            None
514        }
515        Ok(true) => {
516            tracing::info!(
517                block_id = %block_id,
518                lines = line_count,
519                covered = output_size,
520                duration_ms = started.elapsed().as_millis() as u64,
521                "output.idx rebuilt"
522            );
523            Some(line_count)
524        }
525        Err(e) => {
526            crate::backend::transcript::damage::note_if_shared(fs, block_id, "index rebuild", &e);
527            tracing::warn!(
528                block_id = %block_id,
529                error = %e,
530                duration_ms = started.elapsed().as_millis() as u64,
531                "output.idx rebuild write failed"
532            );
533            None
534        }
535    }
536}
537
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542    use crate::backend::storage::filestore::{FileMeta, FileOpts};
543
544    #[test]
545    fn a_rebuild_for_a_generation_that_is_no_longer_current_publishes_nothing() {
546        // Codex P2 on #3634: `output` replaced after the builder captured its
547        // generation. The index of the old bytes must not be written, and the
548        // caller must not get a count (it would apply those offsets to the new
549        // file).
550        let fs = FileStore::open_in_memory().unwrap();
551        let zone = "blk-idx-guard";
552        fs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
553        fs.append_lines(zone, "output", b"a\nb\nc\n").unwrap();
554        let old = output_now(&fs, zone).and_then(|(_, g)| g);
555        fs.write_file(zone, "output", b"x\n").unwrap();
556
557        assert_eq!(build_output_idx_from(&fs, zone, 6, 0, Vec::new(), 0, old, None), None);
558        assert!(fs.line_state(zone, "output.idx").unwrap().is_none(), "no index may be published");
559
560        // With the current generation it builds and publishes.
561        assert_eq!(rebuild_output_idx(&fs, zone, 2, output_now(&fs, zone).and_then(|(_, g)| g)), Some(1));
562        assert!(fs.line_state(zone, "output.idx").unwrap().is_some());
563    }
564
565    #[test]
566    fn a_read_through_the_index_comes_from_one_snapshot_or_not_at_all() {
567        let fs = FileStore::open_in_memory().unwrap();
568        let zone = "blk-idx-read";
569        fs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
570        fs.append_lines(zone, "output", b"{\"a\":1}\n{\"b\":2}\n{\"c\":3}\n").unwrap();
571        // No index yet: nothing to read through.
572        assert!(read_via_index(&fs, zone, 0, 10).is_none());
573        let view = output_index(&fs, zone).unwrap();
574        assert_eq!(rebuild_output_idx(&fs, zone, view.output_size, view.output_gen), Some(3));
575
576        let r = read_via_index(&fs, zone, 1, 10).unwrap();
577        assert_eq!((r.total, r.line_offsets.clone()), (3, vec![8, 16]));
578        assert_eq!(r.raw, b"{\"b\":2}\n{\"c\":3}\n");
579        assert_eq!(r.stamps, None, "no stamp sidecar yet");
580        // Stamps come from the sidecar in the same snapshot as the lines: per
581        // line, the newest record at or before its offset.
582        let stamps: &[u8] = b"{\"off\":0,\"ms\":7}\n{\"off\":16,\"ms\":9}\n";
583        fs.make_file(zone, crate::backend::agent_session::TSIDX_FILE, FileMeta::default(), FileOpts::default()).unwrap();
584        fs.append_data(zone, crate::backend::agent_session::TSIDX_FILE, stamps).unwrap();
585        assert_eq!(read_via_index(&fs, zone, 1, 10).unwrap().stamps, Some(vec![7, 9]));
586        let r = read_via_index(&fs, zone, 0, 1).unwrap();
587        assert_eq!((r.line_offsets.clone(), r.raw), (vec![0], b"{\"a\":1}\n".to_vec()));
588        assert!(read_via_index(&fs, zone, 5, 10).unwrap().line_offsets.is_empty());
589
590        // Replaced by content of the same size and a different layout: the
591        // index no longer describes it, so nothing is read through it.
592        fs.write_file(zone, "output", b"{\"x\":11111}\n{\"y\":22222}\n").unwrap();
593        assert_eq!(fs.line_state(zone, "output").unwrap().unwrap().size, 24);
594        assert!(read_via_index(&fs, zone, 0, 10).is_none());
595    }
596
597    /// An agent's spawn appending to the transcript between the index being
598    /// extended and the read: the strict read gives up (the index no longer
599    /// covers `output`), and the stale read serves the indexed lines whose end
600    /// is known — never the last indexed line, which the append may continue.
601    #[test]
602    fn a_read_outrun_by_an_append_serves_the_indexed_prefix() {
603        let fs = FileStore::open_in_memory().unwrap();
604        let zone = "blk-idx-stale";
605        fs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
606        fs.append_lines(zone, "output", b"{\"a\":1}\n{\"b\":2}\n{\"c\":3}\n").unwrap();
607        let view = output_index(&fs, zone).unwrap();
608        assert_eq!(rebuild_output_idx(&fs, zone, view.output_size, view.output_gen), Some(3));
609        fs.append_lines(zone, "output", b"{\"d\":4}\n").unwrap();
610
611        assert!(read_via_index(&fs, zone, 0, 10).is_none(), "the index no longer covers output");
612        let r = read_via_stale_index(&fs, zone, 0, 10).unwrap();
613        assert_eq!(r.total, 2, "lines 0 and 1; line 2's end isn't in the index");
614        assert_eq!(r.line_offsets, vec![0, 8]);
615        assert_eq!(r.raw, b"{\"a\":1}\n{\"b\":2}\n");
616        let r = read_via_stale_index(&fs, zone, 1, 10).unwrap();
617        assert_eq!((r.line_offsets.clone(), r.raw), (vec![8], b"{\"b\":2}\n".to_vec()));
618        assert!(read_via_stale_index(&fs, zone, 2, 10).is_none(), "nothing requested is in the usable prefix");
619        assert!(read_via_stale_index(&fs, zone, 0, 0).is_none());
620    }
621
622    #[test]
623    fn a_stale_read_refuses_a_replaced_output() {
624        let fs = FileStore::open_in_memory().unwrap();
625        let zone = "blk-idx-stale-replaced";
626        fs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
627        fs.append_lines(zone, "output", b"{\"a\":1}\n{\"b\":2}\n").unwrap();
628        let view = output_index(&fs, zone).unwrap();
629        assert_eq!(rebuild_output_idx(&fs, zone, view.output_size, view.output_gen), Some(2));
630        // Replaced by longer content: a prefix of the old file is no prefix of this one.
631        fs.replace_file(zone, "output", b"{\"x\":11111}\n{\"y\":22222}\n{\"z\":3}\n", &[]).unwrap();
632        assert!(read_via_stale_index(&fs, zone, 0, 10).is_none());
633    }
634
635    /// Extending in place (header patched, new entries appended) must leave
636    /// exactly the bytes a full rebuild of the same `output` writes — through
637    /// blank lines, a line still open when the index was last built, and
638    /// enough entries to cross a 64 KB part.
639    #[test]
640    fn extending_in_place_matches_a_full_rebuild() {
641        let fs = FileStore::open_in_memory().unwrap();
642        let (zone, twin) = ("blk-idx-extend", "blk-idx-extend-twin");
643        for z in [zone, twin] {
644            fs.make_file(z, "output", FileMeta::default(), FileOpts::default()).unwrap();
645        }
646        let many: String = (0..9000).map(|i| format!("{{\"n\":{i}}}\n")).collect();
647        let chunks: Vec<&[u8]> = vec![b"{\"a\":1}\n\n{\"b\":", b"2}\n{\"c\":3}\n  \n", many.as_bytes(), b"{\"tail\":"];
648        for chunk in chunks {
649            for z in [zone, twin] {
650                fs.append_data(z, "output", chunk).unwrap();
651            }
652            assert!(output_now(&fs, zone).unwrap().1.is_some(), "output must stay counted, or extending only ever rebuilds");
653            let extended = extend_output_idx(&fs, zone).unwrap();
654            let view = output_index(&fs, twin).unwrap();
655            let rebuilt = rebuild_output_idx(&fs, twin, view.output_size, view.output_gen).unwrap();
656            assert_eq!(extended, rebuilt);
657            assert_eq!(
658                fs.read_file(zone, IDX).unwrap(),
659                fs.read_file(twin, IDX).unwrap(),
660                "extended index differs from a rebuild after {} lines",
661                rebuilt
662            );
663        }
664        assert_eq!(output_index(&fs, zone).unwrap().fresh_lines, Some(9004));
665    }
666
667    #[test]
668    fn a_fresh_index_reads_the_same_through_either_door() {
669        let fs = FileStore::open_in_memory().unwrap();
670        let zone = "blk-idx-fresh-both";
671        fs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
672        fs.append_lines(zone, "output", b"{\"a\":1}\n{\"b\":2}\n").unwrap();
673        let view = output_index(&fs, zone).unwrap();
674        rebuild_output_idx(&fs, zone, view.output_size, view.output_gen).unwrap();
675        let strict = read_via_index(&fs, zone, 0, 10).unwrap();
676        let stale = read_via_stale_index(&fs, zone, 0, 10).unwrap();
677        assert_eq!((strict.total, strict.raw), (stale.total, stale.raw));
678    }
679}