Skip to main content

agentmux_srv/server/app_api/
blockfile_read.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `blockfile:read_range`: where the lines come from (the `output.idx` index, the
5//! whole file, the broker's ring buffer) and how a read is checked and trimmed before it is answered.
6
7use super::*;
8
9type FileStoreRef = Arc<crate::backend::storage::filestore::FileStore>;
10
11/// What the guards at the end of a read need to know about it.
12pub(super) struct RangeRead<'a> {
13    pub(super) cmd: &'a CommandBlockfileReadRangeData,
14    /// The stores a transcript's lines are attributed from (a transcript only).
15    pub(super) stores: (&'a crate::backend::storage::store::Store, &'a crate::backend::storage::filestore::FileStore),
16    pub(super) offset: usize,
17    pub(super) stream: String,
18    /// Who signed the transcript's lines (a transcript only).
19    pub(super) owner: Option<String>,
20    /// `output`'s generation before the lines were read (a transcript only).
21    pub(super) gen_before: Option<String>,
22}
23
24/// The answer for a read that expected a generation the file is no longer in.
25pub(super) fn mismatch(stream: &str, gen: Option<String>) -> BlockfileReadRangeResult {
26    BlockfileReadRangeResult { stream: Some(stream.to_string()), gen, gen_mismatch: Some(true), ..Default::default() }
27}
28
29impl RangeRead<'_> {
30    /// Vets, trims and stamps the lines read, given `output`'s generation after the read.
31    pub(super) fn finish(&self, mut result: BlockfileReadRangeResult, gen_after: Option<String>) -> BlockfileReadRangeResult {
32        let cmd = self.cmd;
33        if let Some(owner) = &self.owner {
34            crate::backend::transcript::attribution::vet_for_viewer(self.stores.0, self.stores.1, owner, &mut result.lines);
35        }
36        if let Some(turns) = cmd.tail_turns.filter(|t| *t > 0) {
37            trim_to_last_turns(&mut result, self.offset as u64, turns as usize);
38        }
39        if let Some(bytes) = cmd.tail_bytes.filter(|b| *b > 0) {
40            trim_to_tail_bytes(&mut result, self.offset as u64, bytes as usize);
41        }
42        if self.gen_before.is_some() && gen_after == self.gen_before {
43            result.stream = Some(self.stream.clone());
44            result.gen = self.gen_before.clone();
45            result
46        } else if cmd.expect_gen.is_some() {
47            mismatch(&self.stream, gen_after)
48        } else {
49            result
50        }
51    }
52}
53
54/// The lines `output.idx` serves for this window, or `None` when the whole-file path has to answer.
55pub(super) async fn indexed_window(
56    filestore: &FileStoreRef,
57    read_block: &str,
58    block_id: &str,
59    offset: usize,
60    limit: usize,
61    clock: &mut ReadRangeClock,
62) -> Option<BlockfileReadRangeResult> {
63    // Runs on the blocking pool (#2841). A full rebuild is a
64    // streaming scan of `output`, which reaches hundreds of MB
65    // on a long-lived agent, and every index/output read in
66    // `read_from_index` is blocking file I/O as well — none of it may occupy a
67    // Tokio runtime worker. The body (`read_from_index`) is unchanged; only
68    // where it runs is.
69    let idx_clock = std::sync::Arc::new(std::sync::Mutex::new(IndexClock::default()));
70    let idx_result: Option<BlockfileReadRangeResult> = {
71        let filestore = filestore.clone();
72        let read_block = read_block.to_string();
73        let idx_clock = idx_clock.clone();
74        let spawned = std::time::Instant::now();
75        let compute = move || read_from_index(&filestore, &read_block, offset, limit, &idx_clock, spawned);
76        // A panic in the scan must degrade to the slow path
77        // (the whole-file read), not fail the read — but it is logged rather
78        // than silently swallowed.
79        match tokio::task::spawn_blocking(compute).await {
80            Ok(v) => v,
81            Err(e) => {
82                tracing::warn!(
83                    block_id = %block_id,
84                    error = %e,
85                    "blockfile:read_range: output.idx task failed; falling back"
86                );
87                None
88            }
89        }
90    };
91    clock.index = Some(std::mem::take(&mut *idx_clock.lock().unwrap()));
92    idx_result
93}
94
95/// How long a read waits for a file with no line epoch to be counted (the pane's read allows 30 s).
96const INDEX_COUNT_WAIT: std::time::Duration = std::time::Duration::from_secs(20);
97
98/// The read on the blocking pool: brings `output.idx` up to date and reads the window through it.
99fn read_from_index(
100    filestore: &FileStoreRef,
101    read_block: &str,
102    offset: usize,
103    limit: usize,
104    idx_clock: &std::sync::Mutex<IndexClock>,
105    spawned: std::time::Instant,
106) -> Option<BlockfileReadRangeResult> {
107    use crate::backend::blockcontroller::shell::{extend_output_idx, read_via_index, read_via_stale_index};
108    idx_clock.lock().unwrap().queued_ms = ms_since(spawned);
109    let run = std::time::Instant::now();
110    let out_stat = filestore.stat(read_block, "output").ok()??;
111    if out_stat.opts.circular {
112        return None; // circular files: fall back to slow path
113    }
114    // A file with no line epoch has no generation to label the index with, so the index is rebuilt
115    // from byte 0 by every read and, while the file grows, never serves one (seconds each on a
116    // gigabyte transcript, then refused). Count it first: once per file, shared by every reader.
117    // Still counting after the wait: the whole-file path answers (a small file) or refuses (a
118    // large one, with a retry), without rebuilding.
119    if !crate::backend::transcript::counting::ensure_counted(filestore, read_block, INDEX_COUNT_WAIT) {
120        return None;
121    }
122    // Everything the answer rests on — the index judged fresh,
123    // its entries, the output bytes they point at — comes from
124    // ONE database snapshot (Codex on #3634), never the stale
125    // per-process `stat` cache. A missing or stale index is
126    // rebuilt once, for the output as a snapshot saw it, and read
127    // again in a new snapshot; if that still doesn't match
128    // (replaced again meanwhile), the whole-file path answers.
129    // A missing or stale index is brought up to date by
130    // extending it from its last line — scanning only the
131    // bytes appended since, as `line_count` did before it
132    // answered from the counter (5a-3b). A full rebuild on
133    // every read of a grown file cost seconds on a large
134    // agent zone. `extend_output_idx` still rebuilds when
135    // the index can't be a base (another generation's,
136    // shrunk, missing).
137    let read = match read_via_index(filestore, read_block, offset as u64, limit as u64) {
138        Some(read) => read,
139        None => {
140            let extend = std::time::Instant::now();
141            let extended = extend_output_idx(filestore, read_block);
142            idx_clock.lock().unwrap().extend_ms = Some(ms_since(extend));
143            // A failed extension leaves an index that
144            // may be far behind: its prefix isn't a
145            // stand-in for the read, so take the
146            // whole-file path (#4384).
147            extended?;
148            match read_via_index(filestore, read_block, offset as u64, limit as u64) {
149                Some(read) => read,
150                // The extension succeeded, so only an
151                // append that landed since (an agent's
152                // spawn writing to the transcript its pane
153                // is opening) can make this miss: serve
154                // the indexed prefix, a few lines short at
155                // most, rather than read the whole file
156                // (docs/reports/REPORT_AGENT_OPEN_STALL_RCA_2026_10_05.md).
157                None => {
158                    let read = read_via_stale_index(filestore, read_block, offset as u64, limit as u64)?;
159                    idx_clock.lock().unwrap().stale = true;
160                    read
161                }
162            }
163        }
164    };
165    idx_clock.lock().unwrap().run_ms = ms_since(run);
166    let total_lines = read.total;
167
168    // Empty result cases — answered from the index, no output read.
169    if read.line_offsets.is_empty() {
170        return Some(BlockfileReadRangeResult { lines: vec![], total: total_lines, ..Default::default() });
171    }
172    let raw = read.raw;
173    let text = String::from_utf8_lossy(&raw);
174    let lines: Vec<String> = text
175        .lines()
176        .filter(|l| !l.trim().is_empty())
177        .map(|l| l.to_string())
178        .collect();
179
180    // Receive-time stamps for the returned lines, from the
181    // output.tsidx sidecar in the same snapshot as the lines
182    // (`read_via_index`; only a window of the sidecar is
183    // read). Best-effort: no stamps is never a failed read.
184    // Offsets and lines must pair up one to one.
185    let stamps = read.stamps.filter(|s| s.len() == lines.len());
186
187    Some(BlockfileReadRangeResult { lines, total: total_lines, stamps, ..Default::default() })
188}
189
190
191/// The lines the broker's ring buffer holds for this file of the block.
192pub(super) fn ring_buffer_lines(broker: &Arc<crate::backend::mps::Broker>, cmd: &CommandBlockfileReadRangeData) -> Vec<String> {
193    // Fallback: reconstruct from MPS event ring buffer.
194    // The ring buffer holds at most MAX_PERSIST = 4096 events and the
195    // broker's byte cap per scope; older events are evicted. Offset 0 =
196    // oldest retained line.
197    let scope = format!("block:{}", cmd.block_id);
198    let events = broker.read_event_history(
199        crate::backend::mps::EVENT_BLOCK_FILE,
200        &scope,
201        usize::MAX, // broker clamps to MAX_PERSIST internally
202    );
203
204    let mut lines: Vec<String> = Vec::new();
205    for event in events {
206        let Some(ref event_data) = event.data else { continue };
207        let ev_filename = event_data.get("filename")
208            .and_then(|v| v.as_str()).unwrap_or("");
209        if ev_filename != cmd.filename {
210            continue;
211        }
212        let Some(data64) = event_data.get("data64").and_then(|v| v.as_str()) else { continue };
213        let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(data64) else { continue };
214        let text = String::from_utf8_lossy(&bytes);
215        for line in text.lines() {
216            if !line.trim().is_empty() {
217                lines.push(line.to_string());
218            }
219        }
220    }
221    lines
222}
223
224
225/// The whole file from the store, when it has one worth reading, or the refusal to read a huge one.
226/// `None` falls back to the ring buffer.
227pub(super) fn whole_file_lines(
228    filestore: &FileStoreRef,
229    read_block: &str,
230    cmd: &CommandBlockfileReadRangeData,
231    started: std::time::Instant,
232) -> Result<Option<Vec<String>>, String> {
233    Ok(match filestore.stat(read_block, &cmd.filename) {
234        Ok(Some(ref wf)) if wf.size > 0 => {
235            if !whole_file_read_allowed(&cmd.filename, wf.opts.circular, wf.size) {
236                tracing::warn!(
237                    block_id = %cmd.block_id,
238                    size = wf.size,
239                    total_ms = ms_since(started),
240                    "blockfile:read_range: output.idx can't serve this read and the transcript is too large to read whole; refusing"
241                );
242                return Err(format!(
243                    "blockfile:read_range: the transcript index for {} is unavailable right now; retry",
244                    cmd.block_id
245                ));
246            }
247            if wf.size >= WHOLE_FILE_WARN_BYTES {
248                tracing::warn!(
249                    block_id = %cmd.block_id,
250                    filename = %cmd.filename,
251                    size = wf.size,
252                    "blockfile:read_range: reading the whole file (no usable output.idx)"
253                );
254            }
255            match filestore.read_file(read_block, &cmd.filename) {
256                Ok(Some(bytes)) => {
257                    let text = String::from_utf8_lossy(&bytes);
258                    let lines: Vec<String> = text.lines()
259                        .filter(|l| !l.trim().is_empty())
260                        .map(|l| l.to_string())
261                        .collect();
262                    Some(lines)
263                }
264                Ok(None) => None,
265                Err(e) => {
266                    tracing::warn!(
267                        block_id = %cmd.block_id,
268                        filename = %cmd.filename,
269                        error = %e,
270                        "blockfile:read_range: filestore read failed, falling back to ring buffer"
271                    );
272                    None
273                }
274            }
275        }
276        Ok(_) => None, // file absent or empty → fall back
277        Err(e) => {
278            tracing::warn!(
279                block_id = %cmd.block_id,
280                error = %e,
281                "blockfile:read_range: filestore stat failed, falling back to ring buffer"
282            );
283            None
284        }
285    })
286}