use super::{Atelier, MinPrice, Policy, PUBLIC_SQUAD};
use crate::hub_allocation::HubAllocation;
use serde::Deserialize;
use std::path::Path;
#[derive(Debug, Default, Clone)]
pub struct Legacy {
pub p2p_env: Option<String>,
pub spaces: Option<(bool, Option<f64>)>,
pub hub_allocation: Option<HubAllocation>,
pub hosting_toml: Option<String>,
}
impl Legacy {
pub fn read(home: &Path, get: &dyn Fn(&str) -> Option<String>) -> Self {
let spaces_file = home.join("spaces").join("settings.json");
Self {
p2p_env: get("ZAKURO_P2P").filter(|v| !v.trim().is_empty()),
spaces: spaces_file.exists().then(|| {
let s = crate::spaces::read_settings(home);
(s.enabled, s.min_price_per_hour)
}),
hub_allocation: crate::hub_allocation::load(home),
hosting_toml: std::fs::read_to_string(hosting_path(home)).ok(),
}
}
}
fn hosting_path(home: &Path) -> std::path::PathBuf {
home.join("agent").join("hosting.toml")
}
fn gb(n: u64) -> String {
format!("{n}G")
}
pub fn from_legacy(l: &Legacy) -> Result<Policy, String> {
let mut p = Policy::default();
if let Some(text) = &l.hosting_toml {
apply_hosting(&mut p, text).map_err(|e| format!("agent/hosting.toml: {e}"))?;
}
if let Some((enabled, price)) = l.spaces {
p.workloads.spaces = enabled;
if enabled {
if let Some(m) = price {
p.sharing.min_price = MinPrice::PerHour(m);
}
}
}
if let Some(a) = &l.hub_allocation {
p.workloads.hub_serving = a.enabled;
if a.enabled {
if a.ram_gb > 0 {
p.budget.memory = gb(a.ram_gb);
}
if a.vram_gb > 0 {
p.budget.vram = gb(a.vram_gb);
p.budget.gpu = true;
}
if a.disk_gb > 0 {
p.budget.disk = gb(a.disk_gb);
}
}
}
if let Some(v) = &l.p2p_env {
if p2p_is_off(v) {
p.sharing.squads = Vec::new();
}
}
p.validate()
.map_err(|e| format!("the migrated policy is invalid: {e}"))?;
Ok(p)
}
pub fn p2p_is_off(v: &str) -> bool {
!(v == "true" || v == "1")
}
fn apply_hosting(p: &mut Policy, text: &str) -> Result<(), String> {
let h: HostingV1 = toml::from_str(text).map_err(|e| e.to_string())?;
p.budget.cpu = h.budget.cpu;
p.budget.memory = h.budget.memory;
p.budget.gpu = h.budget.gpu;
p.budget.disk = h.budget.disk;
p.budget.on_ac_only = h.budget.on_ac_only;
p.workloads.spaces = h.workloads.spaces;
p.workloads.environments = h.workloads.environments;
p.workloads.atelier = if h.workloads.atelier.is_empty() {
Atelier::Off
} else {
Atelier::Backends(h.workloads.atelier)
};
p.sharing.when = h.sharing.when;
p.sharing.squads = h
.sharing
.sources
.into_iter()
.map(|s| {
if s == "hub" {
PUBLIC_SQUAD.to_string()
} else {
s
}
})
.collect();
p.cleanup.idle_ttl = h.cleanup.idle_ttl;
Ok(())
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HostingV1 {
budget: HostingBudget,
workloads: HostingWorkloads,
sharing: HostingSharing,
cleanup: HostingCleanup,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HostingBudget {
cpu: String,
memory: String,
gpu: bool,
disk: String,
on_ac_only: bool,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HostingWorkloads {
atelier: Vec<String>,
spaces: bool,
environments: bool,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HostingSharing {
when: String,
sources: Vec<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HostingCleanup {
idle_ttl: String,
}
pub fn retire_hosting_toml(home: &Path) {
let p = hosting_path(home);
if p.exists() {
let _ = std::fs::rename(&p, p.with_extension("toml.migrated"));
}
}
fn deprecated(old: &str, new: &str) {
eprintln!(" note: `{old}` is deprecated; it now edits policy.toml. Use `{new}`.");
}
pub fn alias_spaces(home: &Path, enabled: bool, min_price: Option<f64>) -> Result<(), String> {
deprecated(
if enabled {
"zc spaces enable"
} else {
"zc spaces disable"
},
"zc policy set workloads.spaces=true|false",
);
super::update(home, None, None, |p| {
p.workloads.spaces = enabled;
if let (true, Some(m)) = (enabled, min_price) {
p.sharing.min_price = MinPrice::PerHour(m);
}
Ok(())
})
.map(|_| ())
.map_err(|e| e.to_string())
}
pub fn alias_hub_allocation(home: &Path, a: Option<&HubAllocation>) -> Result<(), String> {
deprecated(
"zc hub allocate",
"zc policy set workloads.hub_serving=true|false (sizes: zc budget)",
);
super::update(home, None, None, |p| {
match a {
Some(a) if a.enabled => {
p.workloads.hub_serving = true;
if a.ram_gb > 0 {
p.budget.memory = gb(a.ram_gb);
}
if a.vram_gb > 0 {
p.budget.vram = gb(a.vram_gb);
p.budget.gpu = true;
}
if a.disk_gb > 0 {
p.budget.disk = gb(a.disk_gb);
}
}
_ => p.workloads.hub_serving = false,
}
Ok(())
})
.map(|_| ())
.map_err(|e| e.to_string())
}
pub fn alias_p2p(home: &Path, value: &str) {
deprecated("ZAKURO_P2P", "zc policy set sharing.squads=[]|public");
if !p2p_is_off(value) {
return;
}
if let Err(e) = super::update(home, None, None, |p| {
p.sharing.squads = Vec::new();
Ok(())
}) {
eprintln!(" [POLICY] ZAKURO_P2P=0 could not be applied: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hub(enabled: bool, vram: u64, ram: u64, disk: u64) -> HubAllocation {
HubAllocation {
enabled,
vram_gb: vram,
ram_gb: ram,
disk_gb: disk,
purpose: vec!["inference".into()],
}
}
#[test]
fn nothing_set_gives_the_defaults() {
assert_eq!(from_legacy(&Legacy::default()).unwrap(), Policy::default());
}
#[test]
fn explicit_p2p_off_closes_the_node_and_on_does_not() {
for off in ["0", "false", "no"] {
let p = from_legacy(&Legacy {
p2p_env: Some(off.into()),
..Default::default()
})
.unwrap();
assert!(p.sharing.squads.is_empty(), "{off}");
}
for on in ["1", "true"] {
let p = from_legacy(&Legacy {
p2p_env: Some(on.into()),
..Default::default()
})
.unwrap();
assert_eq!(p.sharing.squads, vec!["public".to_string()], "{on}");
}
}
#[test]
fn spaces_enabled_keeps_its_price_and_disabled_stays_off() {
let p = from_legacy(&Legacy {
spaces: Some((true, Some(2.5))),
..Default::default()
})
.unwrap();
assert!(p.workloads.spaces);
assert_eq!(p.sharing.min_price, MinPrice::PerHour(2.5));
let p = from_legacy(&Legacy {
spaces: Some((false, Some(2.5))),
..Default::default()
})
.unwrap();
assert!(!p.workloads.spaces);
assert_eq!(p.sharing.min_price, MinPrice::Default);
}
#[test]
fn hub_allocation_moves_its_slice_into_the_budget() {
let p = from_legacy(&Legacy {
hub_allocation: Some(hub(true, 8, 16, 100)),
..Default::default()
})
.unwrap();
assert!(p.workloads.hub_serving);
assert_eq!(
(
p.budget.memory.as_str(),
p.budget.vram.as_str(),
p.budget.disk.as_str()
),
("16G", "8G", "100G")
);
assert!(p.budget.gpu, "lent VRAM implies a GPU budget");
let p = from_legacy(&Legacy {
hub_allocation: Some(hub(false, 8, 16, 100)),
..Default::default()
})
.unwrap();
assert!(!p.workloads.hub_serving);
assert_eq!(p.budget.memory, "50%", "a disabled slice moves nothing");
}
#[test]
fn hosting_toml_sections_move_over_and_explicit_switches_win() {
let hosting = r#"
[budget]
cpu = "25%"
memory = "6g"
gpu = true
disk = "80G"
on_ac_only = false
[workloads]
atelier = ["peft"]
spaces = false
environments = true
[sharing]
when = "always"
sources = ["hub", "lab"]
[cleanup]
idle_ttl = "3d"
"#;
let p = from_legacy(&Legacy {
hosting_toml: Some(hosting.into()),
spaces: Some((true, None)),
..Default::default()
})
.unwrap();
assert_eq!(p.budget.cpu, "25%");
assert_eq!(p.budget.memory, "6g");
assert!(p.budget.gpu && !p.budget.on_ac_only);
assert_eq!(p.budget.disk, "80G");
assert_eq!(p.workloads.atelier, Atelier::Backends(vec!["peft".into()]));
assert!(
p.workloads.spaces,
"the explicit Spaces opt-in beats hosting.toml"
);
assert_eq!(p.sharing.when, "always");
assert_eq!(
p.sharing.squads,
vec!["public".to_string(), "lab".to_string()]
);
assert_eq!(p.cleanup.idle_ttl, "3d");
}
#[test]
fn a_hosting_toml_that_does_not_parse_is_an_error_naming_the_key() {
let e = from_legacy(&Legacy {
hosting_toml: Some("[budget]\nfoo = 1\n".into()),
..Default::default()
})
.unwrap_err();
assert!(e.contains("foo"), "{e}");
}
#[test]
fn first_load_migrates_from_the_files_on_disk_once() {
let home = super::super::test_home();
std::fs::create_dir_all(home.join("spaces")).unwrap();
std::fs::write(
home.join("spaces/settings.json"),
r#"{"enabled": true, "min_price_per_hour": 4.0}"#,
)
.unwrap();
std::fs::create_dir_all(home.join("agent")).unwrap();
std::fs::write(
home.join("agent/hosting.toml"),
"[budget]\ncpu = \"50%\"\nmemory = \"50%\"\ngpu = false\ndisk = \"50G\"\non_ac_only = true\n\
[workloads]\natelier = []\nspaces = true\nenvironments = true\n\
[sharing]\nwhen = \"idle\"\nsources = [\"hub\"]\n[cleanup]\nidle_ttl = \"2d\"\n",
)
.unwrap();
let p = super::super::load(&home).unwrap();
assert_eq!(p.sharing.min_price, MinPrice::PerHour(4.0));
assert_eq!(p.cleanup.idle_ttl, "2d");
assert_eq!(p.workloads.atelier, Atelier::Off);
assert!(!home.join("agent/hosting.toml").exists(), "retired");
assert!(home.join("agent/hosting.toml.migrated").exists());
std::fs::write(home.join("spaces/settings.json"), r#"{"enabled": false}"#).unwrap();
assert_eq!(super::super::load(&home).unwrap(), p);
}
#[test]
fn the_aliases_edit_the_policy() {
let home = super::super::test_home();
super::super::load(&home).unwrap();
alias_spaces(&home, false, None).unwrap();
assert!(!super::super::load(&home).unwrap().workloads.spaces);
alias_spaces(&home, true, Some(1.5)).unwrap();
let p = super::super::load(&home).unwrap();
assert!(p.workloads.spaces);
assert_eq!(p.sharing.min_price, MinPrice::PerHour(1.5));
alias_hub_allocation(&home, Some(&hub(true, 0, 8, 40))).unwrap();
let p = super::super::load(&home).unwrap();
assert!(p.workloads.hub_serving);
assert_eq!(p.budget.memory, "8G");
alias_hub_allocation(&home, None).unwrap();
assert!(!super::super::load(&home).unwrap().workloads.hub_serving);
alias_p2p(&home, "1");
assert!(!super::super::load(&home).unwrap().sharing.squads.is_empty());
alias_p2p(&home, "0");
assert!(super::super::load(&home).unwrap().sharing.squads.is_empty());
super::super::update(&home, None, None, |p| {
p.sharing.squads = Vec::new();
Ok(())
})
.unwrap();
alias_p2p(&home, "1");
assert!(super::super::load(&home).unwrap().sharing.squads.is_empty());
}
}