agentmux_srv_core/backend/transcript/
migrate_run.rs1use 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
19pub const KEY_MIGRATE: &str = "history:compactmigrate";
21pub 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 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#[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 pub unproven_causes: std::collections::BTreeMap<&'static str, usize>,
60 pub unknown_kinds: std::collections::BTreeMap<String, usize>,
62 pub unsettled_zones: Vec<String>,
64 pub swapped_zones: Vec<String>,
66}
67
68pub 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
105pub 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
122pub 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}