Skip to main content

agentmux_srv_core/backend/transcript/
copies.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The per-channel copy of an agent's conversation, and its removal (check L5 of
5//! `SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 9).
6//!
7//! Before new data was written once, to the agent's zone in the shared store, every line was also
8//! written to `output` in the zone of the block that ran it, in this channel's own store. Those
9//! copies are the second full copy of a conversation. A copy goes only when **every kept line of it
10//! is in the shared store**: its lines in the compact form (minus the blank ones and the fragments the
11//! reduce pass proves redundant; a cut-off reply as its interrupted line), compared by hash, as a multiset, with the lines of the agent's current
12//! conversation and its archives. A line the store lacks is put there first: in the agent's current
13//! zone when that is empty (the copy was the conversation), otherwise in a new archive zone of its
14//! own, so nothing is inserted into the middle of a conversation another srv may be appending to.
15//!
16//! Nothing is edited in place and nothing is deleted before the check: the copy is read in
17//! snapshots, and the deletion runs under the block's transcript lock and only if the file is still
18//! the one that was read (size, generation, time).
19
20use 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
31/// How much of a file one snapshot reads.
32const CHUNK: i64 = 4 << 20;
33/// The most a pass holds in memory to put in the store.
34const MAX_MISSING_BYTES: usize = 256 << 20;
35/// The files a copy leaves in its block's zone.
36const COPY_FILES: [&str; 3] = [OUTPUT_FILE, TSIDX_FILE, "output.idx"];
37/// The reply in progress of a copy: a block that still has one is not touched.
38const LIVE_FILE: &str = "output.live";
39
40#[derive(Debug, Clone, Copy)]
41pub struct Options {
42    /// Read and check; write and delete nothing.
43    pub dry_run: bool,
44    /// A copy written to within this many ms may still be growing: it is left for a later pass.
45    pub quiet_ms: i64,
46    /// Rest between two blocks.
47    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/// Where the lines the store lacked went.
57#[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    /// The block has no copy (none, or an empty file: the leftovers are removed).
67    Nothing,
68    /// Every kept line is in the store; the copy is gone.
69    Deleted,
70    /// A dry run: the copy was checked, nothing was written.
71    DryRun,
72    /// Written to lately: left for a later pass.
73    Recent,
74    /// The block still holds a reply in progress.
75    LiveFile,
76    /// The agent's shared zone is marked damaged: the copy is the one that can restore it.
77    Damaged,
78    /// The copy or the store changed while it was read: left for a later pass.
79    Changed,
80    /// Too many missing lines to hold in memory, or the store refused them: the copy is left as it is.
81    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    /// Kept lines of the copy.
91    pub kept: usize,
92    /// Of those, lines the store lacked.
93    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/// A file as one snapshot saw it: what a later read must still find.
104#[derive(Debug, Clone, PartialEq, Eq)]
105struct Seen {
106    size: i64,
107    modts: i64,
108    gen: Option<String>,
109}
110
111/// A read that did not complete.
112#[derive(Debug)]
113enum Fail {
114    /// The file is not the one that was first read (written to, swapped, deleted).
115    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
130/// `[pos, pos + len)` of a file, only if it is still the file that was seen.
131fn 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
153/// Calls `on_line` with each line of the file (without its newline), in order, and returns what the
154/// file was when the read began; `None` for no file. The read is of one file: a write that grows it
155/// is not seen, a swap or a delete is [`Fail::Changed`].
156fn 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
160/// [`stream_lines`] with each line's byte offset in the file.
161fn 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
182/// The kept lines of a copy, by hash: how many of each.
183struct Kept {
184    counts: HashMap<u128, usize>,
185    lines: usize,
186}
187
188/// How much of a copy is planned at once: a window ends at the first turn boundary after this.
189const WINDOW_BYTES: usize = 8 << 20;
190
191/// Calls `on_line` with each line of the copy in the compact form, in order: the lines the reduce pass
192/// would write for it, which are its lines without the blank ones and without the fragments of a message
193/// that has a complete line, with a reply that was cut off as the interrupted line it reassembles to.
194/// A fragment that cannot be proven redundant stays, as it does in the pass, so what only the copy holds
195/// is never taken for redundant. Each call has where the line is in the copy: a kept line at its own offset, a
196/// reply that was cut off at its last fragment's.
197fn 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    // The window's lines, and where each one is in the copy.
200    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
234/// The zones of an agent's conversation in the store: the current one and every archive.
235fn 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
248/// Takes from `counts` the lines of the agent's conversation in the store; what is left is what the
249/// store lacks.
250fn 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/// Lines of the copy to put in the store, as they will be written (through the rule of a live write: a value
265/// srv withholds is not written), and where each is: its offset in what is written and in the copy.
266#[derive(Default)]
267struct Recovered {
268    bytes: Vec<u8>,
269    at: Vec<(u64, u64)>,
270    /// The session id each line carries, if it does.
271    own: Vec<Option<String>>,
272    /// The session each line belongs to in the copy: its own, or for a line that carries none (a message a person
273    /// typed, echoed by AgentMux) that of the next line with one, else the last before it.
274    owner: Vec<Option<String>>,
275}
276
277/// The kept lines of the copy that `lacking` counts, in the copy's order, one line each.
278fn 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    // Missing lines with no session of their own, waiting for the next line that has one; and the last that did.
282    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    /// Whether the record reader, given only these lines, gives every line the session it belongs to: a line
309    /// with no session id of its own goes to the next line that has one, and past the last to the last.
310    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    /// One part per session the lines belong to, each in the copy's order, with its lines' places in it.
326    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
348/// The times the copy received the recovered lines at, as the records of the placed file's `output.tsidx`
349/// (`(offset in the placed lines, ms)`), one where the time changes. Nothing when the copy has no times.
350fn 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
372/// The records of an `output.tsidx` for `(offset, ms)` times: a line each.
373fn 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
377/// Puts the lines the store lacked in it, with the times they were received at. In the agent's current zone
378/// when the agent has no conversation in the store (decided in the transaction that writes), otherwise in a new
379/// archive zone, one for each session the lines belong to when the record reader could not tell them apart. The
380/// lines are read back before this answers.
381fn 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, &times)?.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
399/// Some of the recovered lines in an archive zone of their own, which names `owner` as the session of the
400/// lines that carry none.
401fn 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
412/// What a block's copy leaves to look at before it is read: the outcome when it is not to be checked
413/// now.
414fn 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
428/// What one pass works with.
429pub 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    /// Deletes the copy, if it is still what was read. Under the block's transcript lock, which every
438    /// write of its transcript holds.
439    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            // Nothing is announced: a pane reads the agent's zone first (`TranscriptSource`), and what it
445            // follows of the copy's stream stops growing as it did when single-copy writing began.
446            self.own.delete_files(block, &COPY_FILES).map_err(|e| format!("delete: {e}"))?;
447            Ok(true)
448        })
449    }
450
451    /// The sidecars of a copy that is not there. Under the block's transcript lock, looking again that
452    /// there is still no `output`: a write that fell back to the block's copy may have made it since.
453    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, &COPY_FILES).map_err(|e| format!("delete: {e}"))?;
457            }
458            Ok::<(), String>(())
459        })?;
460        Ok(())
461    }
462
463    /// Checks one block's copy against the store, puts what the store lacks in it, and deletes the copy.
464    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/// Counts of one pass over a channel's copies. No names, no content.
507#[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
543/// The defined agents' blocks of this channel: `(block id, agent definition id)`. A quick-launch pane
544/// (its `agentId` is a provider key, and its zone is shared) is not one: its own copy is its record.
545fn 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
557/// One pass over this channel's copies of defined agents' conversations. `None` when there is no shared
558/// store, or it is this channel's own store: then the copy is the only one.
559pub 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
588/// A copy was deleted and its log not yet scrubbed: set by the deletion, cleared once the log is overwritten.
589static LOG_TO_SCRUB: AtomicBool = AtomicBool::new(false);
590
591/// The deleted rows are not recoverable from the store's write-ahead log: it is overwritten in place
592/// (`FileStore::scrub_wal`). It does not run while another srv has the store open, and then it is tried
593/// again by the next pass, which has nothing left to delete.
594fn 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;