zc2 0.0.47

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The local API's hosting views (`/v2/deployments`, `/v2/images`,
//! `/v2/hosting`), as plain functions over the catalogue, the settings and
//! the host runner's live state, so they are tested without a server.

use crate::agent::deployments::{self, DeploymentView, State};
use crate::agent::hosting::Hosting;
pub use crate::agent::runners::CatalogueEntry;
use crate::agent::runners::{Isolation, RunnerKind};
use crate::sandbox::HostResources;
use serde_json::{json, Value};

/// What the views are computed from.
pub struct Ctx<'a> {
    pub cat: &'a [CatalogueEntry],
    pub host: HostResources,
    /// Apple Silicon: GPU memory is RAM.
    pub unified: bool,
    /// Why the host runner does not serve (`hosting_loop::step`).
    pub host_reason: Option<&'a str>,
    /// The host runner is up and taking jobs.
    pub serving: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ApiErr {
    pub status: u16,
    pub code: &'static str,
    pub message: String,
}

fn err(status: u16, code: &'static str, message: impl Into<String>) -> ApiErr {
    ApiErr {
        status,
        code,
        message: message.into(),
    }
}

/// Settings the agent can act on: the budget resolves and the TTL parses.
pub fn validate(h: &Hosting) -> Result<(), String> {
    h.budget()?;
    h.idle_ttl()?;
    Ok(())
}

fn rows(
    ctx: &Ctx,
    h: &Hosting,
) -> Result<(Vec<DeploymentView>, deployments::Usage, bool, Value), String> {
    let budget = h.budget()?;
    let total = budget.total(&ctx.host)?;
    let running: Vec<(String, crate::agent::runners::Reservation)> = ctx
        .cat
        .iter()
        .filter(|e| ctx.serving && e.isolation == Isolation::Host && e.supported)
        .map(|e| (e.kind.id().to_string(), e.reservation))
        .collect();
    let (mut rows, usage, full) =
        deployments::view(ctx.cat, h, &total, budget.disk_bytes, &running, ctx.unified);
    // A host runner that would fit but cannot serve says why.
    for r in rows.iter_mut() {
        let host = ctx
            .cat
            .iter()
            .any(|e| e.kind.id() == r.kind && e.isolation == Isolation::Host);
        if host && r.state == State::Ready {
            if let Some(reason) = ctx.host_reason {
                r.state = State::Blocked;
                r.blocked_reason = Some(reason.to_string());
            }
        }
    }
    let budget_json = json!({
        "cpu_millis": total.cpu_millis,
        "memory_bytes": total.memory_bytes,
        "disk_bytes": budget.disk_bytes,
        "gpu": h.budget.gpu,
    });
    Ok((rows, usage, full, budget_json))
}

/// Why this machine may not be earning, most actionable first. The app
/// shows it when the week's earnings are zero. (`price-above-market` needs
/// market data the agent does not have yet.)
pub fn not_earning_reason(
    ctx: &Ctx,
    rows: &[DeploymentView],
    budget_full: bool,
) -> Option<&'static str> {
    if ctx.host_reason == Some("unreachable") {
        return Some("tunnel-offline");
    }
    if budget_full {
        return Some("budget-full");
    }
    let live = |r: &&DeploymentView| matches!(r.state, State::Ready | State::Running);
    if !rows.iter().any(|r| live(&r)) {
        return Some("nothing-enabled");
    }
    // Host runners serve the owner's own jobs only (no public squad yet).
    let host_live = rows.iter().filter(live).any(|r| {
        ctx.cat
            .iter()
            .any(|e| e.kind.id() == r.kind && e.isolation == Isolation::Host)
    });
    host_live.then_some("owner-squads-only")
}

/// `GET /v2/deployments`.
pub fn deployments(ctx: &Ctx, h: &Hosting) -> Result<Value, String> {
    let (rows, usage, full, budget) = rows(ctx, h)?;
    let reason = not_earning_reason(ctx, &rows, full);
    Ok(json!({
        "deployments": rows,
        "usage": usage,
        "budget": budget,
        "budget_full": full,
        "unified_memory": ctx.unified,
        "not_earning_reason": reason,
    }))
}

