Skip to main content

agentmux_srv_core/backend/transcript/
migrate_run.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! When the compact-form reduce pass runs, and what it tells the log
5//! (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` sections 9 and 15, PR 6).
6//!
7//! The pass is off until the settings say so. `history:compactmigrate` turns it on;
8//! `history:compactmigratedryrun` makes it read, plan and check every zone and write nothing, and
9//! report counts, which is how the first run on a real store is judged before it changes one.
10
11use std::collections::HashMap;
12use std::sync::atomic::AtomicBool;
13
14use super::copies;
15use super::migrate::{migrate_all, Options, Outcome, Report};
16use crate::backend::storage::filestore::FileStore;
17use crate::backend::storage::store::Store;
18
19/// Turns the pass on.
20pub const KEY_MIGRATE: &str = "history:compactmigrate";
21/// Makes the pass read and check only.
22pub const KEY_DRY_RUN: &str = "history:compactmigratedryrun";
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct Policy {
26    pub enabled: bool,
27    pub dry_run: bool,
28}
29
30impl Policy {
31    /// What the settings ask for. A missing or mistyped key is off. A dry run runs on its own, without
32    /// the first setting: it writes nothing.
33    pub fn from_extra(extra: &HashMap<String, serde_json::Value>) -> Self {
34        let on = |k: &str| extra.get(k).and_then(|v| v.as_bool()).unwrap_or(false);
35        let dry_run = on(KEY_DRY_RUN);
36        Self { enabled: on(KEY_MIGRATE) || dry_run, dry_run }
37    }
38}
39
40/// Counts of one pass over the store. No names, no content.
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
42pub struct Summary {
43    pub dry_run: bool,
44    pub zones: usize,
45    pub swapped: usize,
46    pub already_compact: usize,
47    pub dry_ran: usize,
48    pub empty: usize,
49    pub stale: usize,
50    pub busy: usize,
51    pub failed: usize,
52    pub stopped: usize,
53    pub bytes_before: i64,
54    pub bytes_after: i64,
55    pub dropped_fragments: usize,
56    pub interrupted_lines: usize,
57    pub unproven_fragments: usize,
58    /// The same fragments by why their message could not be proven.
59    pub unproven_causes: std::collections::BTreeMap<&'static str, usize>,
60    /// The event and delta kinds the reduce does not reassemble, by name, each with the messages that named it. Protocol names only.
61    pub unknown_kinds: std::collections::BTreeMap<String, usize>,
62    /// The zones that still hold fragments that could not be proven (at most 10): what keeps a zone from being compact.
63    pub unsettled_zones: Vec<String>,
64    /// The zones this pass swapped (at most 10). A zone swapped in every pass has an end the next pass does not count as compact.
65    pub swapped_zones: Vec<String>,
66}
67
68/// The counts of a pass, from its reports.
69pub fn summarize(reports: &[Report], dry_run: bool) -> Summary {
70    let mut s = Summary { dry_run, zones: reports.len(), ..Summary::default() };
71    for r in reports {
72        match r.outcome {
73            Outcome::Swapped { .. } => s.swapped += 1,
74            Outcome::AlreadyCompact => s.already_compact += 1,
75            Outcome::DryRun => s.dry_ran += 1,
76            Outcome::Empty => s.empty += 1,
77            Outcome::Stale => s.stale += 1,
78            Outcome::Busy => s.busy += 1,
79            Outcome::Failed(_) => s.failed += 1,
80            Outcome::Stopped => s.stopped += 1,
81        }
82        s.bytes_before += r.bytes_before;
83        s.bytes_after += r.bytes_after;
84        s.dropped_fragments += r.stats.dropped_fragments;
85        s.interrupted_lines += r.stats.interrupted_lines;
86        s.unproven_fragments += r.stats.unproven_fragments;
87        for (why, n) in &r.stats.unproven_by_cause {
88            *s.unproven_causes.entry(why).or_default() += n;
89        }
90        for (kind, n) in &r.stats.unknown_kinds {
91            if s.unknown_kinds.len() < 32 || s.unknown_kinds.contains_key(kind) {
92                *s.unknown_kinds.entry(kind.clone()).or_default() += n;
93            }
94        }
95        if r.stats.unproven_fragments > 0 && s.unsettled_zones.len() < 10 {
96            s.unsettled_zones.push(r.zone.clone());
97        }
98        if matches!(r.outcome, Outcome::Swapped { .. }) && s.swapped_zones.len() < 10 {
99            s.swapped_zones.push(r.zone.clone());
100        }
101    }
102    s
103}
104
105/// One pass over the shared transcript store's agent zones, when the settings ask for it. `None`
106/// when the pass is off or the store is not open. Blocking: run it on a blocking thread.
107pub fn pass_global(policy: &Policy, stop: &AtomicBool) -> Option<Summary> {
108    if !policy.enabled {
109        return None;
110    }
111    let global = crate::backend::agent_session::global_transcript_store()?;
112    let opts = Options { dry_run: policy.dry_run, ..Options::default() };
113    let reports = migrate_all(global, "agent:", &opts, stop);
114    for r in &reports {
115        if let Outcome::Failed(why) = &r.outcome {
116            tracing::warn!(zone = %r.zone, why = %why, "history migration: a zone was left as it was");
117        }
118    }
119    Some(summarize(&reports, policy.dry_run))
120}
121
122/// One pass over this channel's per-channel copies of defined agents' conversations (check L5): each
123/// is deleted once every kept line of it is in the shared store, and what the store lacked is put there
124/// first. Runs after [`pass_global`], in the same pass. `None` when the pass is off or there is no shared
125/// store. Blocking: run it on a blocking thread.
126pub fn pass_copies(policy: &Policy, stop: &AtomicBool, own: &FileStore, mstore: &Store) -> Option<copies::Summary> {
127    if !policy.enabled {
128        return None;
129    }
130    let opts = copies::Options { dry_run: policy.dry_run, ..copies::Options::default() };
131    let reports = copies::pass(own, mstore, &opts, stop)?;
132    Some(copies::summarize(&reports, policy.dry_run))
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use serde_json::json;
139
140    fn extra(pairs: &[(&str, serde_json::Value)]) -> HashMap<String, serde_json::Value> {
141        pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
142    }
143
144    #[test]
145    fn the_pass_is_off_unless_a_setting_turns_it_on() {
146        assert_eq!(Policy::from_extra(&extra(&[])), Policy { enabled: false, dry_run: false });
147        assert!(!Policy::from_extra(&extra(&[(KEY_MIGRATE, json!("yes"))])).enabled, "a mistyped value is off");
148        assert_eq!(Policy::from_extra(&extra(&[(KEY_MIGRATE, json!(true))])), Policy { enabled: true, dry_run: false });
149    }
150
151    #[test]
152    fn a_dry_run_needs_no_other_setting_and_writes_nothing() {
153        let p = Policy::from_extra(&extra(&[(KEY_DRY_RUN, json!(true))]));
154        assert_eq!(p, Policy { enabled: true, dry_run: true });
155        let both = Policy::from_extra(&extra(&[(KEY_MIGRATE, json!(true)), (KEY_DRY_RUN, json!(true))]));
156        assert!(both.dry_run, "the dry run wins when both are set");
157    }
158
159    #[test]
160    fn an_off_pass_does_not_touch_the_store() {
161        assert_eq!(pass_global(&Policy { enabled: false, dry_run: false }, &AtomicBool::new(false)), None);
162        let (fs, store) = (FileStore::open_in_memory().unwrap(), Store::open_in_memory().unwrap());
163        let off = Policy { enabled: false, dry_run: false };
164        assert_eq!(pass_copies(&off, &AtomicBool::new(false), &fs, &store), None);
165    }
166}