1use std::collections::HashMap;
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::Arc;
23use std::time::Duration;
24
25use sha2::{Digest, Sha256};
26
27use crate::backend::agent_session::{agent_current_zone, is_valid_definition_id, OUTPUT_FILE, TSIDX_FILE};
28use crate::backend::storage::filestore::FileStore;
29use crate::backend::storage::store::Store;
30
31const CHUNK: i64 = 4 << 20;
33const MAX_MISSING_BYTES: usize = 256 << 20;
35const COPY_FILES: [&str; 3] = [OUTPUT_FILE, TSIDX_FILE, "output.idx"];
37const LIVE_FILE: &str = "output.live";
39
40#[derive(Debug, Clone, Copy)]
41pub struct Options {
42 pub dry_run: bool,
44 pub quiet_ms: i64,
46 pub pause: Duration,
48}
49
50impl Default for Options {
51 fn default() -> Self {
52 Self { dry_run: false, quiet_ms: 10 * 60 * 1000, pause: Duration::from_millis(50) }
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Placed {
59 No,
60 Current,
61 Recovered,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum Outcome {
66 Nothing,
68 Deleted,
70 DryRun,
72 Recent,
74 LiveFile,
76 Damaged,
78 Changed,
80 Failed(String),
82 Stopped,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Report {
87 pub block: String,
88 pub outcome: Outcome,
89 pub bytes: i64,
90 pub kept: usize,
92 pub missing: usize,
94 pub placed: Placed,
95}
96
97impl Report {
98 fn new(block: &str, outcome: Outcome) -> Self {
99 Self { block: block.to_string(), outcome, bytes: 0, kept: 0, missing: 0, placed: Placed::No }
100 }
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105struct Seen {
106 size: i64,
107 modts: i64,
108 gen: Option<String>,
109}
110
111#[derive(Debug)]
113enum Fail {
114 Changed,
116 Store(String),
117}
118
119impl From<String> for Fail {
120 fn from(e: String) -> Self {
121 Fail::Store(e)
122 }
123}
124
125fn seen(fs: &FileStore, zone: &str, name: &str) -> Result<Option<Seen>, String> {
126 let file = fs.read_snapshot(|s| s.file(zone, name)).map_err(|e| format!("read: {e}"))?;
127 Ok(file.map(|f| Seen { size: f.size, modts: f.modts, gen: f.gen }))
128}
129
130fn read_chunk(fs: &FileStore, zone: &str, name: &str, was: &Seen, pos: i64, len: i64) -> Result<Vec<u8>, Fail> {
132 let got = fs
133 .read_snapshot(|s| {
134 let Some(file) = s.file(zone, name)? else { return Ok(None) };
135 if file.gen != was.gen || file.size < pos + len {
136 return Ok(None);
137 }
138 s.bytes(zone, name, pos, len)
139 })
140 .map_err(|e| Fail::Store(format!("read: {e}")))?;
141 got.ok_or(Fail::Changed)
142}
143
144fn is_blank(line: &[u8]) -> bool {
145 line.iter().all(u8::is_ascii_whitespace)
146}
147
148fn key(line: &[u8]) -> u128 {
149 let digest = Sha256::digest(line);
150 u128::from_be_bytes(digest[..16].try_into().expect("16 bytes"))
151}
152
153fn stream_lines(fs: &FileStore, zone: &str, name: &str, on_line: &mut dyn FnMut(&[u8])) -> Result<Option<Seen>, Fail> {
157 stream_lines_at(fs, zone, name, &mut |_, line| on_line(line))
158}
159
160fn stream_lines_at(fs: &FileStore, zone: &str, name: &str, on_line: &mut dyn FnMut(u64, &[u8])) -> Result<Option<Seen>, Fail> {
162 let Some(was) = seen(fs, zone, name)? else { return Ok(None) };
163 let (mut pos, mut carry, mut carry_at) = (0, Vec::new(), 0u64);
164 while pos < was.size {
165 let len = CHUNK.min(was.size - pos);
166 carry.extend_from_slice(&read_chunk(fs, zone, name, &was, pos, len)?);
167 pos += len;
168 let whole = carry.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1);
169 let mut at = carry_at;
170 carry.drain(..whole).as_slice().split(|b| *b == b'\n').for_each(|l| {
171 on_line(at, l);
172 at += l.len() as u64 + 1;
173 });
174 carry_at += whole as u64;
175 }
176 if !carry.is_empty() {
177 on_line(carry_at, &carry);
178 }
179 Ok(Some(was))
180}
181
182struct Kept {
184 counts: HashMap<u128, usize>,
185 lines: usize,
186}
187
188const WINDOW_BYTES: usize = 8 << 20;
190
191fn reduced_lines(fs: &FileStore, block: &str, on_line: &mut dyn FnMut(u64, &[u8])) -> Result<Seen, Fail> {
198 use super::compact::{compact_lines, is_turn_boundary, WindowEnd};
199 let (mut window, mut at, mut bytes): (Vec<String>, Vec<u64>, usize) = (Vec::new(), Vec::new(), 0);
201 let plan = |window: &mut Vec<String>, at: &mut Vec<u64>, end: WindowEnd, on_line: &mut dyn FnMut(u64, &[u8])| {
202 let (lines, plan) = compact_lines(window, end);
203 lines.iter().zip(plan.sources()).for_each(|(l, from)| on_line(at[from], l.as_bytes()));
204 window.clear();
205 at.clear();
206 };
207 let was = stream_lines_at(fs, block, OUTPUT_FILE, &mut |off, line| {
208 if is_blank(line) {
209 return;
210 }
211 let Ok(text) = std::str::from_utf8(line) else { return on_line(off, line) };
212 bytes += line.len();
213 window.push(text.to_string());
214 at.push(off);
215 if bytes >= WINDOW_BYTES && is_turn_boundary(text) {
216 plan(&mut window, &mut at, WindowEnd::Open, on_line);
217 bytes = 0;
218 }
219 })?
220 .ok_or(Fail::Changed)?;
221 plan(&mut window, &mut at, WindowEnd::Final, on_line);
222 Ok(was)
223}
224
225fn kept_lines(fs: &FileStore, block: &str) -> Result<(Kept, Seen), Fail> {
226 let mut kept = Kept { counts: HashMap::new(), lines: 0 };
227 let was = reduced_lines(fs, block, &mut |_, line| {
228 *kept.counts.entry(key(line)).or_insert(0) += 1;
229 kept.lines += 1;
230 })?;
231 Ok((kept, was))
232}
233
234fn conversation_zones(global: &FileStore, def: &str) -> Result<Vec<String>, String> {
236 let current = agent_current_zone(def);
237 let archives = format!("agent:{def}:archive:");
238 let mut zones: Vec<String> = global
239 .zone_ids_with_prefix(&format!("agent:{def}:"))
240 .map_err(|e| format!("zones: {e}"))?
241 .into_iter()
242 .filter(|z| *z == current || z.starts_with(&archives))
243 .collect();
244 zones.sort();
245 Ok(zones)
246}
247
248fn take_store_lines(global: &FileStore, def: &str, counts: &mut HashMap<u128, usize>, stop: &AtomicBool) -> Result<(), Fail> {
251 for zone in conversation_zones(global, def)? {
252 if counts.values().all(|n| *n == 0) || stop.load(Ordering::Relaxed) {
253 break;
254 }
255 stream_lines(global, &zone, OUTPUT_FILE, &mut |line| {
256 if let Some(n) = counts.get_mut(&key(line)).filter(|n| **n > 0) {
257 *n -= 1;
258 }
259 })?;
260 }
261 Ok(())
262}
263
264#[derive(Default)]
267struct Recovered {
268 bytes: Vec<u8>,
269 at: Vec<(u64, u64)>,
270 own: Vec<Option<String>>,
272 owner: Vec<Option<String>>,
275}
276
277fn missing_lines(fs: &FileStore, block: &str, mut lacking: HashMap<u128, usize>) -> Result<Recovered, Fail> {
279 use crate::backend::history::record::line_session_id;
280 let mut out = Recovered::default();
281 let (mut waiting, mut last): (Vec<usize>, Option<String>) = (Vec::new(), None);
283 reduced_lines(fs, block, &mut |off, line| {
284 let sid = line_session_id(line);
285 if let Some(n) = lacking.get_mut(&key(line)).filter(|n| **n > 0) {
286 *n -= 1;
287 if out.bytes.len() <= MAX_MISSING_BYTES {
288 if sid.is_none() {
289 waiting.push(out.at.len());
290 }
291 out.at.push((out.bytes.len() as u64, off));
292 out.own.push(sid.clone());
293 out.owner.push(sid.clone());
294 out.bytes.extend_from_slice(super::withhold::text(&String::from_utf8_lossy(line)).as_bytes());
295 out.bytes.push(b'\n');
296 }
297 }
298 if sid.is_some() {
299 waiting.drain(..).for_each(|i| out.owner[i] = sid.clone());
300 last = sid;
301 }
302 })?;
303 waiting.drain(..).for_each(|i| out.owner[i] = last.clone());
304 Ok(out)
305}
306
307impl Recovered {
308 fn reads_as_owned(&self) -> bool {
311 let mut inferred: Vec<Option<&String>> = vec![None; self.own.len()];
312 let mut next: Option<&String> = None;
313 for i in (0..self.own.len()).rev() {
314 next = self.own[i].as_ref().or(next);
315 inferred[i] = next;
316 }
317 let mut before: Option<&String> = None;
318 for i in 0..self.own.len() {
319 before = self.own[i].as_ref().or(before);
320 inferred[i] = inferred[i].or(before);
321 }
322 inferred.iter().zip(&self.owner).all(|(read, owner)| *read == owner.as_ref())
323 }
324
325 fn by_owner(&self) -> Vec<(Option<String>, Recovered)> {
327 let mut parts: Vec<(Option<String>, Recovered)> = Vec::new();
328 for i in 0..self.at.len() {
329 let at = match parts.iter().position(|(owner, _)| *owner == self.owner[i]) {
330 Some(at) => at,
331 None => {
332 parts.push((self.owner[i].clone(), Recovered::default()));
333 parts.len() - 1
334 }
335 };
336 let from = self.at[i].0 as usize;
337 let to = self.at.get(i + 1).map_or(self.bytes.len(), |next| next.0 as usize);
338 let part = &mut parts[at].1;
339 part.at.push((part.bytes.len() as u64, self.at[i].1));
340 part.own.push(self.own[i].clone());
341 part.owner.push(self.owner[i].clone());
342 part.bytes.extend_from_slice(&self.bytes[from..to]);
343 }
344 parts
345 }
346}
347
348fn received_times(own: &FileStore, block: &str, lines: &Recovered) -> Vec<(i64, i64)> {
351 let size = match own.stat(block, TSIDX_FILE) {
352 Ok(Some(f)) if f.size > 0 => f.size,
353 _ => return Vec::new(),
354 };
355 let offsets: Vec<u64> = lines.at.iter().map(|(_, copy)| *copy).collect();
356 if offsets.windows(2).any(|w| w[1] < w[0]) {
357 return Vec::new();
358 }
359 let read = |off: i64, len: i64| own.read_at(block, TSIDX_FILE, off, len).map(|(_, data)| Some(data));
360 let Ok(Some(times)) = crate::backend::blockcontroller::shell::stamps::stamps_for(&read, size, &offsets) else {
361 return Vec::new();
362 };
363 let mut out: Vec<(i64, i64)> = Vec::new();
364 for ((placed, _), ms) in lines.at.iter().zip(times) {
365 if ms > 0 && out.last().map_or(true, |(_, last)| *last != ms) {
366 out.push((*placed as i64, ms));
367 }
368 }
369 out
370}
371
372fn tsidx_records(times: &[(i64, i64)]) -> Vec<u8> {
374 times.iter().map(|(off, ms)| format!("{{\"off\":{off},\"ms\":{ms}}}\n")).collect::<String>().into_bytes()
375}
376
377fn place(own: &FileStore, block: &str, global: &Arc<FileStore>, def: &str, lines: &Recovered) -> Result<Placed, String> {
382 let times = received_times(own, block, lines);
383 if super::append::mirror_seed_with_stamps(global, def, &lines.bytes, ×)?.is_some() {
384 let back = global.read_file(&agent_current_zone(def), OUTPUT_FILE).map_err(|e| format!("read back: {e}"))?.unwrap_or_default();
385 return if back.ends_with(&lines.bytes) { Ok(Placed::Current) } else { Err(NOT_AS_WRITTEN.to_string()) };
386 }
387 if lines.reads_as_owned() {
388 archive_part(own, block, global, def, lines, None)?;
389 } else {
390 for (owner, part) in lines.by_owner() {
391 archive_part(own, block, global, def, &part, owner.as_deref())?;
392 }
393 }
394 Ok(Placed::Recovered)
395}
396
397const NOT_AS_WRITTEN: &str = "the lines are not in the store as written";
398
399fn archive_part(own: &FileStore, block: &str, global: &Arc<FileStore>, def: &str, part: &Recovered, owner: Option<&str>) -> Result<(), String> {
402 let tsidx = tsidx_records(&received_times(own, block, part));
403 let zone = crate::backend::agent_session::archive::archive_lines(global, def, &part.bytes, &tsidx, owner)?;
404 let back = global.read_file(&zone, OUTPUT_FILE).map_err(|e| format!("read back: {e}"))?.unwrap_or_default();
405 if back == part.bytes {
406 Ok(())
407 } else {
408 Err(NOT_AS_WRITTEN.to_string())
409 }
410}
411
412fn skip(own: &FileStore, block: &str, def: &str, opts: &Options, now_ms: i64) -> Result<Option<Outcome>, String> {
415 if super::damage::is_damaged(&agent_current_zone(def)) {
416 return Ok(Some(Outcome::Damaged));
417 }
418 if seen(own, block, LIVE_FILE)?.is_some_and(|f| f.size > 0) {
419 return Ok(Some(Outcome::LiveFile));
420 }
421 let Some(copy) = seen(own, block, OUTPUT_FILE)? else { return Ok(Some(Outcome::Nothing)) };
422 if copy.size > 0 && now_ms - copy.modts < opts.quiet_ms {
423 return Ok(Some(Outcome::Recent));
424 }
425 Ok(None)
426}
427
428pub struct Run<'a> {
430 pub own: &'a FileStore,
431 pub global: &'a Arc<FileStore>,
432 pub opts: Options,
433 pub stop: &'a AtomicBool,
434}
435
436impl Run<'_> {
437 fn delete_if_unchanged(&self, block: &str, was: &Seen) -> Result<bool, String> {
440 super::append::with_transcript_order(block, || {
441 if seen(self.own, block, OUTPUT_FILE)?.as_ref() != Some(was) {
442 return Ok(false);
443 }
444 self.own.delete_files(block, ©_FILES).map_err(|e| format!("delete: {e}"))?;
447 Ok(true)
448 })
449 }
450
451 fn remove_leftovers(&self, block: &str) -> Result<(), Fail> {
454 super::append::with_transcript_order(block, || {
455 if seen(self.own, block, OUTPUT_FILE)?.is_none() {
456 self.own.delete_files(block, ©_FILES).map_err(|e| format!("delete: {e}"))?;
457 }
458 Ok::<(), String>(())
459 })?;
460 Ok(())
461 }
462
463 pub fn reconcile(&self, block: &str, def: &str) -> Report {
465 let mut report = Report::new(block, Outcome::Stopped);
466 report.outcome = match self.check(block, def, &mut report) {
467 Ok(outcome) => outcome,
468 Err(Fail::Changed) => Outcome::Changed,
469 Err(Fail::Store(why)) => Outcome::Failed(why),
470 };
471 report
472 }
473
474 fn check(&self, block: &str, def: &str, report: &mut Report) -> Result<Outcome, Fail> {
475 let now_ms = agentmux_common::time::now_ms();
476 if let Some(early) = skip(self.own, block, def, &self.opts, now_ms)? {
477 if early == Outcome::Nothing && !self.opts.dry_run {
478 self.remove_leftovers(block)?;
479 }
480 return Ok(early);
481 }
482 let (kept, was) = kept_lines(self.own, block)?;
483 report.kept = kept.lines;
484 report.bytes = was.size;
485 let mut lacking = kept.counts;
486 take_store_lines(self.global, def, &mut lacking, self.stop)?;
487 if self.stop.load(Ordering::Relaxed) {
488 return Ok(Outcome::Stopped);
489 }
490 lacking.retain(|_, n| *n > 0);
491 report.missing = lacking.values().sum();
492 if self.opts.dry_run {
493 return Ok(Outcome::DryRun);
494 }
495 if !lacking.is_empty() {
496 let lines = missing_lines(self.own, block, lacking)?;
497 if lines.bytes.len() > MAX_MISSING_BYTES {
498 return Ok(Outcome::Failed("more missing lines than a pass holds".to_string()));
499 }
500 report.placed = place(self.own, block, self.global, def, &lines)?;
501 }
502 Ok(if self.delete_if_unchanged(block, &was)? { Outcome::Deleted } else { Outcome::Changed })
503 }
504}
505
506#[derive(Debug, Clone, Default, PartialEq, Eq)]
508pub struct Summary {
509 pub dry_run: bool,
510 pub blocks: usize,
511 pub deleted: usize,
512 pub checked: usize,
513 pub nothing: usize,
514 pub waiting: usize,
515 pub failed: usize,
516 pub bytes: i64,
517 pub missing_lines: usize,
518 pub placed_current: usize,
519 pub placed_recovered: usize,
520}
521
522pub fn summarize(reports: &[Report], dry_run: bool) -> Summary {
523 let mut s = Summary { dry_run, blocks: reports.len(), ..Summary::default() };
524 for r in reports {
525 match &r.outcome {
526 Outcome::Deleted => s.deleted += 1,
527 Outcome::DryRun => s.checked += 1,
528 Outcome::Nothing => s.nothing += 1,
529 Outcome::Failed(_) => s.failed += 1,
530 _ => s.waiting += 1,
531 }
532 s.bytes += r.bytes;
533 s.missing_lines += r.missing;
534 match r.placed {
535 Placed::Current => s.placed_current += 1,
536 Placed::Recovered => s.placed_recovered += 1,
537 Placed::No => {}
538 }
539 }
540 s
541}
542
543fn agent_blocks(mstore: &Store) -> Result<Vec<(String, String)>, String> {
546 let blocks = mstore.get_all::<crate::backend::obj::Block>().map_err(|e| format!("blocks: {e}"))?;
547 Ok(blocks
548 .into_iter()
549 .filter_map(|b| {
550 let def = crate::backend::obj::meta_get_string(&b.meta, "agentId", "");
551 let ok = is_valid_definition_id(&def) && crate::backend::providers::get_provider(&def).is_none();
552 ok.then_some((b.oid, def))
553 })
554 .collect())
555}
556
557pub fn pass(own: &FileStore, mstore: &Store, opts: &Options, stop: &AtomicBool) -> Option<Vec<Report>> {
560 let global = crate::backend::agent_session::global_transcript_store()?;
561 if std::ptr::eq(own, global.as_ref()) {
562 return None;
563 }
564 let blocks = match agent_blocks(mstore) {
565 Ok(b) => b,
566 Err(e) => {
567 tracing::warn!(error = %e, "history copies: the blocks could not be listed");
568 return None;
569 }
570 };
571 let run = Run { own, global, opts: *opts, stop };
572 let mut reports = Vec::new();
573 for (block, def) in blocks {
574 if stop.load(Ordering::Relaxed) {
575 break;
576 }
577 let report = run.reconcile(&block, &def);
578 if let Outcome::Failed(why) = &report.outcome {
579 tracing::warn!(block = %report.block, why = %why, "history copies: a copy was left as it was");
580 }
581 reports.push(report);
582 std::thread::sleep(opts.pause);
583 }
584 scrub_after_deleting(own, opts, reports.iter().any(|r| r.outcome == Outcome::Deleted));
585 Some(reports)
586}
587
588static LOG_TO_SCRUB: AtomicBool = AtomicBool::new(false);
590
591fn scrub_after_deleting(own: &FileStore, opts: &Options, deleted: bool) {
595 if opts.dry_run {
596 return;
597 }
598 if deleted {
599 LOG_TO_SCRUB.store(true, Ordering::Relaxed);
600 }
601 if !LOG_TO_SCRUB.load(Ordering::Relaxed) {
602 return;
603 }
604 match own.scrub_wal(super::framer::other_srv) {
605 Ok(true) => LOG_TO_SCRUB.store(false, Ordering::Relaxed),
606 Ok(false) => tracing::info!("history copies: the store's log is scrubbed by a later pass"),
607 Err(e) => tracing::warn!(error = %e, "history copies: the store's log could not be scrubbed"),
608 }
609}
610
611#[cfg(test)]
612#[path = "copies_tests.rs"]
613mod tests;