zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! The first-load migration (ADR ZC-0017 ยง6) and the deprecated switches
//! that now edit the policy.
//!
//! A node without `policy.toml` gets one generated from what it already has,
//! so an owner's explicit choice survives the upgrade:
//!
//! - explicit `ZAKURO_P2P=0` -> `squads = []`;
//! - Spaces enabled (`spaces/settings.json`) -> `spaces = true` and its
//!   minimum price; `zc spaces disable` -> `spaces = false`;
//! - hub allocation enabled -> `hub_serving = true`, its RAM / VRAM / disk
//!   into `[budget]`; a disabled one -> `hub_serving = false`;
//! - an `agent/hosting.toml` (zc#575) -> its sections moved over unchanged;
//! - nothing of that -> the ADR defaults.

use super::{Atelier, MinPrice, Policy, PUBLIC_SQUAD};
use crate::hub_allocation::HubAllocation;
use serde::Deserialize;
use std::path::Path;

/// What the old switches say, gathered once.
#[derive(Debug, Default, Clone)]
pub struct Legacy {
    pub p2p_env: Option<String>,
    /// `(enabled, min price)` from `spaces/settings.json`, when it exists.
    pub spaces: Option<(bool, Option<f64>)>,
    pub hub_allocation: Option<HubAllocation>,
    /// The text of `agent/hosting.toml`, when it exists.
    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)
}

/// The broker's reading of `ZAKURO_P2P`: `true` or `1` is on, anything else off.
pub fn p2p_is_off(v: &str) -> bool {
    !(v == "true" || v == "1")
}

/// zc#575's `hosting.toml` v1: the same section and key names as policy.toml,
/// but `workloads.atelier` is a list and `sharing.sources` names squads or
/// `hub`. Moved over unchanged (ADR 0017 ยง6).
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(())
}

// The shape of the file zc#575 wrote, parsed here (the agent is not built on
// every platform the broker is).
#[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,
}

/// Its content now lives in policy.toml: keep the file, under another name, so
/// nothing reads two sources.
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"));
    }
}

// ---- the deprecated switches, as aliases ---------------------------------------

fn deprecated(old: &str, new: &str) {
    eprintln!("  note: `{old}` is deprecated; it now edits policy.toml. Use `{new}`.");
}

/// `zc spaces enable|disable` -> `workloads.spaces` (and the minimum price).
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())
}

/// `zc hub allocate --enable|--disable` -> `workloads.hub_serving` and the
/// RAM / VRAM / disk of `[budget]`.
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())
}

/// An explicit `ZAKURO_P2P`: `0` closes the node to foreign work
/// (`squads = []`); `1` changes nothing, because opening a node the owner
/// closed is not something a stale environment variable may do.
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();
        // hosting.toml needs every section (zc#575's struct has no defaults).
        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());
        // A second load reads the file; changing the old inputs changes nothing.
        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);
        // ZAKURO_P2P=1 never opens a node the owner closed; =0 closes it.
        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());
    }
}