agentmux_srv_core/backend/transcript/
live.rs1use std::collections::HashMap;
21use std::sync::{Arc, LazyLock, Mutex};
22
23use super::compact::{recover_live, LiveReply};
24use crate::backend::agent_session::OUTPUT_FILE;
25use crate::backend::storage::error::StoreError;
26use crate::backend::storage::filestore::{FileOpts, FileStore};
27
28pub const LIVE_FILE: &str = "output.live";
30
31const RECOVERY_TAIL_BYTES: i64 = 4 << 20;
33
34#[derive(Default)]
35struct State {
36 reply: LiveReply,
37 looked: bool,
39 held_zone: String,
41 held_shared: Option<Arc<FileStore>>,
42 unshared: Vec<u8>,
45 held_live: Vec<u8>,
48 held_live_own: Option<(Arc<FileStore>, String)>,
50}
51
52const UNSHARED_CAP: usize = 16 << 20;
55
56pub(crate) fn take_unshared(block_id: &str) -> Vec<u8> {
58 let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
59 states.get_mut(block_id).map(|st| std::mem::take(&mut st.unshared)).unwrap_or_default()
60}
61
62pub(crate) fn put_unshared(block_id: &str, shared: &Arc<FileStore>, zone: &str, lines: Vec<u8>) {
64 let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
65 if lines.is_empty() {
66 if let Some(st) = states.get_mut(block_id) {
67 st.unshared = Vec::new();
68 }
69 } else if lines.len() > UNSHARED_CAP {
70 tracing::warn!(block = %block_id, bytes = lines.len(), "transcript: too much is held only in the block's own copy to send it from memory");
71 } else {
72 let st = states.entry(block_id.to_string()).or_default();
73 st.held_zone = zone.to_string();
74 st.held_shared = Some(shared.clone());
75 st.unshared = lines;
76 }
77}
78
79fn take_held_live(block_id: &str) -> (Vec<u8>, Option<(Arc<FileStore>, String)>) {
81 let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
82 states.get_mut(block_id).map_or_else(Default::default, |st| (std::mem::take(&mut st.held_live), st.held_live_own.take()))
83}
84
85fn put_held_live(block_id: &str, shared: &Arc<FileStore>, zone: &str, held: Vec<u8>, own: Option<(Arc<FileStore>, String)>) {
86 let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
87 if held.is_empty() {
88 if let Some(st) = states.get_mut(block_id) {
89 st.held_live = Vec::new();
90 st.held_live_own = None;
91 }
92 } else if held.len() > UNSHARED_CAP {
93 tracing::warn!(block = %block_id, bytes = held.len(), "transcript live file: too much is held only in the block's own copy to send it from memory");
94 } else {
95 let st = states.entry(block_id.to_string()).or_default();
96 st.held_zone = zone.to_string();
97 st.held_shared = Some(shared.clone());
98 st.held_live = held;
99 st.held_live_own = own.or(st.held_live_own.take());
100 }
101}
102
103pub(crate) fn clear_held_live(block_id: &str) {
105 let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
106 if let Some(st) = states.get_mut(block_id) {
107 st.held_live = Vec::new();
108 st.held_live_own = None;
109 }
110}
111
112fn release_held(fs: &FileStore, zone: &str) -> Vec<u8> {
118 let drained: Vec<(Vec<u8>, Vec<u8>, Option<(Arc<FileStore>, String)>)> = {
119 let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
120 states
121 .values_mut()
122 .filter(|st| st.held_zone == zone && st.held_shared.as_ref().is_some_and(|held_in| std::ptr::eq(Arc::as_ptr(held_in), fs)))
123 .map(|st| (std::mem::take(&mut st.unshared), std::mem::take(&mut st.held_live), st.held_live_own.take()))
124 .collect()
125 };
126 let mut fragments = Vec::new();
127 for (lines, held, own) in drained {
128 if !lines.is_empty() {
129 if let Err(e) = fs.append_data(zone, OUTPUT_FILE, &lines) {
130 tracing::warn!(zone = %zone, error = %e, "transcript: lines held for the zone could not be added before its archive");
131 }
132 }
133 fragments.extend_from_slice(&held);
134 if let Some((own_fs, own_zone)) = own {
135 let _ = own_fs.delete_file(&own_zone, LIVE_FILE);
136 }
137 }
138 fragments
139}
140
141static STATES: LazyLock<Mutex<HashMap<String, State>>> = LazyLock::new(Default::default);
142
143pub(crate) enum Run {
145 Fragments(Vec<u8>),
147 Lines(Vec<u8>),
149 ClearLive,
151}
152
153fn push(runs: &mut Vec<Run>, fragment: bool, line: &[u8]) {
154 match runs.last_mut() {
155 Some(Run::Fragments(b)) if fragment => {
156 b.extend_from_slice(line);
157 b.push(b'\n');
158 }
159 Some(Run::Lines(b)) if !fragment => {
160 b.extend_from_slice(line);
161 b.push(b'\n');
162 }
163 _ => {
164 let mut b = line.to_vec();
165 b.push(b'\n');
166 runs.push(if fragment { Run::Fragments(b) } else { Run::Lines(b) });
167 }
168 }
169}
170
171pub(crate) fn plan(block_id: &str, records: &[u8]) -> Vec<Run> {
174 let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
175 let st = states.entry(block_id.to_string()).or_default();
176 let mut runs = Vec::new();
177 for line in records.split(|b| *b == b'\n').filter(|l| !l.is_empty()) {
178 let Ok(text) = std::str::from_utf8(line) else {
179 push(&mut runs, false, line);
180 continue;
181 };
182 let before = st.reply.before(text);
183 for e in &before.emits {
184 push(&mut runs, false, e.line().as_bytes());
185 }
186 push(&mut runs, before.fragment, line);
187 if before.ended {
188 runs.push(Run::ClearLive);
189 } else if st.reply.holds_fragments() && st.reply.settled() {
190 st.reply.reset();
191 runs.push(Run::ClearLive);
192 }
193 }
194 runs
195}
196
197#[cfg(test)]
199pub(crate) fn forget(block_id: &str) {
200 STATES.lock().unwrap_or_else(|e| e.into_inner()).remove(block_id);
201}
202
203pub(crate) fn targets(
207 block_id: &str,
208 filestore: Option<&Arc<FileStore>>,
209 global: Option<(&Arc<FileStore>, &str)>,
210) -> Vec<(Arc<FileStore>, String)> {
211 let mut out = Vec::new();
212 if let Some((gfs, zone)) = global {
213 out.push((gfs.clone(), zone.to_string()));
214 }
215 if let Some(fs) = filestore {
216 out.push((fs.clone(), block_id.to_string()));
217 }
218 out
219}
220
221fn append_live(fs: &FileStore, zone: &str, bytes: &[u8]) -> Result<(), StoreError> {
223 let put = || fs.append_data(zone, LIVE_FILE, bytes);
224 match put() {
225 Err(StoreError::NotFound) => match fs.make_file(zone, LIVE_FILE, HashMap::new(), FileOpts::default()) {
226 Ok(()) | Err(StoreError::AlreadyExists) => put().map(|_| ()),
227 Err(e) => Err(e),
228 },
229 other => other.map(|_| ()),
230 }
231}
232
233pub(crate) fn append_fragments(block_id: &str, targets: &[(Arc<FileStore>, String)], bytes: &[u8], single_copy: bool) {
239 if !single_copy {
240 for (fs, zone) in targets {
241 if let Err(e) = append_live(fs, zone, bytes) {
242 tracing::warn!(zone = %zone, error = %e, "transcript live file: append failed");
243 }
244 }
245 return;
246 }
247 let Some((shared_fs, shared_zone)) = targets.first() else { return };
248 let (mut held, held_own) = take_held_live(block_id);
249 let mut shared_took = true;
250 if !held.is_empty() {
251 shared_took = append_live(shared_fs, shared_zone, &held).is_ok();
252 if shared_took {
253 held.clear();
254 if let Some((own_fs, own_zone)) = held_own.as_ref() {
255 let _ = own_fs.delete_file(own_zone, LIVE_FILE);
256 }
257 }
258 }
259 if shared_took {
260 shared_took = match append_live(shared_fs, shared_zone, bytes) {
261 Ok(()) => true,
262 Err(e) => {
263 tracing::warn!(zone = %shared_zone, error = %e, "transcript live file: append failed");
264 false
265 }
266 };
267 }
268 let mut own = held_own.filter(|_| !held.is_empty());
269 if !shared_took {
270 held.extend_from_slice(bytes);
271 if let Some((fs, zone)) = targets.get(1) {
272 if let Err(e) = append_live(fs, zone, bytes) {
273 tracing::warn!(zone = %zone, error = %e, "transcript live file: the fallback append failed");
274 }
275 own = Some((fs.clone(), zone.clone()));
276 }
277 }
278 put_held_live(block_id, shared_fs, shared_zone, held, own);
279}
280
281pub(crate) fn clear(targets: &[(Arc<FileStore>, String)]) {
283 for (fs, zone) in targets {
284 match fs.delete_file(zone, LIVE_FILE) {
285 Ok(()) | Err(StoreError::NotFound) => {}
286 Err(e) => tracing::warn!(zone = %zone, error = %e, "transcript live file: clearing failed"),
287 }
288 }
289}
290
291fn lines_of(bytes: &[u8], cut_head: bool) -> Vec<String> {
293 let text = String::from_utf8_lossy(bytes);
294 let mut it = text.split('\n');
295 if cut_head {
296 it.next();
297 }
298 it.filter(|l| !l.is_empty()).map(str::to_string).collect()
299}
300
301fn leftovers_of(fs: &FileStore, zone: &str, extra: &[u8]) -> Option<Vec<u8>> {
304 let mut live = fs.read_file(zone, LIVE_FILE).ok().flatten().unwrap_or_default();
305 if !live.is_empty() && !live.ends_with(b"\n") && !extra.is_empty() {
306 live.push(b'\n');
307 }
308 live.extend_from_slice(extra);
309 if live.is_empty() {
310 return None;
311 }
312 let size = fs.stat(zone, OUTPUT_FILE).ok().flatten().map_or(0, |f| f.size);
313 let start = (size - RECOVERY_TAIL_BYTES).max(0);
314 let tail = if size > start { fs.read_bytes_db(zone, OUTPUT_FILE, start, size - start).unwrap_or_default() } else { Vec::new() };
315 let emits = recover_live(&lines_of(&tail, start > 0), &lines_of(&live, false));
316 let mut out = Vec::new();
317 for e in emits {
318 out.extend_from_slice(e.line().as_bytes());
319 out.push(b'\n');
320 }
321 Some(out)
322}
323
324pub(crate) fn settle(fs: &FileStore, zone: &str) -> bool {
329 let held = release_held(fs, zone);
330 let Some(left) = leftovers_of(fs, zone, &held) else { return true };
331 if !left.is_empty() {
332 if let Err(e) = fs.append_data(zone, OUTPUT_FILE, &left) {
333 tracing::warn!(zone = %zone, error = %e, "transcript live file: settling before archive failed");
334 return false;
335 }
336 }
337 match fs.delete_file(zone, LIVE_FILE) {
338 Ok(()) | Err(StoreError::NotFound) => true,
339 Err(e) => {
340 tracing::warn!(zone = %zone, error = %e, "transcript live file: clearing failed");
341 false
342 }
343 }
344}
345
346pub(crate) fn recover_once(block_id: &str, targets: &[(Arc<FileStore>, String)], single_copy: bool) -> Option<Vec<u8>> {
353 {
354 let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
355 let st = states.entry(block_id.to_string()).or_default();
356 if std::mem::replace(&mut st.looked, true) {
357 return None;
358 }
359 }
360 let (fs, zone) = targets.first()?;
361 let holds = fs.stat(zone, OUTPUT_FILE).ok().flatten().is_some_and(|f| f.size > 0);
362 let found = if single_copy {
363 let own_live = if holds && targets.len() > 1 {
370 targets[1..].iter().find_map(|(own_fs, own_zone)| own_fs.read_file(own_zone, LIVE_FILE).ok().flatten().filter(|b| !b.is_empty()))
371 } else {
372 None
373 };
374 let shared_live = fs.read_file(zone, LIVE_FILE).ok().flatten().unwrap_or_default();
375 let extra = own_live.filter(|own| !shared_live.ends_with(own)).unwrap_or_default();
376 leftovers_of(fs, zone, &extra)
377 } else {
378 leftovers_of(fs, zone, &[]).or_else(|| {
381 if holds { targets[1..].iter().find_map(|(own_fs, own_zone)| leftovers_of(own_fs, own_zone, &[])) } else { None }
382 })
383 };
384 clear(targets);
385 clear_held_live(block_id);
386 found
387}
388
389#[cfg(test)]
390#[path = "live_tests.rs"]
391mod tests;