zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The deployments view: every runner kind with its reservation and whether
//! it runs, is ready, or is greyed out (and why), plus what Zakuro uses of
//! each budgeted resource. The app greys out `Blocked` rows and shows the
//! budget banner when `budget_full`.

use crate::agent::hosting::Hosting;
pub use crate::agent::runners::Reservation;
use crate::agent::runners::{CatalogueEntry, RunnerKind};
pub use crate::sandbox::Limits;
use serde::Serialize;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum State {
    Running,
    Ready,
    Blocked,
    Disabled,
    Unsupported,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DeploymentView {
    pub kind: String,
    pub state: State,
    /// `budget`, `hardware`, `disabled`, `gpu-off`, `unreachable`,
    /// `owner-squads-only`.
    pub blocked_reason: Option<String>,
    pub reservation: Reservation,
    pub earnings_per_gb_week: Option<f64>,
    /// Running, but the budget has since shrunk below what runs: it takes no
    /// new jobs; nothing is killed.
    pub over_budget: bool,
}

/// What Zakuro holds of each budgeted resource (the app's bars).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
pub struct Usage {
    pub cpu_millis: u32,
    /// On unified memory this includes GPU memory.
    pub memory_bytes: u64,
    pub disk_bytes: u64,
}

impl Usage {
    fn add(&mut self, r: &Reservation, unified_memory: bool) {
        self.cpu_millis += r.cpu_millis;
        self.memory_bytes += r.memory_bytes + if unified_memory { r.vram_bytes } else { 0 };
        self.disk_bytes += r.disk_bytes;
    }

    fn within(&self, total: &Limits, disk_budget: u64) -> bool {
        self.cpu_millis <= total.cpu_millis
            && self.memory_bytes <= total.memory_bytes
            && self.disk_bytes <= disk_budget
    }
}

fn enabled(kind: RunnerKind, h: &Hosting) -> bool {
    match kind {
        RunnerKind::Spaces => h.workloads.spaces,
        RunnerKind::Environments => h.workloads.environments,
        k => k
            .atelier_backend()
            .is_some_and(|b| h.workloads.atelier.iter().any(|a| a == b)),
    }
}

/// The deployments view. `running` lists what runs now, in start order,
/// with the reservation each was started under (it may be a kind outside the
/// catalogue). CPU, memory and disk are summed against the budget; on
/// unified memory a reservation's `vram_bytes` counts as memory. On a CUDA
/// box VRAM is not summed: a GPU is passed through or not
/// (`sandbox::admit`), and the runner refuses a job its free VRAM cannot hold.
/// Returns the rows, what Zakuro uses, and whether any enabled row is
/// blocked by the budget.
pub fn view(
    cat: &[CatalogueEntry],
    h: &Hosting,
    total: &Limits,
    disk_budget_bytes: u64,
    running: &[(String, Reservation)],
    unified_memory: bool,
) -> (Vec<DeploymentView>, Usage, bool) {
    let mut usage = Usage::default();
    let mut over: Vec<&str> = Vec::new();
    for (kind, r) in running {
        usage.add(r, unified_memory);
        if !usage.within(total, disk_budget_bytes) {
            over.push(kind);
        }
    }
    let mut committed = usage;
    let mut full = false;
    let mut rows = Vec::with_capacity(cat.len());
    for e in cat {
        let id = e.kind.id();
        let row = |state, reason: Option<&str>| DeploymentView {
            kind: id.to_string(),
            state,
            blocked_reason: reason.map(String::from),
            reservation: e.reservation,
            earnings_per_gb_week: None,
            over_budget: over.contains(&id),
        };
        let is_running = running.iter().any(|(k, _)| k == id);
        rows.push(if is_running {
            row(State::Running, None)
        } else if !e.supported {
            row(State::Unsupported, Some("hardware"))
        } else if !enabled(e.kind, h) {
            row(State::Disabled, Some("disabled"))
        } else if e.kind.atelier_backend().is_some() && !h.budget.gpu {
            row(State::Disabled, Some("gpu-off"))
        } else {
            let mut next = committed;
            next.add(&e.reservation, unified_memory);
            if next.within(total, disk_budget_bytes) {
                committed = next;
                row(State::Ready, None)
            } else {
                full = true;
                row(State::Blocked, Some("budget"))
            }
        });
    }
    // A running deployment the budget no longer covers fills it too.
    (rows, usage, full || !over.is_empty())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::hosting::defaults;
    use crate::agent::runners::{catalogue, Hardware};
    use crate::sandbox::{Gpus, HostResources};

    const GIB: u64 = 1 << 30;

    fn hw(apple: bool) -> Hardware {
        Hardware {
            apple_silicon: apple,
            nvidia: if apple {
                vec![]
            } else {
                vec![crate::bench_node::fingerprint::GpuId {
                    vendor: "nvidia".into(),
                    model: "RTX".into(),
                    uuid: "g".into(),
                    vram_bytes: 11 * GIB,
                }]
            },
            host: HostResources {
                logical_cpus: 10,
                memory_bytes: Some(16 * GIB),
            },
        }
    }

    fn total(mem_gib: u64) -> Limits {
        Limits {
            cpu_millis: 8000,
            memory_bytes: mem_gib * GIB,
            gpus: Gpus::All,
        }
    }

    fn find<'a>(v: &'a [DeploymentView], kind: &str) -> &'a DeploymentView {
        v.iter().find(|d| d.kind == kind).unwrap()
    }

    fn res(mem: u64, disk: u64) -> Reservation {
        Reservation {
            cpu_millis: 1000,
            memory_bytes: mem * GIB,
            vram_bytes: 0,
            disk_bytes: disk * GIB,
        }
    }

    #[test]
    fn fits_then_greys_out_second() {
        // Linux CUDA box: peft (8 GiB) running, ludwig would add 4 GiB; a
        // 10 GiB budget leaves 2 GiB, so ludwig is blocked.
        let cat = catalogue(&hw(false));
        let mut h = defaults(&cat);
        h.workloads.spaces = false;
        h.workloads.environments = false;
        let running = vec![("atelier-peft".to_string(), cat[0].reservation)];
        let (v, _, full) = view(&cat, &h, &total(10), 100 * GIB, &running, false);
        assert_eq!(find(&v, "atelier-peft").state, State::Running);
        let l = find(&v, "atelier-ludwig");
        assert_eq!(l.state, State::Blocked);
        assert_eq!(l.blocked_reason.as_deref(), Some("budget"));
        assert!(full);
    }

    #[test]
    fn unified_memory_counts_gpu_once() {
        let cat = catalogue(&hw(true));
        let mut h = defaults(&cat);
        h.workloads.spaces = false;
        h.workloads.environments = false;
        let (v, _, full) = view(&cat, &h, &total(8), 100 * GIB, &[], true);
        assert_eq!(find(&v, "atelier-peft").state, State::Ready);
        assert!(!full);
        let running = vec![("atelier-peft".to_string(), cat[0].reservation)];
        let (_, usage, _) = view(&cat, &h, &total(8), 100 * GIB, &running, true);
        assert_eq!(usage.memory_bytes, 8 * GIB);
    }

    #[test]
    fn unified_memory_adds_vram_to_memory() {
        let cat = catalogue(&hw(true));
        let h = defaults(&cat);
        let mut r = res(4, 1);
        r.vram_bytes = 4 * GIB;
        let running = vec![("custom".to_string(), r)];
        let (_, usage, _) = view(&cat, &h, &total(8), 100 * GIB, &running, true);
        assert_eq!(usage.memory_bytes, 8 * GIB);
    }

    #[test]
    fn shrinking_budget_marks_running_over_budget() {
        let cat = catalogue(&hw(true));
        let h = defaults(&cat);
        let running = vec![("atelier-peft".to_string(), cat[0].reservation)];
        let (v, _, _) = view(&cat, &h, &total(4), 100 * GIB, &running, true);
        let p = find(&v, "atelier-peft");
        assert_eq!(p.state, State::Running);
        assert!(p.over_budget);
    }

    #[test]
    fn over_budget_running_row_fills_the_budget() {
        // Only peft enabled; the budget shrank below it: the banner shows.
        let cat = catalogue(&hw(true));
        let mut h = defaults(&cat);
        h.workloads.spaces = false;
        h.workloads.environments = false;
        let running = vec![("atelier-peft".to_string(), cat[0].reservation)];
        let (_, _, full) = view(&cat, &h, &total(4), 100 * GIB, &running, true);
        assert!(full);
    }

    #[test]
    fn disabled_and_unsupported_are_not_counted() {
        let cat = catalogue(&hw(true));
        let mut h = defaults(&cat);
        h.workloads.spaces = false;
        h.workloads.environments = false;
        let (v, usage, full) = view(&cat, &h, &total(8), 100 * GIB, &[], true);
        assert_eq!(find(&v, "spaces").state, State::Disabled);
        assert_eq!(
            find(&v, "spaces").blocked_reason.as_deref(),
            Some("disabled")
        );
        let l = find(&v, "atelier-ludwig");
        assert_eq!(l.state, State::Unsupported);
        assert_eq!(l.blocked_reason.as_deref(), Some("hardware"));
        assert_eq!(usage.memory_bytes, 0);
        assert!(!full);
    }

    #[test]
    fn disk_is_a_dimension() {
        let cat = catalogue(&hw(true));
        let mut h = defaults(&cat);
        h.workloads.spaces = false;
        h.workloads.environments = false;
        let (v, _, full) = view(&cat, &h, &total(16), 20 * GIB, &[], true);
        let p = find(&v, "atelier-peft");
        assert_eq!(p.state, State::Blocked);
        assert_eq!(p.blocked_reason.as_deref(), Some("budget"));
        assert!(full);
    }

    #[test]
    fn gpu_off_disables_atelier() {
        let cat = catalogue(&hw(true));
        let mut h = defaults(&cat);
        h.budget.gpu = false;
        let (v, _, _) = view(&cat, &h, &total(16), 100 * GIB, &[], true);
        let p = find(&v, "atelier-peft");
        assert_eq!(p.state, State::Disabled);
        assert_eq!(p.blocked_reason.as_deref(), Some("gpu-off"));
    }
}