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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Per-Space container runner. One container per active Space: pulled by
//! digest, started with the broker socket bind-mounted, fed leases through
//! the socket API. The broker owns the lease: it heartbeats while a batch
//! runs, abandons it on expiry, and signs the receipt itself.

use std::collections::{BTreeMap, HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use serde_json::{json, Value};

use super::client::{Completion, Hub, Lease};
use super::receipt;
use super::socket;
use super::Stats;
use crate::broker::deploy::{ContainerRuntime, RunSpec};
use crate::broker::node_identity::NodeKey;

/// Path of the socket inside the container.
pub const CONTAINER_SOCKET: &str = "/run/zakuro/space.sock";
/// At most this many outputs per batch (hub enforces it too).
pub const MAX_OUTPUTS: usize = 64;

pub type Runtime = Arc<dyn ContainerRuntime + Send + Sync>;

fn now_epoch() -> i64 {
    chrono::Utc::now().timestamp()
}

fn rfc3339_now() -> String {
    chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
}

fn parse_epoch(s: &str) -> Option<i64> {
    chrono::DateTime::parse_from_rfc3339(s)
        .ok()
        .map(|d| d.timestamp())
}

/// Whether a lease's deadline has already passed.
pub fn is_expired(lease: &Lease) -> bool {
    parse_epoch(&lease.deadline).is_none_or(|d| d <= now_epoch())
}

/// The reference to pull: the lease's `mirror_ref` exactly when it already
/// pins a digest (`…@sha256:…`), else `mirror_ref@digest`.
pub fn pull_ref(lease: &Lease) -> String {
    if lease.image.mirror_ref.contains('@') {
        lease.image.mirror_ref.clone()
    } else {
        format!("{}@{}", lease.image.mirror_ref, lease.image.digest)
    }
}

/// Label carrying the owning node's fingerprint.
pub const NODE_LABEL: &str = "zakuro.space.node";

/// Container name: per node and Space, so two brokers on one docker daemon
/// never `rm -f` each other's containers.
pub fn container_name(node_fp: &str, space_id: &str) -> String {
    format!("zk-space-{node_fp}-{space_id}")
}

/// `docker ps --filter label=` value selecting this node's Space containers.
pub fn node_label_filter(node_fp: &str) -> String {
    format!("{NODE_LABEL}={node_fp}")
}

pub fn docker_config_dir(state_dir: &Path, space_id: &str) -> PathBuf {
    state_dir.join("spaces").join(space_id).join("docker")
}

pub fn socket_path(state_dir: &Path, space_id: &str) -> PathBuf {
    state_dir.join("spaces").join(format!("{space_id}.sock"))
}

struct Active {
    lease: Lease,
    started: String,
    deadline: i64,
    last_hb: Instant,
}

struct Inner {
    queue: VecDeque<Lease>,
    active: HashMap<i64, Active>,
    last_activity: Instant,
}

/// State shared between the runner's maintenance thread and the socket
/// connection threads.
pub struct Session {
    pub space_id: String,
    hub: Hub,
    runtime: Runtime,
    node_key: Arc<NodeKey>,
    container_id: Mutex<String>,
    expected_digest: String,
    docker_cfg: PathBuf,
    inner: Mutex<Inner>,
    stats: Arc<Stats>,
    dead: AtomicBool,
    /// Set when the container was killed for a reason that should back off
    /// claiming (digest mismatch, lease expiry/loss), as opposed to an idle
    /// stop or shutdown.
    failed: AtomicBool,
    /// Receipts the hub accepted.
    completions: AtomicU64,
    /// First retry delay for a transient `complete` failure.
    complete_retry_base: Duration,
}

/// Longest wait between `complete` retries.
const COMPLETE_RETRY_CAP: Duration = Duration::from_secs(30);
/// Keep retrying `complete` this long past the lease deadline (spec §5).
const COMPLETE_GRACE_S: i64 = 60;

/// Retry `complete` with exponential backoff on transient errors (transport,
/// hub 5xx) until `give_up_at` (epoch seconds). Final answers return at once.
fn complete_with_retry(
    hub: &Hub,
    lease_id: &str,
    signed: &receipt::SignedReceipt,
    give_up_at: i64,
    base: Duration,
) -> Result<Completion, String> {
    let mut delay = base;
    loop {
        std::thread::sleep(delay);
        match hub.complete(lease_id, signed) {
            Ok(c) => return Ok(c),
            Err(e) => {
                if now_epoch() >= give_up_at {
                    return Err(e);
                }
            }
        }
        delay = (delay * 2).min(COMPLETE_RETRY_CAP.max(base));
    }
}

impl Session {
    fn touch(inner: &mut Inner) {
        inner.last_activity = Instant::now();
    }

    pub fn is_dead(&self) -> bool {
        self.dead.load(Ordering::SeqCst)
    }

    /// Killed for a reason that warrants backing off further claims.
    pub fn failed(&self) -> bool {
        self.failed.load(Ordering::SeqCst)
    }

    /// Receipts accepted by the hub so far.
    pub fn completions(&self) -> u64 {
        self.completions.load(Ordering::SeqCst)
    }

    fn kill_failed(&self) {
        self.failed.store(true, Ordering::SeqCst);
        self.kill();
    }

    /// Leases queued or running.
    pub fn outstanding(&self) -> usize {
        let g = self.inner.lock().unwrap();
        g.queue.len() + g.active.len()
    }

    pub fn counts(&self) -> (usize, usize) {
        let g = self.inner.lock().unwrap();
        (g.queue.len(), g.active.len())
    }

    pub fn enqueue(&self, lease: Lease) {
        let mut g = self.inner.lock().unwrap();
        g.queue.push_back(lease);
        Self::touch(&mut g);
    }

    /// Stop and remove the container; abandon every lease (the hub's reaper
    /// requeues them). Idempotent.
    pub fn kill(&self) {
        if self.dead.swap(true, Ordering::SeqCst) {
            return;
        }
        let cid = self.container_id.lock().unwrap().clone();
        let _ = self.runtime.stop(&cid);
        let _ = self.runtime.rm(&cid);
        let _ = std::fs::remove_dir_all(&self.docker_cfg);
        let mut g = self.inner.lock().unwrap();
        g.queue.clear();
        g.active.clear();
    }

    /// Whether the running container's image still is the leased digest.
    /// Fails closed: an inspect error counts as a mismatch.
    fn digest_ok(&self) -> bool {
        let cid = self.container_id.lock().unwrap().clone();
        match self.runtime.image_digest(&cid) {
            Ok(d) => d.split(',').any(|x| x.trim() == self.expected_digest),
            Err(_) => false,
        }
    }

    /// `GET /next`.
    pub fn next(&self) -> (u16, String) {
        if self.is_dead() {
            return (204, String::new());
        }
        // An empty poll is not activity: only a served batch refreshes the
        // idle timer, or a polling worker would keep the container forever.
        let mut g = self.inner.lock().unwrap();
        while let Some(lease) = g.queue.pop_front() {
            let Some(deadline) = parse_epoch(&lease.deadline).filter(|d| *d > now_epoch()) else {
                eprintln!(
                    "  [SPACES] lease {} expired before start; abandoned",
                    lease.lease_id
                );
                continue;
            };
            let body = json!({
                "batch_id": lease.batch_id,
                "seq": lease.seq,
                "inputs": lease.inputs,
                "output_presign_endpoint": "/outputs",
                "max_runtime_s": lease.requirements.max_runtime_s,
            })
            .to_string();
            g.active.insert(
                lease.batch_id,
                Active {
                    started: rfc3339_now(),
                    deadline,
                    last_hb: Instant::now(),
                    lease,
                },
            );
            Self::touch(&mut g);
            return (200, body);
        }
        (204, String::new())
    }

    /// The lease id of a live (unexpired) active batch.
    fn live_lease(&self, batch_id: i64) -> Result<String, (u16, String)> {
        let mut g = self.inner.lock().unwrap();
        Self::touch(&mut g);
        let Some(a) = g.active.get(&batch_id) else {
            return Err((
                409,
                json!({"error": "unknown or abandoned batch"}).to_string(),
            ));
        };
        if a.deadline <= now_epoch() {
            g.active.remove(&batch_id);
            return Err((409, json!({"error": "lease expired"}).to_string()));
        }
        Ok(a.lease.lease_id.clone())
    }

    /// `POST /outputs`: proxy to the hub's `outputs:presign`.
    pub fn outputs(&self, body: &[u8]) -> (u16, String) {
        let v: Value = match serde_json::from_slice(body) {
            Ok(v) => v,
            Err(_) => return (400, json!({"error": "bad json"}).to_string()),
        };
        let Some(batch_id) = v.get("batch_id").and_then(|b| b.as_i64()) else {
            return (400, json!({"error": "batch_id required"}).to_string());
        };
        let names: Vec<String> = v
            .get("names")
            .and_then(|n| n.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|s| s.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        if names.len() > MAX_OUTPUTS {
            return (
                400,
                json!({"error": "too many outputs (max 64)"}).to_string(),
            );
        }
        let lease_id = match self.live_lease(batch_id) {
            Ok(l) => l,
            Err(e) => return e,
        };
        match self.hub.presign(&lease_id, &names) {
            Ok((code, text)) => (code, text),
            Err(e) => (502, json!({"error": e}).to_string()),
        }
    }

    /// `POST /done`: verify the digest, sign the receipt, complete.
    pub fn done(&self, body: &[u8]) -> (u16, String) {
        let v: Value = match serde_json::from_slice(body) {
            Ok(v) => v,
            Err(_) => return (400, json!({"error": "bad json"}).to_string()),
        };
        let (Some(batch_id), Some(exit_code)) = (
            v.get("batch_id").and_then(|b| b.as_i64()),
            v.get("exit_code").and_then(|b| b.as_i64()),
        ) else {
            return (
                400,
                json!({"error": "batch_id and exit_code required"}).to_string(),
            );
        };
        let mut hashes = BTreeMap::new();
        if let Some(m) = v.get("output_hashes").and_then(|m| m.as_object()) {
            for (k, h) in m {
                if let Some(h) = h.as_str() {
                    hashes.insert(k.clone(), h.to_string());
                }
            }
        }
        if hashes.len() > MAX_OUTPUTS {
            return (
                400,
                json!({"error": "too many outputs (max 64)"}).to_string(),
            );
        }
        if let Err(e) = self.live_lease(batch_id) {
            return e;
        }
        // Re-read the running container's image digest. A mismatch (image
        // re-tagged locally) is never reported: kill and abandon.
        if !self.digest_ok() {
            eprintln!(
                "  [SPACES] image digest mismatch for space {}; killing container, no receipt",
                self.space_id
            );
            self.kill_failed();
            return (
                409,
                json!({"accepted": false, "reason": "image digest mismatch"}).to_string(),
            );
        }
        let Some(active) = self.inner.lock().unwrap().active.remove(&batch_id) else {
            return (
                409,
                json!({"accepted": false, "reason": "abandoned"}).to_string(),
            );
        };
        let signed = receipt::build(
            &active.lease,
            &hashes,
            exit_code,
            &active.started,
            &rfc3339_now(),
            &self.node_key,
        );
        {
            let mut g = self.inner.lock().unwrap();
            Self::touch(&mut g);
        }
        match self.hub.complete(&active.lease.lease_id, &signed) {
            Ok(c) => self.finish_completion(c),
            Err(first_err) => {
                // Transient (transport error or hub 5xx): the work is done
                // and signed, so keep the receipt and retry with backoff
                // until the lease deadline plus grace, off the worker's
                // socket so its read timeout is not the limit.
                eprintln!(
                    "  [SPACES] complete for batch {batch_id} failed ({first_err}); retrying in background"
                );
                let hub = self.hub.clone();
                let stats = self.stats.clone();
                let base = self.complete_retry_base;
                let give_up_at = active.deadline + COMPLETE_GRACE_S;
                let lease_id = active.lease.lease_id.clone();
                let spawned = std::thread::Builder::new()
                    .name("spaces-complete".into())
                    .spawn(move || {
                        match complete_with_retry(&hub, &lease_id, &signed, give_up_at, base) {
                            Ok(Completion::Accepted { paid }) => stats.record_paid(paid),
                            Ok(Completion::Rejected { status }) => eprintln!(
                                "  [SPACES] hub rejected receipt for batch {batch_id} ({status})"
                            ),
                            Err(e) => {
                                eprintln!("  [SPACES] gave up completing batch {batch_id}: {e}")
                            }
                        }
                    });
                match spawned {
                    Ok(_) => (
                        202,
                        json!({"accepted": "pending", "reason": first_err}).to_string(),
                    ),
                    Err(e) => (
                        502,
                        json!({"accepted": false, "reason": e.to_string()}).to_string(),
                    ),
                }
            }
        }
    }

    fn finish_completion(&self, c: Completion) -> (u16, String) {
        match c {
            Completion::Accepted { paid } => {
                self.completions.fetch_add(1, Ordering::SeqCst);
                self.stats.record_paid(paid);
                (200, json!({"accepted": true}).to_string())
            }
            Completion::Rejected { status } => (
                409,
                json!({"accepted": false, "reason": format!("hub rejected ({status})")})
                    .to_string(),
            ),
        }
    }

    /// One maintenance pass: drop expired leases, heartbeat the due ones.
    pub fn maintain(&self) {
        let now = now_epoch();
        let mut due: Vec<(i64, String, u64)> = Vec::new();
        let mut lost = false;
        {
            let mut g = self.inner.lock().unwrap();
            let expired: Vec<i64> = g
                .active
                .iter()
                .filter(|(_, a)| a.deadline <= now)
                .map(|(b, _)| *b)
                .collect();
            for b in expired {
                eprintln!("  [SPACES] lease for batch {b} expired; abandoned, killing container");
                g.active.remove(&b);
                lost = true;
            }
            for (b, a) in g.active.iter() {
                let every = a.lease.heartbeat_every_s.max(1);
                if a.last_hb.elapsed() >= Duration::from_secs(every) {
                    due.push((*b, a.lease.lease_id.clone(), every));
                }
            }
        }
        for (batch, lease_id, _) in due {
            let res = self.hub.heartbeat(&lease_id);
            let mut g = self.inner.lock().unwrap();
            match res {
                Ok(until) => {
                    if let Some(a) = g.active.get_mut(&batch) {
                        a.last_hb = Instant::now();
                        if let Some(d) = until.as_deref().and_then(parse_epoch) {
                            a.deadline = d;
                        }
                    }
                }
                Err(e) => {
                    eprintln!("  [SPACES] heartbeat for batch {batch} failed: {e}");
                    if e.contains("HTTP 409") || e.contains("HTTP 404") {
                        g.active.remove(&batch);
                        lost = true;
                    } else if let Some(a) = g.active.get_mut(&batch) {
                        // Transient: retry next period, not every poll.
                        a.last_hb = Instant::now();
                    }
                }
            }
        }
        if lost {
            // The lease is gone but the command may still be running (or
            // hung): kill the container so the next lease gets a fresh one
            // instead of queueing behind a stuck worker.
            self.kill_failed();
        }
    }

    fn idle_for(&self) -> Duration {
        let g = self.inner.lock().unwrap();
        if g.queue.is_empty() && g.active.is_empty() {
            g.last_activity.elapsed()
        } else {
            Duration::ZERO
        }
    }
}

pub struct RunnerDeps {
    pub hub: Hub,
    pub runtime: Runtime,
    pub node_key: Arc<NodeKey>,
    pub state_dir: PathBuf,
    pub stats: Arc<Stats>,
    pub network: String,
    pub idle_timeout: Duration,
    /// Short node identity fingerprint: part of the container name and the
    /// `zakuro.space.node` label, so brokers sharing a docker daemon never
    /// touch each other's containers.
    pub node_fp: String,
    pub complete_retry_base: Duration,
}

pub struct SpaceRunner {
    pub session: Arc<Session>,
    stop: Arc<AtomicBool>,
    sock: PathBuf,
}

impl SpaceRunner {
    /// Log in, pull by digest, bind the socket, start the container.
    pub fn start(deps: &RunnerDeps, lease: &Lease) -> Result<SpaceRunner, String> {
        let rt = &deps.runtime;
        // A private docker config so the pull token never lands in the
        // host's ~/.docker/config.json; removed when the container stops.
        let docker_cfg = docker_config_dir(&deps.state_dir, &lease.space_id);
        std::fs::create_dir_all(&docker_cfg).map_err(|e| format!("docker config dir: {e}"))?;
        let cleanup = |e: String| {
            let _ = std::fs::remove_dir_all(&docker_cfg);
            e
        };
        rt.login_in(
            &docker_cfg,
            &lease.pull.registry,
            &lease.pull.username,
            &lease.pull.token,
        )
        .map_err(|e| cleanup(format!("registry login failed: {e}")))?;
        let image = pull_ref(lease);
        rt.pull_in(&docker_cfg, &image)
            .map_err(|e| cleanup(format!("pull {image} failed: {e}")))?;

        let sock = socket_path(&deps.state_dir, &lease.space_id);
        let session = Arc::new(Session {
            space_id: lease.space_id.clone(),
            hub: deps.hub.clone(),
            runtime: rt.clone(),
            node_key: deps.node_key.clone(),
            container_id: Mutex::new(String::new()),
            expected_digest: lease.image.digest.clone(),
            docker_cfg: docker_cfg.clone(),
            inner: Mutex::new(Inner {
                queue: VecDeque::new(),
                active: HashMap::new(),
                last_activity: Instant::now(),
            }),
            stats: deps.stats.clone(),
            dead: AtomicBool::new(false),
            failed: AtomicBool::new(false),
            completions: AtomicU64::new(0),
            complete_retry_base: deps.complete_retry_base,
        });
        let stop = Arc::new(AtomicBool::new(false));
        socket::serve(&sock, session.clone(), stop.clone())?;

        let mut env = HashMap::new();
        env.insert("ZAKURO_SPACE_ID".to_string(), lease.space_id.clone());
        env.insert(
            "ZAKURO_SPACE_SOCKET".to_string(),
            CONTAINER_SOCKET.to_string(),
        );
        let req = &lease.requirements;
        let spec = RunSpec {
            name: container_name(&deps.node_fp, &lease.space_id),
            image: &image,
            cmd: None,
            ports: &[],
            env: &env,
            labels: vec![
                ("zakuro.space".to_string(), lease.space_id.clone()),
                (NODE_LABEL.to_string(), deps.node_fp.clone()),
            ],
            mounts: vec![(sock.display().to_string(), CONTAINER_SOCKET.to_string())],
            cpus: (req.cpus > 0.0).then_some(req.cpus),
            memory_gb: (req.memory_gb > 0.0).then_some(req.memory_gb),
            gpus: (req.gpus > 0).then_some(req.gpus),
            network: Some(deps.network.clone()),
            hardened: true,
        };
        let cid = match rt.run(&spec) {
            Ok(c) => c,
            Err(e) => {
                stop.store(true, Ordering::SeqCst);
                let _ = std::fs::remove_file(&sock);
                return Err(cleanup(format!("run failed: {e}")));
            }
        };
        *session.container_id.lock().unwrap() = cid;
        // Verify before taking any work; /done re-verifies.
        if !session.digest_ok() {
            session.kill_failed();
            stop.store(true, Ordering::SeqCst);
            let _ = std::fs::remove_file(&sock);
            return Err("image digest mismatch after start".to_string());
        }

        let runner = SpaceRunner {
            session: session.clone(),
            stop: stop.clone(),
            sock,
        };
        let idle = deps.idle_timeout;
        let s2 = session.clone();
        let stop2 = stop.clone();
        let sock2 = runner.sock.clone();
        let _ = std::thread::Builder::new()
            .name("spaces-maint".into())
            .spawn(move || {
                while !stop2.load(Ordering::SeqCst) && !s2.is_dead() {
                    std::thread::sleep(Duration::from_millis(100));
                    s2.maintain();
                    if s2.idle_for() >= idle {
                        eprintln!("  [SPACES] space {} idle; stopping container", s2.space_id);
                        break;
                    }
                }
                s2.kill();
                stop2.store(true, Ordering::SeqCst);
                let _ = std::fs::remove_file(&sock2);
            });
        Ok(runner)
    }

    /// Whether the container is gone (idle stop, digest mismatch, shutdown).
    pub fn finished(&self) -> bool {
        self.session.is_dead() || self.stop.load(Ordering::SeqCst)
    }

    pub fn shutdown(&self) {
        self.session.kill();
        self.stop.store(true, Ordering::SeqCst);
        let _ = std::fs::remove_file(&self.sock);
    }
}