zc2 0.0.39

P2P compute broker with credit-based billing, WAL, and broker mesh support
//! Rolling hourly usage/earnings history behind the summary's `history`
//! field (docs/agent-api.md "Summary v1"). Pure recording logic: `Core`
//! samples the supervisor's request gauge and the hub's `earnings.today`
//! into it on every fresh hub poll, and persists it next to the rest of the
//! agent's state so it survives a restart.

use crate::agent::files;
use crate::agent::summary::{HourBucket, HourlyHistory};
use chrono::{DateTime, Duration, Timelike, Utc};
use serde::{Deserialize, Serialize};
use std::path::Path;

/// At most this many hourly buckets are kept, oldest first.
const MAX_HOURS: usize = 12;

/// The rolling series, plus the last raw gauge values seen so the next
/// sample can turn into a delta. Persisted as-is (its shape need not match
/// the wire `history` field) in the agent's state dir.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct History {
    hours: Vec<HourBucket>,
    #[serde(default)]
    last_requests: Option<u64>,
    #[serde(default)]
    last_credits: Option<f64>,
}

fn floor_to_hour(now: DateTime<Utc>) -> String {
    now.with_minute(0)
        .and_then(|t| t.with_second(0))
        .and_then(|t| t.with_nanosecond(0))
        .unwrap_or(now)
        .to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

impl History {
    /// Fold one fresh sample in: `requests_5h` and `credits_today` are raw
    /// gauges (spec: the supervisor's summed `requests_5h`, and the hub's
    /// `earnings.today`), sampled only when they are known-fresh -- callers
    /// must not invoke this while the hub is unreachable.
    ///
    /// The first sample of a gauge only establishes a baseline (its delta is
    /// 0): there is no earlier sample to diff against, so nothing before this
    /// moment can be attributed to a specific hour. A gauge that decreases
    /// contributes 0 for `requests_5h` (a worker restarted, or the window
    /// rolled off), and the new value itself for `credits_today` (a midnight
    /// reset), never a negative delta either way.
    pub fn record(&mut self, now: DateTime<Utc>, requests_5h: u64, credits_today: f64) {
        let requests_delta = match self.last_requests {
            Some(prev) => requests_5h.saturating_sub(prev),
            None => 0,
        };
        let credits_delta = match self.last_credits {
            Some(prev) if credits_today >= prev => credits_today - prev,
            Some(_) => credits_today,
            None => 0.0,
        };
        self.last_requests = Some(requests_5h);
        self.last_credits = Some(credits_today);

        let start = floor_to_hour(now);
        match self.hours.last_mut() {
            Some(b) if b.start == start => {
                b.requests += requests_delta;
                b.credits += credits_delta;
            }
            _ => self.hours.push(HourBucket {
                start,
                requests: requests_delta,
                credits: credits_delta,
            }),
        }
        self.trim();
    }

    fn trim(&mut self) {
        if self.hours.len() > MAX_HOURS {
            let excess = self.hours.len() - MAX_HOURS;
            self.hours.drain(0..excess);
        }
    }

    /// The wire form: `None` once there is nothing recorded yet, so the
    /// whole `history` object is omitted from the summary (contract).
    pub fn to_wire(&self) -> Option<HourlyHistory> {
        if self.hours.is_empty() {
            None
        } else {
            Some(HourlyHistory {
                hours: self.hours.clone(),
            })
        }
    }

    /// Load the persisted series, dropping any bucket older than 12 hours
    /// (an agent that was off for a while must not resurrect ancient
    /// buckets) and capping at 12 either way. A missing file is silently an
    /// empty series; a corrupt or otherwise unreadable one is logged once and
    /// also treated as empty -- never a reason to fail startup.
    pub fn load(path: &Path, now: DateTime<Utc>) -> Self {
        let mut h: Self = if path.exists() {
            files::load_json(path).unwrap_or_else(|| {
                eprintln!(
                    "  [AGENT] {} is unreadable; starting with an empty usage history",
                    path.display()
                );
                Self::default()
            })
        } else {
            Self::default()
        };
        let cutoff = now - Duration::hours(MAX_HOURS as i64);
        h.hours.retain(|b| {
            DateTime::parse_from_rfc3339(&b.start)
                .map(|t| t.with_timezone(&Utc) > cutoff)
                .unwrap_or(false)
        });
        h.trim();
        h
    }

    pub fn save(&self, path: &Path) -> std::io::Result<()> {
        files::save_json(path, self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn t(s: &str) -> DateTime<Utc> {
        DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
    }

    /// Two samples inside one hour accumulate into one bucket.
    #[test]
    fn two_samples_in_one_hour_accumulate() {
        let mut h = History::default();
        h.record(t("2026-09-16T04:10:00Z"), 10, 1.0); // baseline: delta 0
        h.record(t("2026-09-16T04:40:00Z"), 15, 1.5);
        let hours = h.to_wire().unwrap().hours;
        assert_eq!(hours.len(), 1);
        assert_eq!(hours[0].start, "2026-09-16T04:00:00Z");
        assert_eq!(hours[0].requests, 5);
        assert!((hours[0].credits - 0.5).abs() < 1e-9);
    }

    /// A sample crossing an hour boundary opens a new bucket and leaves the
    /// old one intact.
    #[test]
    fn crossing_an_hour_boundary_opens_a_new_bucket() {
        let mut h = History::default();
        h.record(t("2026-09-16T04:50:00Z"), 10, 1.0);
        h.record(t("2026-09-16T04:55:00Z"), 12, 1.2);
        h.record(t("2026-09-16T05:05:00Z"), 20, 1.6);
        let hours = h.to_wire().unwrap().hours;
        assert_eq!(hours.len(), 2);
        assert_eq!(hours[0].start, "2026-09-16T04:00:00Z");
        assert_eq!(hours[0].requests, 2);
        assert_eq!(hours[1].start, "2026-09-16T05:00:00Z");
        assert_eq!(hours[1].requests, 8);
        assert!((hours[1].credits - 0.4).abs() < 1e-9);
    }

    /// A decreasing requests gauge (a worker restart, or the window rolling
    /// off) contributes 0, never a negative.
    #[test]
    fn a_decreasing_requests_gauge_contributes_zero() {
        let mut h = History::default();
        h.record(t("2026-09-16T04:00:00Z"), 30, 0.0);
        h.record(t("2026-09-16T04:05:00Z"), 4, 0.0); // worker restarted
        let hours = h.to_wire().unwrap().hours;
        assert_eq!(hours[0].requests, 0);
    }

    /// A decreasing `earnings.today` (a midnight reset) contributes the new
    /// value, not a negative.
    #[test]
    fn a_decreasing_earnings_today_contributes_the_new_value() {
        let mut h = History::default();
        h.record(t("2026-09-16T04:00:00Z"), 0, 9.5);
        h.record(t("2026-09-16T04:05:00Z"), 0, 0.4); // local midnight reset
        let hours = h.to_wire().unwrap().hours;
        assert!((hours[0].credits - 0.4).abs() < 1e-9);
    }

    /// Only the last 12 buckets are kept, oldest dropped first.
    #[test]
    fn only_the_last_12_buckets_are_kept() {
        let mut h = History::default();
        for hour in 0..15 {
            h.record(
                t(&format!("2026-09-16T{hour:02}:00:00Z")),
                (hour as u64) + 1,
                0.0,
            );
        }
        let hours = h.to_wire().unwrap().hours;
        assert_eq!(hours.len(), 12);
        assert_eq!(hours.first().unwrap().start, "2026-09-16T03:00:00Z");
        assert_eq!(hours.last().unwrap().start, "2026-09-16T14:00:00Z");
    }

    /// An hour with no samples is absent from `hours`: gaps are never padded
    /// with zeroes, so the chart can tell "no data" from "no work".
    #[test]
    fn an_hour_with_no_samples_is_absent() {
        let mut h = History::default();
        h.record(t("2026-09-16T04:00:00Z"), 1, 0.0);
        h.record(t("2026-09-16T06:00:00Z"), 3, 0.0); // 05:00 skipped entirely
        let hours = h.to_wire().unwrap().hours;
        assert_eq!(hours.len(), 2);
        assert_eq!(hours[0].start, "2026-09-16T04:00:00Z");
        assert_eq!(hours[1].start, "2026-09-16T06:00:00Z");
    }

    /// Nothing recorded yet -> the wire form is `None`, so `history` is
    /// omitted from the summary entirely.
    #[test]
    fn an_empty_series_has_no_wire_form() {
        assert_eq!(History::default().to_wire(), None);
    }

    /// Round-trip through the persisted file: save, reload, identical.
    #[test]
    fn round_trips_through_the_persisted_file() {
        let dir = std::env::temp_dir().join(format!(
            "zc-history-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("history.json");

        let mut h = History::default();
        h.record(t("2026-09-16T04:00:00Z"), 5, 0.4);
        h.record(t("2026-09-16T05:00:00Z"), 12, 0.9);
        h.save(&path).unwrap();

        let reloaded = History::load(&path, t("2026-09-16T05:10:00Z"));
        assert_eq!(reloaded, h);

        std::fs::remove_dir_all(&dir).ok();
    }

    /// Buckets older than 12 hours are dropped on load (an agent that was off
    /// for a while must not resurrect ancient buckets), and a missing or
    /// corrupt file starts empty instead of failing.
    #[test]
    fn load_drops_stale_buckets_and_survives_a_bad_file() {
        let dir = std::env::temp_dir().join(format!(
            "zc-history-test-stale-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();

        let missing = dir.join("missing.json");
        assert_eq!(
            History::load(&missing, t("2026-09-16T12:00:00Z")),
            History::default()
        );

        let corrupt = dir.join("corrupt.json");
        std::fs::write(&corrupt, b"not json").unwrap();
        assert_eq!(
            History::load(&corrupt, t("2026-09-16T12:00:00Z")),
            History::default()
        );

        let mut h = History::default();
        h.record(t("2026-09-15T10:00:00Z"), 1, 0.1); // 26h ago -> dropped
        h.record(t("2026-09-16T11:00:00Z"), 2, 0.2); // 1h ago -> kept
        let stale = dir.join("stale.json");
        h.save(&stale).unwrap();
        let reloaded = History::load(&stale, t("2026-09-16T12:00:00Z"));
        let hours = reloaded.to_wire().unwrap().hours;
        assert_eq!(hours.len(), 1);
        assert_eq!(hours[0].start, "2026-09-16T11:00:00Z");

        std::fs::remove_dir_all(&dir).ok();
    }
}