zc2 0.0.38

P2P compute broker with credit-based 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
//! What the Mesh tab shows, as plain data: nodes, each with the workers this
//! machine's broker knows, built from the same listing `zc ls` prints.

use crate::{ListedBroker, Listing};
use std::collections::{BTreeMap, HashSet};

#[derive(Debug, Clone, PartialEq)]
pub struct MeshWorker {
    pub name: String,
    pub status: String,
    pub cpus: f64,
    pub gpus: u32,
    pub mem_total_gib: f64,
    pub mem_avail_gib: f64,
    pub price_per_hour: f64,
    pub cpu_model: Option<String>,
    pub gpu_model: Option<String>,
    pub gpu_vram_gb: Option<u64>,
    pub storage_gb: Option<u64>,
    pub python: Option<String>,
    pub served_models: Vec<String>,
    pub requests_5h: u64,
    pub requests_1w: u64,
}

impl MeshWorker {
    /// One entry of the broker's `GET /workers` (`WorkerInfo`).
    pub fn from_json(w: &serde_json::Value) -> Self {
        let f = |k: &str| w.get(k).and_then(|v| v.as_f64());
        let s = |k: &str| w.get(k).and_then(|v| v.as_str()).map(str::to_string);
        let u = |k: &str| w.get(k).and_then(|v| v.as_u64());
        MeshWorker {
            name: s("name").unwrap_or_else(|| "?".into()),
            // The broker's word is `healthy`; the question a list answers is
            // whether the worker will take work.
            status: match s("status").as_deref() {
                Some("healthy") => "ready".into(),
                Some(other) => other.into(),
                None => "?".into(),
            },
            cpus: f("cpus_total")
                .or_else(|| f("cpus_available"))
                .unwrap_or(0.0),
            gpus: u("gpus_total").or_else(|| u("gpus_available")).unwrap_or(0) as u32,
            mem_total_gib: f("memory_total_gib").unwrap_or(0.0),
            mem_avail_gib: f("memory_available_gib").unwrap_or(0.0),
            price_per_hour: f("price_per_hour").unwrap_or(0.0),
            cpu_model: s("cpu_model"),
            gpu_model: s("gpu_model"),
            gpu_vram_gb: u("gpu_vram_gb"),
            storage_gb: u("storage_gb"),
            python: s("python_version"),
            served_models: w
                .get("served_models")
                .and_then(|v| v.as_array())
                .map(|a| {
                    a.iter()
                        .filter_map(|m| {
                            m.as_str().map(str::to_string).or_else(|| {
                                m.get("name").and_then(|n| n.as_str()).map(str::to_string)
                            })
                        })
                        .collect()
                })
                .unwrap_or_default(),
            requests_5h: u("requests_5h").unwrap_or(0),
            requests_1w: u("requests_1w").unwrap_or(0),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct MeshNode {
    /// Key-derived fingerprint, without the `zc://node-` prefix.
    pub fp: String,
    pub name: Option<String>,
    pub is_self: bool,
    pub workers: Vec<MeshWorker>,
}

impl MeshNode {
    /// The address work is dispatched to. Workers bind loopback and are not
    /// addressable; the node is.
    pub fn address(&self) -> String {
        format!("zc://node-{}", self.fp)
    }
    pub fn label(&self) -> String {
        let name = self.name.clone().unwrap_or_else(|| "-".into());
        match self.is_self {
            true => format!("{name} (this machine)"),
            false => name,
        }
    }
    pub fn total_cpus(&self) -> f64 {
        self.workers.iter().map(|w| w.cpus).sum()
    }
    pub fn total_gpus(&self) -> u32 {
        self.workers.iter().map(|w| w.gpus).sum()
    }
    pub fn total_mem_gib(&self) -> f64 {
        self.workers.iter().map(|w| w.mem_total_gib).sum()
    }
    /// Lowest and highest worker price; `None` without workers.
    pub fn price_range(&self) -> Option<(f64, f64)> {
        let mut p: Vec<f64> = self.workers.iter().map(|w| w.price_per_hour).collect();
        p.sort_by(|a, b| a.total_cmp(b));
        Some((*p.first()?, *p.last()?))
    }
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct MeshSnapshot {
    pub nodes: Vec<MeshNode>,
    /// Why this is only this machine's view, when the hub was unavailable.
    pub local_only: Option<String>,
    pub unreachable: usize,
    pub offline: usize,
    /// Age of the broker list when it came from the cache.
    pub as_of_secs: Option<u64>,
    /// Why the local broker's workers could not be read, if they could not.
    pub workers_error: Option<String>,
}

impl MeshSnapshot {
    pub fn from_listing(
        brokers: &[ListedBroker],
        listing: &Listing,
        workers: &[serde_json::Value],
        workers_error: Option<String>,
    ) -> Self {
        let mut by_fp: BTreeMap<String, Vec<MeshWorker>> = BTreeMap::new();
        for w in workers {
            if let Some(fp) = crate::worker_node_fp(w) {
                by_fp.entry(fp).or_default().push(MeshWorker::from_json(w));
            }
        }
        match listing {
            Listing::Directory {
                unreachable,
                offline,
                as_of_secs,
            } => MeshSnapshot {
                nodes: brokers
                    .iter()
                    .map(|b| MeshNode {
                        fp: b.fp.clone(),
                        name: b.name.clone(),
                        is_self: b.is_self,
                        workers: by_fp.get(&b.fp).cloned().unwrap_or_default(),
                    })
                    .collect(),
                local_only: None,
                unreachable: *unreachable,
                offline: *offline,
                as_of_secs: *as_of_secs,
                workers_error,
            },
            Listing::LocalOnly(why) => MeshSnapshot {
                nodes: by_fp
                    .into_iter()
                    .map(|(fp, workers)| MeshNode {
                        fp,
                        name: None,
                        is_self: false,
                        workers,
                    })
                    .collect(),
                local_only: Some(why.clone()),
                workers_error,
                ..Default::default()
            },
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sort {
    Price,
    Cpus,
    Name,
}

impl Sort {
    pub fn next(self) -> Sort {
        match self {
            Sort::Price => Sort::Cpus,
            Sort::Cpus => Sort::Name,
            Sort::Name => Sort::Price,
        }
    }
    pub fn title(self) -> &'static str {
        match self {
            Sort::Price => "price",
            Sort::Cpus => "CPUs",
            Sort::Name => "name",
        }
    }
}

/// One line of the Mesh list: a node, or a worker under it (indices into
/// `MeshSnapshot::nodes` and that node's `workers`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowRef {
    Node(usize),
    Worker(usize, usize),
}

/// The rows the list shows, in order. Nodes with workers come before the
/// ones this machine has no worker detail for, then `sort` orders each
/// half. A non-empty `filter` (case-insensitive substring of a name or an
/// address) keeps matching nodes and workers and opens their nodes; with no
/// filter, a node's workers show when its fingerprint is in `expanded`.
pub fn visible_rows(
    snap: &MeshSnapshot,
    expanded: &HashSet<String>,
    filter: &str,
    sort: Sort,
) -> Vec<RowRef> {
    let needle = filter.to_lowercase();
    let hit = |s: &str| s.to_lowercase().contains(&needle);
    let mut order: Vec<usize> = (0..snap.nodes.len()).collect();
    let key_name = |i: usize| {
        snap.nodes[i]
            .name
            .clone()
            .unwrap_or_else(|| snap.nodes[i].fp.clone())
    };
    order.sort_by(|&a, &b| {
        let (na, nb) = (&snap.nodes[a], &snap.nodes[b]);
        na.workers
            .is_empty()
            .cmp(&nb.workers.is_empty())
            .then_with(|| match sort {
                Sort::Price => {
                    let pa = na.price_range().map(|p| p.0).unwrap_or(f64::MAX);
                    let pb = nb.price_range().map(|p| p.0).unwrap_or(f64::MAX);
                    pa.total_cmp(&pb)
                }
                Sort::Cpus => nb.total_cpus().total_cmp(&na.total_cpus()),
                Sort::Name => std::cmp::Ordering::Equal,
            })
            .then_with(|| key_name(a).cmp(&key_name(b)))
    });
    let mut rows = Vec::new();
    for i in order {
        let node = &snap.nodes[i];
        let mut workers: Vec<usize> = (0..node.workers.len()).collect();
        workers.sort_by(|&a, &b| {
            let (wa, wb) = (&node.workers[a], &node.workers[b]);
            match sort {
                Sort::Price => wa.price_per_hour.total_cmp(&wb.price_per_hour),
                Sort::Cpus => wb.cpus.total_cmp(&wa.cpus),
                Sort::Name => std::cmp::Ordering::Equal,
            }
            .then_with(|| wa.name.cmp(&wb.name))
        });
        if needle.is_empty() {
            rows.push(RowRef::Node(i));
            if expanded.contains(&node.fp) {
                rows.extend(workers.into_iter().map(|j| RowRef::Worker(i, j)));
            }
            continue;
        }
        let node_hit = hit(&node.fp) || node.name.as_deref().is_some_and(hit);
        let shown: Vec<usize> = workers
            .into_iter()
            .filter(|&j| node_hit || hit(&node.workers[j].name))
            .collect();
        if node_hit || !shown.is_empty() {
            rows.push(RowRef::Node(i));
            rows.extend(shown.into_iter().map(|j| RowRef::Worker(i, j)));
        }
    }
    rows
}

/// A price per hour as a list shows it: `free`, or the number without
/// trailing zeros.
pub fn price_text(p: f64) -> String {
    if p <= 0.0 {
        "free".into()
    } else if p.fract() == 0.0 {
        format!("{p:.0}")
    } else {
        format!("{p}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ListedBroker, Listing};
    use serde_json::json;

    fn w(name: &str, fp: &str, cpus: f64, price: f64) -> serde_json::Value {
        json!({"name": name, "node": format!("zc://node-{fp}"), "status": "healthy",
               "cpus_total": cpus, "gpus_total": 0, "memory_total_gib": 16.0,
               "memory_available_gib": 4.0, "price_per_hour": price})
    }
    fn b(fp: &str, name: &str) -> ListedBroker {
        ListedBroker {
            fp: fp.into(),
            name: Some(name.into()),
            is_self: false,
        }
    }
    fn dir() -> Listing {
        Listing::Directory {
            unreachable: 1,
            offline: 2,
            as_of_secs: Some(40),
        }
    }

    #[test]
    fn workers_group_under_their_node_and_healthy_reads_ready() {
        let s = MeshSnapshot::from_listing(
            &[b("aaaa", "i9"), b("bbbb", "x399")],
            &dir(),
            &[w("i9-w0", "aaaa", 20.0, 3.6), w("x-w0", "bbbb", 32.0, 2.0)],
            None,
        );
        assert_eq!(s.nodes.len(), 2);
        assert_eq!(s.nodes[0].workers[0].status, "ready");
        assert_eq!(s.nodes[0].address(), "zc://node-aaaa");
        assert_eq!((s.unreachable, s.offline, s.as_of_secs), (1, 2, Some(40)));
    }

    #[test]
    fn a_local_only_listing_groups_by_worker_node() {
        let s = MeshSnapshot::from_listing(
            &[],
            &Listing::LocalOnly("hub unavailable".into()),
            &[w("a", "cccc", 1.0, 1.0), w("b", "cccc", 1.0, 1.0)],
            None,
        );
        assert_eq!(s.local_only.as_deref(), Some("hub unavailable"));
        assert_eq!(s.nodes.len(), 1);
        assert_eq!(s.nodes[0].workers.len(), 2);
    }

    #[test]
    fn nodes_with_workers_come_first_then_sort_applies() {
        let s = MeshSnapshot::from_listing(
            &[
                b("empty", "zz-broker"),
                b("aaaa", "pricey"),
                b("bbbb", "cheap"),
            ],
            &dir(),
            &[w("p", "aaaa", 8.0, 9.0), w("c", "bbbb", 64.0, 1.0)],
            None,
        );
        let rows = visible_rows(&s, &HashSet::new(), "", Sort::Price);
        assert_eq!(
            rows,
            vec![RowRef::Node(2), RowRef::Node(1), RowRef::Node(0)]
        );
        let rows = visible_rows(&s, &HashSet::new(), "", Sort::Cpus);
        assert_eq!(rows[0], RowRef::Node(2)); // 64 CPUs first
    }

    #[test]
    fn expanded_nodes_show_their_workers() {
        let s = MeshSnapshot::from_listing(
            &[b("aaaa", "i9")],
            &dir(),
            &[w("w0", "aaaa", 1.0, 1.0), w("w1", "aaaa", 2.0, 1.0)],
            None,
        );
        let mut open = HashSet::new();
        open.insert("aaaa".to_string());
        let rows = visible_rows(&s, &open, "", Sort::Name);
        assert_eq!(
            rows,
            vec![RowRef::Node(0), RowRef::Worker(0, 0), RowRef::Worker(0, 1)]
        );
    }

    #[test]
    fn a_filter_keeps_matching_nodes_and_workers_case_insensitively() {
        let s = MeshSnapshot::from_listing(
            &[b("aaaa", "i9"), b("bbbb", "x399")],
            &dir(),
            &[
                w("gpu-04", "aaaa", 1.0, 1.0),
                w("cpu-01", "aaaa", 1.0, 1.0),
                w("w", "bbbb", 1.0, 1.0),
            ],
            None,
        );
        let rows = visible_rows(&s, &HashSet::new(), "GPU", Sort::Name);
        assert_eq!(rows, vec![RowRef::Node(0), RowRef::Worker(0, 0)]);
        let rows = visible_rows(&s, &HashSet::new(), "x399", Sort::Name);
        assert_eq!(rows, vec![RowRef::Node(1), RowRef::Worker(1, 0)]);
    }

    #[test]
    fn prices_read_free_or_trimmed() {
        assert_eq!(price_text(0.0), "free");
        assert_eq!(price_text(38.0), "38");
        assert_eq!(price_text(3.6), "3.6");
    }
}