/// `PUT /v2/deployments/{kind}`: the new settings, or why not. Enabling
/// something that would not fit the budget is refused (409 `budget`).
pub fn set_enabled(ctx: &Ctx, h: &Hosting, kind: &str, on: bool) -> Result<Hosting, ApiErr> {
    let k = RunnerKind::from_id(kind)
        .ok_or_else(|| err(404, "not_found", format!("no runner kind {kind:?}")))?;
    let entry = ctx
        .cat
        .iter()
        .find(|e| e.kind == k)
        .ok_or_else(|| err(404, "not_found", format!("no runner kind {kind:?}")))?;
    if on && !entry.supported {
        return Err(err(
            409,
            "hardware",
            format!(
                "this machine cannot run {kind} ({})",
                entry.reason.unwrap_or("unsupported")
            ),
        ));
    }
    let mut next = h.clone();
    match k {
        RunnerKind::Spaces => next.workloads.spaces = on,
        RunnerKind::Environments => next.workloads.environments = on,
        _ => {
            let b = k.atelier_backend().expect("atelier kind").to_string();
            next.workloads.atelier.retain(|a| *a != b);
            if on {
                next.workloads.atelier.push(b);
            }
        }
    }
    if on {
        let (rows, ..) = rows(ctx, &next).map_err(|e| err(400, "invalid_input", e))?;
        if rows
            .iter()
            .any(|r| r.kind == kind && r.blocked_reason.as_deref() == Some("budget"))
        {
            return Err(err(
                409,
                "budget",
                "This Mac can't host more deployments within Zakuro's resource limit. Raise the limit or remove one.",
            ));
        }
    }
    Ok(next)
}

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

    fn host() -> HostResources {
        HostResources {
            logical_cpus: 10,
            memory_bytes: Some(16 << 30),
        }
    }

    fn mac() -> Vec<CatalogueEntry> {
        catalogue(&Hardware {
            apple_silicon: true,
            nvidia: vec![],
            host: host(),
        })
    }

    fn ctx<'a>(cat: &'a [CatalogueEntry], reason: Option<&'a str>, serving: bool) -> Ctx<'a> {
        Ctx {
            cat,
            host: host(),
            unified: true,
            host_reason: reason,
            serving,
        }
    }

    #[test]
    fn enable_over_budget_is_409() {
        let cat = mac();
        let mut h = defaults(&cat);
        h.budget.memory = "9g".into();
        h.workloads.spaces = false;
        h.workloads.environments = false;
        // peft (8 GiB) runs; spaces (2 GiB) would not fit in 9 GiB.
        let e = set_enabled(&ctx(&cat, None, true), &h, "spaces", true).unwrap_err();
        assert_eq!((e.status, e.code), (409, "budget"));
        let ok = set_enabled(&ctx(&cat, None, true), &h, "spaces", false).unwrap();
        assert!(!ok.workloads.spaces);
    }

    #[test]
    fn enabling_unsupported_or_unknown_kind_is_refused() {
        let cat = mac();
        let h = defaults(&cat);
        let e = set_enabled(&ctx(&cat, None, false), &h, "atelier-ludwig", true).unwrap_err();
        assert_eq!((e.status, e.code), (409, "hardware"));
        let e = set_enabled(&ctx(&cat, None, false), &h, "nope", true).unwrap_err();
        assert_eq!((e.status, e.code), (404, "not_found"));
    }

    #[test]
    fn disabling_atelier_removes_the_backend() {
        let cat = mac();
        let h = defaults(&cat);
        let h = set_enabled(&ctx(&cat, None, false), &h, "atelier-peft", false).unwrap();
        assert!(h.workloads.atelier.is_empty());
        let h = set_enabled(&ctx(&cat, None, false), &h, "atelier-peft", true).unwrap();
        assert_eq!(h.workloads.atelier, vec!["peft".to_string()]);
    }

    #[test]
    fn not_earning_reason_prefers_tunnel() {
        let cat = mac();
        let h = defaults(&cat);
        let v = deployments(&ctx(&cat, Some("unreachable"), false), &h).unwrap();
        assert_eq!(v["not_earning_reason"], "tunnel-offline");
        let peft = v["deployments"]
            .as_array()
            .unwrap()
            .iter()
            .find(|d| d["kind"] == "atelier-peft")
            .unwrap();
        assert_eq!(peft["state"], "blocked");
        assert_eq!(peft["blocked_reason"], "unreachable");
    }

    #[test]
    fn not_earning_reason_order() {
        let cat = mac();
        let mut h = defaults(&cat);
        h.budget.memory = "1g".into();
        let v = deployments(&ctx(&cat, None, false), &h).unwrap();
        assert_eq!(v["not_earning_reason"], "budget-full");
        assert_eq!(v["budget_full"], true);

        let mut h = defaults(&cat);
        h.workloads = crate::agent::hosting::Workloads {
            atelier: vec![],
            spaces: false,
            environments: false,
        };
        let v = deployments(&ctx(&cat, None, false), &h).unwrap();
        assert_eq!(v["not_earning_reason"], "nothing-enabled");

        // On a 16 GB Mac the default 50% budget is all taken by peft, so
        // Spaces/Environments are greyed out (budget-full); with them off,
        // the remaining reason is the owner-only scope.
        let mut h = defaults(&cat);
        h.workloads.spaces = false;
        h.workloads.environments = false;
        let v = deployments(&ctx(&cat, None, true), &h).unwrap();
        assert_eq!(v["not_earning_reason"], "owner-squads-only");
    }

    #[test]
    fn usage_and_budget_are_reported() {
        let cat = mac();
        let h = defaults(&cat);
        let v = deployments(&ctx(&cat, None, true), &h).unwrap();
        assert_eq!(v["usage"]["memory_bytes"], 8u64 << 30);
        assert_eq!(v["budget"]["memory_bytes"], 8u64 << 30);
        assert_eq!(v["budget"]["disk_bytes"], 50u64 << 30);
        assert_eq!(v["unified_memory"], true);
    }

    #[test]
    fn hosting_put_roundtrips() {
        let cat = mac();
        let mut h = defaults(&cat);
        h.cleanup.idle_ttl = "3d".into();
        assert!(validate(&h).is_ok());
        h.cleanup.idle_ttl = "soon".into();
        assert!(validate(&h).unwrap_err().contains("idle_ttl"));
        let mut h = defaults(&cat);
        h.budget.disk = "50%".into();
        assert!(validate(&h).unwrap_err().contains("disk"));
    }
}