1use std::collections::HashSet;
27use std::path::{Path, PathBuf};
28use std::sync::{Arc, OnceLock};
29
30use crate::backend::storage::error::StoreError;
31use crate::backend::transcript::damage;
32use crate::backend::storage::filestore::{FileStore, FrameOutcome, CODEC_DELTAS, CODEC_DELTA_API, CODEC_ZSTD, FRAME_PARTS};
33
34pub const SETTING_FRAMES: &str = "agent:transcriptframes";
36pub const SETTING_DELTAS: &str = "agent:transcriptdeltas";
39
40const OUTPUT: &str = "output";
41const TSIDX: &str = "output.tsidx";
42const TAIL_BYTES: i64 = 1 << 20;
44const QUIET_MS: i64 = 10 * 60 * 1000;
47const PART_BYTES: i64 = 65536;
49pub const PASS_FRAMES: usize = 64;
51const FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(40);
53const READS_CODECS: [i64; 3] = [CODEC_ZSTD, CODEC_DELTAS, CODEC_DELTA_API];
56const WRITES_CODECS: [i64; 3] = [CODEC_ZSTD, CODEC_DELTAS, CODEC_DELTA_API];
58
59static CONFIG: OnceLock<Arc<crate::backend::wconfig::ConfigState>> = OnceLock::new();
60
61pub fn install_config(config: Arc<crate::backend::wconfig::ConfigState>) {
63 let _ = CONFIG.set(config);
64}
65
66pub fn enabled() -> bool {
69 #[cfg(test)]
70 if FRAMES_OFF_FOR_TEST.with(std::cell::Cell::get) {
71 return false;
72 }
73 on_unless_false(CONFIG.get().and_then(|c| c.extra_bool(SETTING_FRAMES)))
74}
75
76#[cfg(test)]
77thread_local! {
78 static FRAMES_OFF_FOR_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
79}
80
81#[cfg(test)]
84pub(crate) fn set_frames_off_for_test(off: bool) {
85 FRAMES_OFF_FOR_TEST.with(|c| c.set(off));
86}
87
88fn on_unless_false(setting: Option<bool>) -> bool {
89 setting.unwrap_or(true)
90}
91
92fn deltas_enabled() -> bool {
93 CONFIG.get().and_then(|c| c.extra_bool(SETTING_DELTAS)).unwrap_or(true)
94}
95
96fn readers_dir(store_dir: &Path) -> PathBuf {
97 store_dir.join("readers")
98}
99
100pub(crate) fn start_time(sys: &sysinfo::System, pid: u32) -> Option<u64> {
102 sys.process(sysinfo::Pid::from_u32(pid)).map(|p| p.start_time())
103}
104
105pub(crate) fn scan_processes() -> sysinfo::System {
106 let mut sys = sysinfo::System::new();
107 sys.refresh_processes_specifics(
108 sysinfo::ProcessesToUpdate::All,
109 true,
110 sysinfo::ProcessRefreshKind::nothing()
111 .without_tasks()
112 .with_cmd(sysinfo::UpdateKind::Always)
113 .with_exe(sysinfo::UpdateKind::Always),
114 );
115 sys
116}
117
118pub fn mark_reader(store_dir: &Path) {
123 let pid = std::process::id();
124 let sys = scan_processes();
125 let mark = serde_json::json!({
126 "pid": pid,
127 "started_s": start_time(&sys, pid).unwrap_or(0),
128 "version": env!("CARGO_PKG_VERSION"),
129 "codecs": READS_CODECS,
130 });
131 let dir = readers_dir(store_dir);
132 let result = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(dir.join(format!("{pid}.json")), mark.to_string()));
133 if let Err(e) = result {
134 tracing::warn!(error = %e, dir = %dir.display(), "framer: couldn't write this srv's readers file; framing waits for it");
135 }
136}
137
138pub(crate) fn is_srv(name: &str) -> bool {
139 name.to_ascii_lowercase().starts_with("agentmux-srv")
140}
141
142static LAST_PASS: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1);
144
145pub fn note_pass(frames: usize, done: bool) {
147 let frames = if done { 0 } else { frames as i64 };
148 LAST_PASS.store(frames, std::sync::atomic::Ordering::Relaxed);
149}
150
151pub fn steady() -> bool {
155 let last = LAST_PASS.load(std::sync::atomic::Ordering::Relaxed);
156 !enabled() || (0..=4).contains(&last)
157}
158
159pub fn other_srv() -> Option<String> {
164 let sys = scan_processes();
165 let me = std::process::id();
166 sys.processes().iter().find_map(|(pid, process)| {
167 let name = process.name().to_string_lossy().to_string();
168 let monitor = process.cmd().iter().any(|a| a.to_string_lossy() == "--crash-monitor");
169 (pid.as_u32() != me && is_srv(&name) && !monitor).then(|| format!("{name} (pid {}) is running", pid.as_u32()))
170 })
171}
172
173pub fn who_blocks(store_dir: &Path) -> Option<String> {
177 let sys = scan_processes();
178 let dir = readers_dir(store_dir);
179 if let Ok(entries) = std::fs::read_dir(&dir) {
181 for entry in entries.flatten() {
182 let path = entry.path();
183 let alive = path
184 .file_stem()
185 .and_then(|s| s.to_str())
186 .and_then(|s| s.parse::<u32>().ok())
187 .and_then(|pid| sys.process(sysinfo::Pid::from_u32(pid)))
188 .is_some_and(|p| is_srv(&p.name().to_string_lossy()));
189 if !alive {
190 let _ = std::fs::remove_file(&path);
191 }
192 }
193 }
194 for (pid, process) in sys.processes() {
195 let name = process.name().to_string_lossy().to_string();
196 if !is_srv(&name) || process.cmd().iter().any(|a| a.to_string_lossy() == "--crash-monitor") {
197 continue;
198 }
199 let file = dir.join(format!("{}.json", pid.as_u32()));
200 let ok = std::fs::read(&file).ok().is_some_and(|b| reads_frames(&b, process.start_time()));
201 if !ok && !keeps_its_own_store(pid.as_u32(), store_dir) {
202 return Some(blocker_sentence(&name, pid.as_u32(), process.start_time(), process.exe()));
203 }
204 }
205 None
206}
207
208fn blocker_sentence(name: &str, pid: u32, started_s: u64, exe: Option<&Path>) -> String {
211 let since = chrono::DateTime::from_timestamp(started_s as i64, 0).map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string());
212 let mut facts = vec![format!("pid {pid}")];
213 if let Some(since) = since.filter(|_| started_s > 0) {
214 facts.push(format!("running since {since}"));
215 }
216 if let Some(exe) = exe {
217 facts.push(exe.display().to_string());
218 }
219 format!("{name} ({}) can't read compressed history; compression waits until it exits", facts.join(", "))
220}
221
222fn store_dir_named_by(env: &[std::ffi::OsString]) -> Option<PathBuf> {
227 let var = |key: &str| {
228 env.iter().find_map(|kv| {
229 let kv = kv.to_string_lossy();
230 let (k, v) = kv.split_once('=')?;
231 (k.eq_ignore_ascii_case(key) && !v.is_empty()).then(|| PathBuf::from(v))
232 })
233 };
234 let shared = match var("AGENTMUX_HOME_OVERRIDE") {
235 Some(home) => home.join("shared"),
236 None => var("AGENTMUX_SHARED_DIR")?,
237 };
238 Some(shared.join("agents").join("transcripts"))
239}
240
241fn same_folder(a: &Path, b: &Path) -> bool {
244 let norm = |p: &Path| {
245 let p = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
246 let s = p.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
247 let s = s.trim_start_matches("//?/").trim_end_matches('/').to_string();
248 if cfg!(any(windows, target_os = "macos")) { s.to_lowercase() } else { s }
249 };
250 norm(a) == norm(b)
251}
252
253fn keeps_its_own_store(pid: u32, store_dir: &Path) -> bool {
257 let id = sysinfo::Pid::from_u32(pid);
258 let mut sys = sysinfo::System::new();
259 sys.refresh_processes_specifics(
260 sysinfo::ProcessesToUpdate::Some(&[id]),
261 true,
262 sysinfo::ProcessRefreshKind::nothing().with_environ(sysinfo::UpdateKind::Always),
263 );
264 let Some(theirs) = sys.process(id).and_then(|p| store_dir_named_by(p.environ())) else { return false };
265 !same_folder(&theirs, store_dir)
266}
267
268fn reads_frames(file: &[u8], started_s: u64) -> bool {
271 serde_json::from_slice::<serde_json::Value>(file).ok().is_some_and(|v| {
272 let started = v.get("started_s").and_then(|s| s.as_u64()).unwrap_or(0);
273 let codecs: Vec<i64> = v.get("codecs").and_then(|c| c.as_array()).map(|a| a.iter().filter_map(|x| x.as_i64()).collect()).unwrap_or_default();
274 started.abs_diff(started_s) <= 1 && WRITES_CODECS.iter().all(|c| codecs.contains(c))
275 })
276}
277
278#[derive(Debug, Default, Clone, PartialEq, Eq)]
280pub struct PassReport {
281 pub frames: usize,
282 pub codec2: usize,
283 pub raw_bytes: u64,
284 pub stored_bytes: u64,
285 pub skipped: usize,
286 pub waiting: Option<String>,
288 pub done: bool,
290 pub busy: bool,
293}
294
295fn received_ms(store: &FileStore, zone: &str, offset: i64) -> Option<i64> {
298 let size = store.stat(zone, TSIDX).ok()??.size;
299 let read = |off: i64, len: i64| store.read_snapshot(|r| r.bytes(zone, TSIDX, off, len));
300 let stamps = crate::backend::blockcontroller::shell::stamps::stamps_for(&read, size, &[offset as u64]).ok()??;
301 stamps.first().copied().filter(|&ms| ms > 0)
302}
303
304pub fn pass(store: &FileStore, store_dir: &Path, budget: usize, skip: &mut HashSet<(String, i32)>, now_ms: i64) -> Result<PassReport, StoreError> {
308 pass_with(store, &|| who_blocks(store_dir), budget, skip, now_ms)
309}
310
311fn pass_with(
314 store: &FileStore,
315 blocks: &dyn Fn() -> Option<String>,
316 budget: usize,
317 skip: &mut HashSet<(String, i32)>,
318 now_ms: i64,
319) -> Result<PassReport, StoreError> {
320 let mut report = PassReport::default();
321 match pass_into(store, blocks, budget, skip, now_ms, &mut report) {
322 Ok(()) => Ok(report),
323 Err(e) if is_busy(&e) => {
327 tracing::debug!(error = %e, frames = report.frames, "framer: the store is busy; the next pass carries on");
328 report.busy = true;
329 report.done = false;
330 Ok(report)
331 }
332 Err(e) => Err(e),
333 }
334}
335
336pub fn note_pass_failed(e: &StoreError) {
340 note_pass_failed_in(damage::FRAMES_ZONE, e);
341}
342
343fn note_pass_failed_in(zone: &str, e: &StoreError) {
344 if !damage::note_corrupt(zone, "framer", e) {
345 tracing::warn!(error = %e, "framer: pass failed");
346 }
347}
348
349fn is_busy(e: &StoreError) -> bool {
351 matches!(
352 e,
353 StoreError::Sqlite(rusqlite::Error::SqliteFailure(f, _))
354 if matches!(f.code, rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked)
355 )
356}
357
358fn groups_behind(size: i64) -> i64 {
360 ((size - TAIL_BYTES).max(0) / PART_BYTES) / FRAME_PARTS as i64
361}
362
363fn crosses_the_boundary(zone: &str, name: &str, old: i64, new: i64) -> bool {
366 (zone.starts_with("agent:") || zone.starts_with("agent-uid:")) && kind_of(name).is_some() && groups_behind(new) > groups_behind(old)
367}
368
369static WAKE: tokio::sync::Notify = tokio::sync::Notify::const_new();
370
371pub fn appended(zone: &str, name: &str, old_size: i64, new_size: i64) {
375 if crosses_the_boundary(zone, name, old_size, new_size) {
376 WAKE.notify_one();
377 }
378}
379
380pub async fn woken() {
382 WAKE.notified().await;
383}
384
385#[derive(Clone, Copy)]
387enum Kind {
388 Output,
390 Sidecar,
392 Final,
394}
395
396fn kind_of(name: &str) -> Option<Kind> {
398 match name {
399 OUTPUT => Some(Kind::Output),
400 "output.tsidx" | "output.idx" | "output.consol" | "continuity.state.jsonl" => Some(Kind::Sidecar),
401 "output.provider" => Some(Kind::Final),
402 _ if name.starts_with("import/") => Some(Kind::Final),
403 _ => None,
404 }
405}
406
407fn zone_is_quiet(store: &FileStore, zone: &str, now_ms: i64) -> bool {
410 let Ok(Some(file)) = store.stat(zone, OUTPUT) else { return false };
411 file.size > 0 && received_ms(store, zone, file.size - 1).is_some_and(|ms| now_ms - ms >= QUIET_MS)
412}
413
414fn groups_of(raw: &[i32], step: i32, quiet: bool) -> Vec<(i32, i32)> {
417 let mut out = Vec::new();
418 let mut i = 0;
419 while i < raw.len() {
420 let mut j = i;
421 while j + 1 < raw.len() && raw[j + 1] == raw[j] + 1 && (j + 1 - i) < step as usize {
422 j += 1;
423 }
424 let count = (j - i + 1) as i32;
425 if count == step || quiet {
426 out.push((raw[i], count));
427 }
428 i = j + 1;
429 }
430 out
431}
432
433#[allow(clippy::too_many_arguments)]
435fn frame_file(
436 store: &FileStore,
437 zone: &str,
438 name: &str,
439 size: i64,
440 quiet: bool,
441 codec: i64,
442 skip: &mut HashSet<(String, i32)>,
443 report: &mut PassReport,
444 budget: usize,
445) -> Result<bool, StoreError> {
446 if size <= 0 {
447 return Ok(false);
448 }
449 let last_part = ((size - 1) / PART_BYTES) as i32;
451 let below = if quiet { last_part } else { ((size - TAIL_BYTES).max(0) / PART_BYTES) as i32 };
452 if below <= 0 {
453 return Ok(false);
454 }
455 let raw = store.raw_parts_below(zone, name, below)?;
456 let key_zone = if name == OUTPUT { zone.to_string() } else { format!("{zone}/{name}") };
458 for (first, count) in groups_of(&raw, FRAME_PARTS, quiet) {
459 let key = (key_zone.clone(), first);
460 if skip.contains(&key) {
461 continue;
462 }
463 match store.frame_parts(zone, name, first, count, codec)? {
464 FrameOutcome::Framed { raw, stored, codec } => {
465 report.frames += 1;
466 report.raw_bytes += raw as u64;
467 report.stored_bytes += stored as u64;
468 report.codec2 += usize::from(codec == CODEC_DELTAS || codec == CODEC_DELTA_API);
469 }
470 FrameOutcome::Skipped(why) => {
471 tracing::debug!(zone = %zone, name, first, why, "framer: skipped");
472 report.skipped += 1;
473 skip.insert(key);
474 }
475 }
476 if report.frames >= budget {
477 return Ok(true);
478 }
479 std::thread::sleep(FRAME_PAUSE);
483 }
484 Ok(false)
485}
486
487fn pass_into(
490 store: &FileStore,
491 blocks: &dyn Fn() -> Option<String>,
492 budget: usize,
493 skip: &mut HashSet<(String, i32)>,
494 now_ms: i64,
495 report: &mut PassReport,
496) -> Result<(), StoreError> {
497 if let Some(who) = blocks() {
498 report.waiting = Some(who);
499 return Ok(());
500 }
501 let deltas = deltas_enabled();
508 store.stamp_frames_version(if deltas {
509 crate::backend::storage::filestore::GLOBAL_TRANSCRIPT_STORE_API_DELTAS_VERSION
510 } else {
511 crate::backend::storage::filestore::GLOBAL_TRANSCRIPT_STORE_FRAMES_VERSION
512 })?;
513 if let Some(who) = blocks() {
514 report.waiting = Some(who);
515 return Ok(());
516 }
517 let output_codec = if deltas { CODEC_DELTA_API } else { CODEC_ZSTD };
520 let mut zones = store.zone_ids_with_prefix("agent:")?;
521 zones.extend(store.zone_ids_with_prefix("agent-uid:")?);
522 for zone in zones {
523 let quiet_zone = zone_is_quiet(store, &zone, now_ms);
524 for file in store.list_files(&zone)? {
525 let Some(kind) = kind_of(&file.name) else { continue };
526 let quiet = match kind {
527 Kind::Final => true,
528 Kind::Output | Kind::Sidecar => quiet_zone,
529 };
530 let codec = if matches!(kind, Kind::Output) { output_codec } else { CODEC_ZSTD };
531 if frame_file(store, &zone, &file.name, file.size, quiet, codec, skip, report, budget)? {
532 return Ok(());
533 }
534 }
535 }
536 report.done = true;
537 Ok(())
538}
539
540#[cfg(test)]
541#[path = "framer_tests.rs"]
542mod tests;