1use std::collections::{BTreeMap, BTreeSet};
53
54use chrono::{DateTime, Datelike, Days, FixedOffset, NaiveDate, Timelike, Weekday};
55use serde::{Deserialize, Serialize};
56
57pub const BASELINE_WINDOW_DAYS: u32 = 28;
59
60pub const WARM_UP_DAYS: u32 = 14;
62
63pub const RECENT_WINDOW_DAYS: [u32; 2] = [7, 14];
65
66pub const DEVIATION_K: f64 = 2.5;
68
69pub const MEANINGFUL_DIMENSIONS: usize = 2;
71
72pub const MEANINGFUL_RUN_DAYS: u32 = 10;
74
75pub const COOLDOWN_DAYS: u32 = 7;
77
78pub const ACTIVITY_MINUTE_FLOOR: f64 = 45.0;
83
84pub fn median(values: &[f64]) -> Option<f64> {
101 let mut finite: Vec<f64> = values.iter().copied().filter(|value| value.is_finite()).collect();
102 if finite.is_empty() {
103 return None;
104 }
105 finite.sort_by(f64::total_cmp);
106 let mid = finite.len() / 2;
107 if finite.len().is_multiple_of(2) {
108 Some(finite[mid - 1] / 2.0 + finite[mid] / 2.0)
110 } else {
111 Some(finite[mid])
112 }
113}
114
115pub fn mad(values: &[f64]) -> Option<f64> {
131 let center = median(values)?;
132 let deviations: Vec<f64> = values
133 .iter()
134 .filter(|value| value.is_finite())
135 .map(|value| (value - center).abs())
136 .collect();
137 median(&deviations)
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase")]
153pub enum DayClass {
154 Weekday,
156 Weekend,
158}
159
160impl DayClass {
161 pub const ALL: [DayClass; 2] = [DayClass::Weekday, DayClass::Weekend];
163
164 pub fn of(date: NaiveDate) -> Self {
166 match date.weekday() {
167 Weekday::Sat | Weekday::Sun => DayClass::Weekend,
168 Weekday::Mon | Weekday::Tue | Weekday::Wed | Weekday::Thu | Weekday::Fri => {
169 DayClass::Weekday
170 }
171 }
172 }
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
189#[serde(rename_all = "camelCase")]
190pub struct DailyValue {
191 pub date: NaiveDate,
193 pub value: f64,
195}
196
197impl DailyValue {
198 pub fn new(date: NaiveDate, value: f64) -> Self {
200 Self { date, value }
201 }
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase")]
223pub struct DimensionBaseline {
224 pub class: DayClass,
226 pub window_end: NaiveDate,
228 pub median: f64,
230 pub mad: f64,
232 pub samples: usize,
234}
235
236impl DimensionBaseline {
237 pub fn threshold(&self, k: f64, floor: f64) -> f64 {
240 (k * self.mad).max(floor)
241 }
242
243 pub fn deviates(&self, recent: f64, k: f64, floor: f64) -> bool {
245 (recent - self.median).abs() > self.threshold(k, floor)
246 }
247}
248
249pub fn baseline(
252 series: &[DailyValue],
253 class: DayClass,
254 window_end: NaiveDate,
255) -> Option<DimensionBaseline> {
256 let values = window_values(series, class, window_end, BASELINE_WINDOW_DAYS);
257 Some(DimensionBaseline {
258 class,
259 window_end,
260 median: median(&values)?,
261 mad: mad(&values)?,
262 samples: values.iter().filter(|value| value.is_finite()).count(),
263 })
264}
265
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
278#[serde(rename_all = "camelCase")]
279pub struct WarmUp {
280 pub observed_days: u32,
282 pub required_days: u32,
284}
285
286impl WarmUp {
287 pub fn is_complete(&self) -> bool {
289 self.observed_days >= self.required_days
290 }
291}
292
293pub fn warm_up(series: &[DailyValue], window_end: NaiveDate) -> WarmUp {
296 let start = window_start(window_end, BASELINE_WINDOW_DAYS);
297 let days: BTreeSet<NaiveDate> = series
298 .iter()
299 .filter(|point| point.value.is_finite() && point.date >= start && point.date <= window_end)
300 .map(|point| point.date)
301 .collect();
302 WarmUp {
303 observed_days: u32::try_from(days.len()).unwrap_or(u32::MAX),
304 required_days: WARM_UP_DAYS,
305 }
306}
307
308pub fn baseline_window_end(as_of: NaiveDate) -> NaiveDate {
311 let longest = RECENT_WINDOW_DAYS.iter().copied().max().unwrap_or(0);
312 as_of.checked_sub_days(Days::new(u64::from(longest))).unwrap_or(NaiveDate::MIN)
313}
314
315#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
331#[serde(rename_all = "camelCase")]
332pub struct DeviationConfig {
333 pub k: f64,
335 pub floors: BTreeMap<String, f64>,
337 pub default_floor: f64,
339}
340
341impl Default for DeviationConfig {
342 fn default() -> Self {
343 Self {
344 k: DEVIATION_K,
345 floors: BTreeMap::from([
346 (ACTIVITY_FIRST_MINUTE.to_string(), ACTIVITY_MINUTE_FLOOR),
347 (ACTIVITY_LAST_MINUTE.to_string(), ACTIVITY_MINUTE_FLOOR),
348 ]),
349 default_floor: 0.0,
350 }
351 }
352}
353
354impl DeviationConfig {
355 pub fn with_floor(mut self, dimension: impl Into<String>, floor: f64) -> Self {
357 self.floors.insert(dimension.into(), floor);
358 self
359 }
360
361 pub fn with_default_floor(mut self, floor: f64) -> Self {
363 self.default_floor = floor;
364 self
365 }
366
367 pub fn floor(&self, dimension: &str) -> f64 {
369 self.floors.get(dimension).copied().unwrap_or(self.default_floor)
370 }
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase")]
376pub struct WindowTest {
377 pub days: u32,
379 #[serde(skip_serializing_if = "Option::is_none")]
381 pub recent_median: Option<f64>,
382 pub samples: usize,
384 pub deviates: bool,
386}
387
388#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
390#[serde(rename_all = "camelCase")]
391pub struct ClassDeviation {
392 pub class: DayClass,
394 #[serde(skip_serializing_if = "Option::is_none")]
396 pub baseline: Option<DimensionBaseline>,
397 #[serde(skip_serializing_if = "Option::is_none")]
399 pub threshold: Option<f64>,
400 pub windows: Vec<WindowTest>,
402 pub deviating: bool,
404}
405
406#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
408#[serde(rename_all = "camelCase")]
409pub struct DimensionDeviation {
410 pub dimension: String,
412 pub floor: f64,
414 pub warm_up: WarmUp,
416 pub classes: Vec<ClassDeviation>,
418 pub deviating: bool,
420}
421
422pub fn check_dimension(
446 dimension: &str,
447 series: &[DailyValue],
448 as_of: NaiveDate,
449 config: &DeviationConfig,
450) -> DimensionDeviation {
451 let window_end = baseline_window_end(as_of);
452 let warm_up = warm_up(series, window_end);
453 let floor = config.floor(dimension);
454 let classes: Vec<ClassDeviation> = DayClass::ALL
455 .iter()
456 .map(|&class| {
457 let baseline = baseline(series, class, window_end);
458 let windows: Vec<WindowTest> = RECENT_WINDOW_DAYS
459 .iter()
460 .map(|&days| {
461 let values = window_values(series, class, as_of, days);
462 let recent_median = median(&values);
463 let deviates = match (recent_median, &baseline) {
464 (Some(recent), Some(baseline)) => {
465 baseline.deviates(recent, config.k, floor)
466 }
467 (None, _) | (_, None) => false,
468 };
469 WindowTest {
470 days,
471 recent_median,
472 samples: values.iter().filter(|value| value.is_finite()).count(),
473 deviates,
474 }
475 })
476 .collect();
477 ClassDeviation {
478 class,
479 threshold: baseline.map(|baseline| baseline.threshold(config.k, floor)),
480 baseline,
481 deviating: warm_up.is_complete() && windows.iter().all(|window| window.deviates),
482 windows,
483 }
484 })
485 .collect();
486 DimensionDeviation {
487 dimension: dimension.to_string(),
488 floor,
489 warm_up,
490 deviating: classes.iter().any(|class| class.deviating),
491 classes,
492 }
493}
494
495#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
497#[serde(rename_all = "camelCase")]
498pub struct DeviationReport {
499 pub as_of: NaiveDate,
501 pub dimensions: Vec<DimensionDeviation>,
503}
504
505impl DeviationReport {
506 pub fn deviating(&self) -> Vec<&str> {
508 self.dimensions
509 .iter()
510 .filter(|dimension| dimension.deviating)
511 .map(|dimension| dimension.dimension.as_str())
512 .collect()
513 }
514}
515
516pub fn check_series(
518 series: &BTreeMap<String, Vec<DailyValue>>,
519 as_of: NaiveDate,
520 config: &DeviationConfig,
521) -> DeviationReport {
522 DeviationReport {
523 as_of,
524 dimensions: series
525 .iter()
526 .map(|(dimension, values)| check_dimension(dimension, values, as_of, config))
527 .collect(),
528 }
529}
530
531pub fn is_meaningful(run_days: &[u32]) -> bool {
547 run_days.len() >= MEANINGFUL_DIMENSIONS
548 || run_days.iter().any(|&days| days >= MEANINGFUL_RUN_DAYS)
549}
550
551#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
577#[serde(rename_all = "camelCase")]
578pub struct DriftState {
579 pub deviating_since: BTreeMap<String, NaiveDate>,
581 pub last_observed: BTreeMap<String, NaiveDate>,
583}
584
585#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
587#[serde(rename_all = "camelCase")]
588pub struct DriftRun {
589 pub dimension: String,
591 pub since: NaiveDate,
593 pub days: u32,
595 pub cooling_down: bool,
597}
598
599#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
601#[serde(rename_all = "camelCase")]
602pub struct DriftStep {
603 pub state: DriftState,
605 pub runs: Vec<DriftRun>,
607 pub observed: Vec<String>,
610}
611
612impl DriftState {
613 pub fn in_cooldown(&self, dimension: &str, day: NaiveDate) -> bool {
615 self.last_observed
616 .get(dimension)
617 .is_some_and(|last| (day - *last).num_days() < i64::from(COOLDOWN_DAYS))
618 }
619
620 pub fn advance(&self, day: NaiveDate, deviating: &[&str]) -> DriftStep {
629 let mut names: Vec<&str> = deviating.to_vec();
630 names.sort_unstable();
631 names.dedup();
632
633 let mut state = DriftState {
634 deviating_since: BTreeMap::new(),
635 last_observed: self.last_observed.clone(),
636 };
637 let runs: Vec<DriftRun> = names
638 .into_iter()
639 .map(|name| {
640 let since = self
641 .deviating_since
642 .get(name)
643 .copied()
644 .filter(|since| *since <= day)
645 .unwrap_or(day);
646 state.deviating_since.insert(name.to_string(), since);
647 DriftRun {
648 dimension: name.to_string(),
649 since,
650 days: u32::try_from((day - since).num_days() + 1).unwrap_or(u32::MAX),
651 cooling_down: self.in_cooldown(name, day),
652 }
653 })
654 .collect();
655
656 let candidates: Vec<&DriftRun> = runs.iter().filter(|run| !run.cooling_down).collect();
657 let candidate_days: Vec<u32> = candidates.iter().map(|run| run.days).collect();
658 let observed: Vec<String> = if is_meaningful(&candidate_days) {
659 candidates.iter().map(|run| run.dimension.clone()).collect()
660 } else {
661 Vec::new()
662 };
663 for dimension in &observed {
664 state.last_observed.insert(dimension.clone(), day);
665 }
666 DriftStep { state, runs, observed }
667 }
668}
669
670#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
675#[serde(rename_all = "camelCase")]
676pub struct LedgerAssessment {
677 pub first_day: NaiveDate,
679 pub last_day: NaiveDate,
681 pub report: DeviationReport,
683 pub runs: Vec<DriftRun>,
685 pub meaningful: bool,
687}
688
689pub fn assess(
697 series: &BTreeMap<String, Vec<DailyValue>>,
698 config: &DeviationConfig,
699) -> Option<LedgerAssessment> {
700 let dates = || series.values().flatten().map(|point| point.date);
701 let first_day = dates().min()?;
702 let last_day = dates().max()?;
703
704 let mut state = DriftState::default();
705 let mut runs = Vec::new();
706 let mut report = check_series(series, first_day, config);
707 for day in first_day.iter_days().take_while(|day| *day <= last_day) {
708 report = check_series(series, day, config);
709 let step = state.advance(day, &report.deviating());
710 state = step.state;
711 runs = step.runs;
712 }
713 let run_days: Vec<u32> = runs.iter().map(|run| run.days).collect();
714 Some(LedgerAssessment {
715 first_day,
716 last_day,
717 report,
718 meaningful: is_meaningful(&run_days),
719 runs,
720 })
721}
722
723pub const ACTIVITY_FIRST_MINUTE: &str = "activity.first_minute";
727
728pub const ACTIVITY_LAST_MINUTE: &str = "activity.last_minute";
730
731#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
754#[serde(rename_all = "camelCase")]
755pub struct LedgerRow {
756 pub ts: DateTime<FixedOffset>,
759 pub partition: String,
761 pub agent: String,
763 pub kind: String,
766 #[serde(default, skip_serializing_if = "Option::is_none")]
768 pub effect: Option<String>,
769 #[serde(default, skip_serializing_if = "Option::is_none")]
771 pub duration_ms: Option<u64>,
772 #[serde(default, skip_serializing_if = "Option::is_none")]
774 pub subject_hash: Option<String>,
775 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
777 pub meta: serde_json::Map<String, serde_json::Value>,
778 #[serde(default, skip_serializing_if = "Option::is_none")]
780 pub trace_id: Option<String>,
781}
782
783#[derive(Debug, thiserror::Error)]
785#[error(
786 "ledger line {line} is not a ledger row: {source}. Each line must be one JSON object with \
787 ts (RFC 3339 with an offset), partition, agent and kind, and optionally effect, \
788 durationMs, subjectHash, meta and traceId"
789)]
790pub struct LedgerParseError {
791 pub line: usize,
793 #[source]
795 pub source: serde_json::Error,
796}
797
798pub fn parse_jsonl(text: &str) -> Result<Vec<LedgerRow>, LedgerParseError> {
819 text.lines()
820 .enumerate()
821 .filter(|(_, line)| !line.trim().is_empty())
822 .map(|(index, line)| {
823 serde_json::from_str(line)
824 .map_err(|source| LedgerParseError { line: index + 1, source })
825 })
826 .collect()
827}
828
829pub fn daily_series(rows: &[LedgerRow]) -> BTreeMap<String, Vec<DailyValue>> {
858 let mut days: BTreeMap<NaiveDate, Vec<&LedgerRow>> = BTreeMap::new();
859 for row in rows {
860 days.entry(row.ts.date_naive()).or_default().push(row);
861 }
862 let kinds: BTreeSet<&str> = rows.iter().map(|row| row.kind.as_str()).collect();
863
864 let mut series: BTreeMap<String, Vec<DailyValue>> = BTreeMap::new();
865 let mut push = |dimension: String, date: NaiveDate, value: f64| {
866 series.entry(dimension).or_default().push(DailyValue::new(date, value));
867 };
868 for (&date, day_rows) in &days {
869 let minutes: Vec<f64> = day_rows
870 .iter()
871 .map(|row| f64::from(row.ts.time().num_seconds_from_midnight()) / 60.0)
872 .collect();
873 let first = minutes.iter().copied().fold(f64::INFINITY, f64::min);
874 let last = minutes.iter().copied().fold(f64::NEG_INFINITY, f64::max);
875 push(ACTIVITY_FIRST_MINUTE.to_string(), date, first);
876 push(ACTIVITY_LAST_MINUTE.to_string(), date, last);
877
878 for kind in &kinds {
879 let of_kind: Vec<&LedgerRow> =
880 day_rows.iter().copied().filter(|row| row.kind == *kind).collect();
881 push(format!("{kind}.count"), date, of_kind.len() as f64);
882
883 let durations: Vec<f64> =
884 of_kind.iter().filter_map(|row| row.duration_ms).map(|ms| ms as f64).collect();
885 if let Some(duration) = median(&durations) {
886 push(format!("{kind}.duration_ms"), date, duration);
887 }
888
889 let mut sums: BTreeMap<&str, f64> = BTreeMap::new();
890 for row in &of_kind {
891 for (key, value) in &row.meta {
892 if let Some(number) = value.as_f64() {
893 *sums.entry(key.as_str()).or_default() += number;
894 }
895 }
896 }
897 for (key, sum) in sums {
898 push(format!("{kind}.meta.{key}"), date, sum);
899 }
900 }
901 }
902 series
903}
904
905fn window_values(series: &[DailyValue], class: DayClass, end: NaiveDate, days: u32) -> Vec<f64> {
907 let start = window_start(end, days);
908 series
909 .iter()
910 .filter(|point| {
911 point.date >= start && point.date <= end && DayClass::of(point.date) == class
912 })
913 .map(|point| point.value)
914 .collect()
915}
916
917fn window_start(end: NaiveDate, days: u32) -> NaiveDate {
919 end.checked_sub_days(Days::new(u64::from(days.saturating_sub(1)))).unwrap_or(NaiveDate::MIN)
920}
921
922#[cfg(test)]
923mod tests {
924 use super::*;
925
926 fn date(year: i32, month: u32, day: u32) -> NaiveDate {
927 NaiveDate::from_ymd_opt(year, month, day).unwrap()
928 }
929
930 fn start() -> NaiveDate {
932 date(2026, 8, 31)
933 }
934
935 fn day(offset: u64) -> NaiveDate {
936 start() + Days::new(offset)
937 }
938
939 fn series(days: u64, value: impl Fn(u64) -> f64) -> Vec<DailyValue> {
941 (0..days).map(|offset| DailyValue::new(day(offset), value(offset))).collect()
942 }
943
944 #[test]
945 fn median_and_mad_of_odd_even_and_empty_inputs() {
946 assert_eq!(median(&[]), None);
947 assert_eq!(mad(&[]), None);
948 assert_eq!(median(&[7.0]), Some(7.0));
949 assert_eq!(mad(&[7.0]), Some(0.0));
950 assert_eq!(median(&[5.0, 1.0, 3.0]), Some(3.0));
951 assert_eq!(median(&[1.0, 4.0, 2.0, 3.0]), Some(2.5));
952 assert_eq!(mad(&[1.0, 2.0, 3.0, 4.0, 100.0]), Some(1.0));
953 assert_eq!(median(&[1.0, f64::NAN, 3.0, f64::INFINITY]), Some(2.0));
954 }
955
956 #[test]
957 fn day_classes_split_saturday_and_sunday_from_the_week() {
958 let classes: Vec<DayClass> = (0..7).map(|offset| DayClass::of(day(offset))).collect();
959 assert_eq!(
960 classes,
961 [
962 DayClass::Weekday,
963 DayClass::Weekday,
964 DayClass::Weekday,
965 DayClass::Weekday,
966 DayClass::Weekday,
967 DayClass::Weekend,
968 DayClass::Weekend,
969 ]
970 );
971 }
972
973 #[test]
974 fn the_baseline_window_ends_before_the_fourteen_day_window() {
975 let as_of = day(41);
976 assert_eq!(baseline_window_end(as_of), day(27));
977 let points = series(42, |offset| if offset < 28 { 10.0 } else { 99.0 });
979 let weekdays = baseline(&points, DayClass::Weekday, baseline_window_end(as_of)).unwrap();
980 assert_eq!(
981 weekdays,
982 DimensionBaseline {
983 class: DayClass::Weekday,
984 window_end: day(27),
985 median: 10.0,
986 mad: 0.0,
987 samples: 20,
988 }
989 );
990 }
991
992 #[test]
993 fn warm_up_completes_on_the_fourteenth_baseline_day() {
994 let as_of = |baseline_days: u64| day(baseline_days - 1 + 14);
997 let shifted = |baseline_days: u64| {
998 series(
999 baseline_days + 14,
1000 move |offset| if offset < baseline_days { 10.0 } else { 50.0 },
1001 )
1002 };
1003 let config = DeviationConfig::default();
1004
1005 let day13 = check_dimension("x", &shifted(13), as_of(13), &config);
1006 assert_eq!(day13.warm_up, WarmUp { observed_days: 13, required_days: 14 });
1007 assert!(!day13.deviating);
1008 assert!(day13.classes.iter().all(|class| !class.deviating));
1009
1010 let day14 = check_dimension("x", &shifted(14), as_of(14), &config);
1011 assert_eq!(day14.warm_up, WarmUp { observed_days: 14, required_days: 14 });
1012 assert!(day14.deviating);
1013 }
1014
1015 #[test]
1016 fn warm_up_counts_days_not_values_and_ignores_days_outside_the_window() {
1017 let mut points = series(14, |_| 1.0);
1018 points.push(DailyValue::new(day(3), 2.0));
1019 assert_eq!(warm_up(&points, day(13)).observed_days, 14);
1020 assert_eq!(warm_up(&points, day(13 + 27)).observed_days, 1);
1022 }
1023
1024 #[test]
1025 fn mad_zero_leaves_the_floor_to_decide() {
1026 let constant = series(28, |_| 100.0);
1027 let weekdays = baseline(&constant, DayClass::Weekday, day(27)).unwrap();
1028 assert_eq!(weekdays.mad, 0.0);
1029 assert!(weekdays.deviates(110.0, DEVIATION_K, 0.0));
1030 assert!(weekdays.deviates(110.0, DEVIATION_K, 9.99));
1031 assert!(!weekdays.deviates(110.0, DEVIATION_K, 10.0));
1033 assert!(!weekdays.deviates(100.0, DEVIATION_K, 0.0));
1034 }
1035
1036 #[test]
1037 fn floors_raise_the_threshold_over_k_times_mad() {
1038 let alternating = series(28, |offset| if offset % 2 == 0 { 99.0 } else { 101.0 });
1040 let weekdays = baseline(&alternating, DayClass::Weekday, day(27)).unwrap();
1041 assert_eq!(weekdays.mad, 1.0);
1042 assert_eq!(weekdays.threshold(DEVIATION_K, 2.0), 2.5);
1043 assert_eq!(weekdays.threshold(DEVIATION_K, 4.0), 4.0);
1044 assert!(weekdays.deviates(103.0, DEVIATION_K, 2.0));
1045 assert!(!weekdays.deviates(103.0, DEVIATION_K, 4.0));
1046 }
1047
1048 #[test]
1049 fn weekday_and_weekend_keep_separate_baselines() {
1050 let weekly = |offset: u64| match DayClass::of(day(offset)) {
1052 DayClass::Weekday => 100.0,
1053 DayClass::Weekend => 0.0,
1054 };
1055 let steady = series(42, weekly);
1056 let test = check_dimension("x", &steady, day(41), &DeviationConfig::default());
1057 assert!(!test.deviating);
1058 assert_eq!(
1059 test.classes.iter().map(|class| class.baseline.unwrap().median).collect::<Vec<_>>(),
1060 [100.0, 0.0]
1061 );
1062
1063 let weekend_drift = series(42, |offset| match DayClass::of(day(offset)) {
1065 DayClass::Weekday => 100.0,
1066 DayClass::Weekend if offset >= 28 => 60.0,
1067 DayClass::Weekend => 0.0,
1068 });
1069 let test = check_dimension("x", &weekend_drift, day(41), &DeviationConfig::default());
1070 assert!(test.deviating);
1071 assert_eq!(
1072 test.classes.iter().map(|class| (class.class, class.deviating)).collect::<Vec<_>>(),
1073 [(DayClass::Weekday, false), (DayClass::Weekend, true)]
1074 );
1075 }
1076
1077 #[test]
1078 fn a_single_busy_week_does_not_deviate() {
1079 let busy_week = series(42, |offset| if offset >= 35 { 50.0 } else { 10.0 });
1081 let config = DeviationConfig::default().with_floor("x", 25.0);
1082 let test = check_dimension("x", &busy_week, day(41), &config);
1083 let weekday = &test.classes[0];
1084 assert_eq!(
1085 weekday.windows.iter().map(|window| window.deviates).collect::<Vec<_>>(),
1086 [true, false]
1087 );
1088 assert!(!test.deviating);
1089 }
1090
1091 #[test]
1092 fn a_class_without_values_does_not_deviate() {
1093 let weekdays_only: Vec<DailyValue> =
1095 series(42, |offset| if offset < 28 { 1.0 } else { 9.0 })
1096 .into_iter()
1097 .filter(|point| DayClass::of(point.date) == DayClass::Weekday)
1098 .collect();
1099 let test = check_dimension("x", &weekdays_only, day(41), &DeviationConfig::default());
1100 let weekend = &test.classes[1];
1101 assert_eq!(weekend.baseline, None);
1102 assert!(weekend.windows.iter().all(|window| window.recent_median.is_none()));
1103 assert!(!weekend.deviating);
1104 assert!(test.deviating);
1105 }
1106
1107 #[test]
1108 fn meaningful_needs_two_dimensions_or_ten_days() {
1109 assert!(!is_meaningful(&[]));
1110 assert!(!is_meaningful(&[1]));
1111 assert!(!is_meaningful(&[9]));
1112 assert!(is_meaningful(&[10]));
1113 assert!(is_meaningful(&[1, 2]));
1114 }
1115
1116 #[test]
1117 fn a_single_dimension_is_observed_on_its_tenth_day() {
1118 let mut state = DriftState::default();
1119 for offset in 0..9 {
1120 let step = state.advance(day(offset), &["x"]);
1121 assert!(step.observed.is_empty(), "day {}", offset + 1);
1122 state = step.state;
1123 }
1124 let tenth = state.advance(day(9), &["x"]);
1125 assert_eq!(tenth.observed, ["x"]);
1126 assert_eq!(
1127 tenth.runs,
1128 [DriftRun { dimension: "x".into(), since: day(0), days: 10, cooling_down: false }]
1129 );
1130 }
1131
1132 #[test]
1133 fn a_day_without_the_deviation_ends_the_run() {
1134 let step = DriftState::default().advance(day(0), &["x"]);
1135 let step = step.state.advance(day(1), &[]);
1136 assert!(step.state.deviating_since.is_empty());
1137 let step = step.state.advance(day(2), &["x"]);
1138 assert_eq!(step.runs[0].since, day(2));
1139 assert_eq!(step.runs[0].days, 1);
1140 }
1141
1142 #[test]
1143 fn the_cooldown_lasts_seven_days_per_dimension() {
1144 let observed = DriftState::default().advance(day(0), &["a", "b"]);
1145 assert_eq!(observed.observed, ["a", "b"]);
1146
1147 let day6 = observed.state.advance(day(6), &["a", "b", "c"]);
1149 assert!(day6.observed.is_empty());
1150 assert_eq!(
1151 day6.runs.iter().map(|run| run.cooling_down).collect::<Vec<_>>(),
1152 [true, true, false]
1153 );
1154
1155 let day7 = day6.state.advance(day(7), &["a", "b", "c"]);
1157 assert_eq!(day7.observed, ["a", "b", "c"]);
1158 assert_eq!(day7.state.last_observed.get("a"), Some(&day(7)));
1159 }
1160
1161 #[test]
1162 fn advancing_twice_on_one_day_observes_once() {
1163 let first = DriftState::default().advance(day(0), &["a", "b"]);
1164 let second = first.state.advance(day(0), &["a", "b"]);
1165 assert_eq!(first.observed.len(), 2);
1166 assert!(second.observed.is_empty());
1167 assert_eq!(first.state, second.state);
1168 }
1169
1170 #[test]
1171 fn advance_leaves_the_state_it_was_called_on_unchanged() {
1172 let state = DriftState::default().advance(day(0), &["a"]).state;
1173 let before = state.clone();
1174 let _ = state.advance(day(1), &["a", "b"]);
1175 assert_eq!(state, before);
1176 }
1177
1178 #[test]
1179 fn assess_counts_runs_across_the_whole_ledger() {
1180 let drift = series(42, |offset| if offset < 28 { 10.0 } else { 50.0 });
1181 let dims = BTreeMap::from([("x".to_string(), drift)]);
1182 let assessment = assess(&dims, &DeviationConfig::default()).unwrap();
1183 assert_eq!((assessment.first_day, assessment.last_day), (day(0), day(41)));
1184 assert_eq!(assessment.report.as_of, day(41));
1185 assert_eq!(assessment.runs.len(), 1);
1186 let run = &assessment.runs[0];
1187 assert_eq!(run.days, u32::try_from((day(41) - run.since).num_days() + 1).unwrap());
1188 assert_eq!(assessment.meaningful, run.days >= MEANINGFUL_RUN_DAYS);
1189 assert_eq!(assess(&BTreeMap::new(), &DeviationConfig::default()), None);
1190 }
1191
1192 #[test]
1193 fn rows_parse_from_camel_case_and_ignore_unknown_fields() {
1194 let rows = parse_jsonl(
1195 r#"{"ts":"2026-10-22T19:20:04+03:00","partition":"work","agent":"assistant","kind":"tool_call","effect":"read_only","durationMs":182,"subjectHash":"hmac-sha256:5f2c","meta":{"attempt":1},"traceId":"4bf9","seq":7}"#,
1196 )
1197 .unwrap();
1198 assert_eq!(
1199 rows,
1200 [LedgerRow {
1201 ts: DateTime::parse_from_rfc3339("2026-10-22T19:20:04+03:00").unwrap(),
1202 partition: "work".into(),
1203 agent: "assistant".into(),
1204 kind: "tool_call".into(),
1205 effect: Some("read_only".into()),
1206 duration_ms: Some(182),
1207 subject_hash: Some("hmac-sha256:5f2c".into()),
1208 meta: serde_json::Map::from_iter([("attempt".to_string(), 1.into())]),
1209 trace_id: Some("4bf9".into()),
1210 }]
1211 );
1212 let json = serde_json::to_value(&rows[0]).unwrap();
1213 assert_eq!(json["durationMs"], 182);
1214 assert_eq!(json["subjectHash"], "hmac-sha256:5f2c");
1215 assert_eq!(json["traceId"], "4bf9");
1216 }
1217
1218 #[test]
1219 fn a_bad_line_reports_its_line_number() {
1220 let export = "\n{\"ts\":\"2026-10-22T09:00:00Z\",\"partition\":\"p\",\"agent\":\"a\",\"kind\":\"k\"}\n{\"ts\":\"2026-10-22T09:00:00\",\"partition\":\"p\",\"agent\":\"a\",\"kind\":\"k\"}\n";
1221 let error = parse_jsonl(export).unwrap_err();
1222 assert_eq!(error.line, 3);
1223 assert!(error.to_string().contains("RFC 3339 with an offset"), "{error}");
1224 }
1225
1226 #[test]
1227 fn daily_series_reads_days_and_times_in_the_row_offset() {
1228 let rows = parse_jsonl(
1229 r#"{"ts":"2026-10-22T23:30:00+03:00","partition":"p","agent":"a","kind":"wake"}
1230{"ts":"2026-10-22T08:15:00+03:00","partition":"p","agent":"a","kind":"tool_call","durationMs":100,"meta":{"inputTokens":10,"label":"x"}}
1231{"ts":"2026-10-22T09:00:00+03:00","partition":"p","agent":"a","kind":"tool_call","durationMs":300,"meta":{"inputTokens":5}}
1232{"ts":"2026-10-23T10:00:00+03:00","partition":"p","agent":"a","kind":"wake"}"#,
1233 )
1234 .unwrap();
1235 let series = daily_series(&rows);
1236 let values = |dimension: &str| -> Vec<(NaiveDate, f64)> {
1237 series[dimension].iter().map(|point| (point.date, point.value)).collect()
1238 };
1239 let (d22, d23) = (date(2026, 10, 22), date(2026, 10, 23));
1240 assert_eq!(
1241 series.keys().map(String::as_str).collect::<Vec<_>>(),
1242 [
1243 "activity.first_minute",
1244 "activity.last_minute",
1245 "tool_call.count",
1246 "tool_call.duration_ms",
1247 "tool_call.meta.inputTokens",
1248 "wake.count",
1249 ]
1250 );
1251 assert_eq!(values("activity.first_minute"), [(d22, 8.0 * 60.0 + 15.0), (d23, 600.0)]);
1252 assert_eq!(values("activity.last_minute"), [(d22, 23.0 * 60.0 + 30.0), (d23, 600.0)]);
1254 assert_eq!(values("tool_call.count"), [(d22, 2.0), (d23, 0.0)]);
1255 assert_eq!(values("tool_call.duration_ms"), [(d22, 200.0)]);
1256 assert_eq!(values("tool_call.meta.inputTokens"), [(d22, 15.0)]);
1257 assert_eq!(values("wake.count"), [(d22, 1.0), (d23, 1.0)]);
1258 }
1259}