zc2 0.0.46

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
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
//! When to run the benchmark on an idle broker. `decide` is pure; the thread
//! that drives it (and the auto-price tick) is at the bottom of the file.
use std::time::Duration;

/// What the last completed run measured, as read back from `bench/last.json`.
#[derive(Clone, Debug, PartialEq)]
pub struct LastRun {
    pub suite: String,
    pub fingerprint_sha256: String,
    pub submitted: bool,
    /// Time since that run finished.
    pub age: Duration,
    /// The run did not fully measure the hardware (a GPU timed out, was busy
    /// or lacked a figure, or the budget ran out).
    pub partial: bool,
    /// The hub refused the report: its HTTP status and the time since.
    pub rejected: Option<(u16, Duration)>,
    /// Consecutive runs (including this one) that were partial because a GPU
    /// was busy. Drives the re-measure back-off (`partial_rerun_after`).
    pub busy_streak: u32,
}

#[derive(Debug, PartialEq)]
pub enum Decision {
    RunNow,
    Wait(Duration),
    Never,
}

/// The broker must have served nothing for this long before a run starts.
pub const IDLE_BEFORE_RUN: Duration = Duration::from_secs(30);

/// How long to hold off after the `failures`-th cancelled run.
pub fn backoff(failures: u32) -> Duration {
    Duration::from_secs(match failures {
        0 | 1 => 60,
        2 => 300,
        3 => 1800,
        _ => 86400,
    })
}

pub fn decide(
    last: Option<&LastRun>,
    current_fp: &str,
    suite: &str,
    idle_for: Duration,
    failures: u32,
    auto_enabled: bool,
) -> Decision {
    if !auto_enabled {
        return Decision::Never;
    }
    // Same hardware, same suite: measured already. An unsubmitted report is
    // re-sent from last.json by the caller, never re-measured.
    if let Some(l) = last {
        if l.suite == suite {
            match l.rejected {
                // 400 means this report was stale or malformed: measure afresh.
                // Anything else 4xx: leave the hub alone for a day first.
                Some((code, since)) if code != 400 && since < REJECTED_HOLD_OFF => {
                    return Decision::Wait(REJECTED_HOLD_OFF - since);
                }
                Some(_) => {}
                None if l.fingerprint_sha256 == current_fp => {
                    // A partial run (a busy or hung GPU) is retried, but not at once.
                    if !l.partial {
                        return Decision::Never;
                    }
                    let hold = partial_rerun_after(l.busy_streak);
                    if l.age < hold {
                        return Decision::Wait(hold - l.age);
                    }
                }
                None => {}
            }
            // Hardware that looks different right after a run is more likely
            // a flaky probe than a swapped part: wait. (A new suite runs at once.)
            if l.fingerprint_sha256 != current_fp
                && l.rejected.is_none()
                && l.age < COMPLETED_HOLD_OFF
            {
                return Decision::Wait(COMPLETED_HOLD_OFF - l.age);
            }
        }
    }
    if failures > 0 {
        return Decision::Wait(backoff(failures));
    }
    if idle_for < IDLE_BEFORE_RUN {
        return Decision::Wait(IDLE_BEFORE_RUN - idle_for);
    }
    Decision::RunNow
}

// --- The thread that drives it -------------------------------------------

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Instant;

use super::fingerprint::HardwareFingerprint;
use super::report::SignedReport;
use super::run::{self, RunCtx, RunOpts, RunOutcome};
use super::submit::{self, SubmitError};
use super::SUITE;
use crate::broker::BrokerState;

const LOOP_EVERY: Duration = Duration::from_secs(10);
const RESUBMIT_EVERY: Duration = Duration::from_secs(60);
/// After a completed run, no new automatic run for this long.
pub const COMPLETED_HOLD_OFF: Duration = Duration::from_secs(24 * 3600);
/// A partial run (see `LastRun::partial`) is re-measured after this long.
pub const PARTIAL_RERUN_AFTER: Duration = Duration::from_secs(6 * 3600);
/// Longest wait between re-measures of a permanently busy GPU.
pub const PARTIAL_RERUN_MAX: Duration = Duration::from_secs(24 * 3600);

/// How long to wait before re-measuring after `busy_streak` consecutive
/// partial-because-busy runs: 6 h, then 12 h, then 24 h (the cap). A GPU held
/// by something long-lived (vLLM) is not worth re-measuring every 6 h. Zero
/// (partial for another reason, e.g. a timeout) keeps the base 6 h.
pub fn partial_rerun_after(busy_streak: u32) -> Duration {
    let doublings = busy_streak.saturating_sub(1).min(2);
    (PARTIAL_RERUN_AFTER * (1 << doublings)).min(PARTIAL_RERUN_MAX)
}
/// After the hub refuses a report with a 4xx other than 400.
pub const REJECTED_HOLD_OFF: Duration = Duration::from_secs(24 * 3600);
/// Between automatic runs after a refusal, so a hub that keeps saying 400
/// is not met with a 60 s measurement every idle window.
const REJECTED_PAUSE: Duration = Duration::from_secs(3600);
/// When another benchmark holds the lock.
const LOCK_BUSY_PAUSE: Duration = Duration::from_secs(300);
const RUN_BUDGET: Duration = Duration::from_secs(60);
/// Automatic runs start 0..this many seconds late, so brokers that restart
/// together (a rollout) do not all measure at once and skew each other.
const START_JITTER_SECS: u64 = 120;

/// 0..`START_JITTER_SECS`, from the clock and the pid (no RNG dependency).
fn start_jitter() -> Duration {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    jitter_from(nanos ^ (std::process::id() as u64).wrapping_mul(0x9E37_79B9))
}

fn jitter_from(seed: u64) -> Duration {
    Duration::from_secs(seed % START_JITTER_SECS)
}

/// Starts the scheduler once per process; later calls do nothing.
pub fn spawn_once(state: Arc<BrokerState>) {
    static STARTED: AtomicBool = AtomicBool::new(false);
    if STARTED.swap(true, Ordering::SeqCst) {
        return;
    }
    let _ = std::thread::Builder::new()
        .name("bench-sched".into())
        .spawn(move || scheduler_loop(&state));
}

fn scheduler_loop(state: &BrokerState) {
    use crate::broker::node_identity::now_secs;
    let (Some(api_url), Some(api_key)) = (&state.config.api_url, &state.config.api_key) else {
        return;
    };
    let Some(dir) = crate::credentials::dir() else {
        return;
    };
    let auto_enabled = std::env::var("ZAKURO_BENCH_AUTO").as_deref() != Ok("0");
    let mut fingerprint: Option<String> = None;
    let mut failures = 0u32;
    let mut not_before = Instant::now();
    let mut next_submit = Instant::now();

    loop {
        std::thread::sleep(LOOP_EVERY);
        if !auto_enabled {
            continue;
        }

        // A report that was measured but not delivered is re-sent, not re-measured.
        if let Some(signed) = run::pending_submission(&dir, None) {
            if Instant::now() >= next_submit {
                match submit::post(api_url, api_key, &signed) {
                    // `post` maps the hub's 409 (already stored) to Ok too.
                    Ok(_) => {
                        let _ = run::save_last(&dir, &signed, run::SubmitState::Done);
                    }
                    Err(SubmitError::Retryable(e)) => {
                        eprintln!("  [BENCH] submit failed, will retry: {e}");
                        next_submit = Instant::now() + RESUBMIT_EVERY;
                    }
                    Err(e @ SubmitError::Rejected(code, _)) => {
                        eprintln!("  [BENCH] {e}");
                        let _ = run::save_last(&dir, &signed, run::SubmitState::Rejected(code));
                        not_before = Instant::now() + REJECTED_PAUSE;
                    }
                }
            }
        }

        if Instant::now() < not_before {
            continue;
        }
        if fingerprint.is_none() {
            // Bounded: cuInit can hang, and this thread must not.
            let Some(ids) = run::enumerate_with_timeout(&AtomicBool::new(false)) else {
                eprintln!("  [BENCH] GPU enumeration timed out; trying again later");
                not_before = Instant::now() + backoff(1);
                continue;
            };
            fingerprint = Some(HardwareFingerprint::detect(ids).sha256());
        }
        let fp = fingerprint.clone().unwrap_or_default();
        let space_busy = crate::spaces::space_containers();
        let spaces_running = || space_busy.load(Ordering::SeqCst) > 0;
        let idle_secs = || {
            // A running Space container saturates CPU/GPU: measuring now
            // would under-report the node (and its price and class).
            if state.inflight.load(Ordering::SeqCst) > 0 || spaces_running() {
                Duration::ZERO
            } else {
                Duration::from_secs(
                    now_secs().saturating_sub(state.last_busy.load(Ordering::SeqCst)),
                )
            }
        };
        let last = run::last_run(&dir);
        if decide(last.as_ref(), &fp, SUITE, idle_secs(), 0, auto_enabled) != Decision::RunNow {
            continue;
        }

        // Jitter, then look again: traffic may have arrived while waiting.
        std::thread::sleep(start_jitter());
        if idle_secs() < IDLE_BEFORE_RUN {
            continue;
        }

        // Clear the flag, then re-check: a request that arrived before the
        // clear is seen by the check, one that arrives after it re-raises the flag.
        state.bench_cancel.store(false, Ordering::SeqCst);
        if state.inflight.load(Ordering::SeqCst) > 0 || spaces_running() {
            state.bench_cancel.store(true, Ordering::SeqCst);
            continue;
        }
        println!("  [BENCH] idle: measuring this node");
        // The Spaces scheduler sends no claims while this is raised.
        let measuring = crate::spaces::bench_running();
        measuring.store(true, Ordering::SeqCst);
        let opts = RunOpts {
            save_as: run::SubmitState::Pending,
            budget: RUN_BUDGET,
            no_gpu: false,
            state_dir: dir.clone(),
            hub_url: Some(api_url.clone()),
            peers: state.peer_manager.peer_urls(),
        };
        let mut submit_hook = |s: &SignedReport| submit::post(api_url, api_key, s).map(|_| ());
        let outcome = run::run(
            &opts,
            &mut RunCtx {
                key: &state.node_key,
                cancel: state.bench_cancel.clone(),
                progress: &|_| {},
                submit: Some(&mut submit_hook),
            },
        );
        measuring.store(false, Ordering::SeqCst);
        match outcome {
            RunOutcome::AlreadyRunning => {
                println!(
                    "  [BENCH] a benchmark is already running; next try in {LOCK_BUSY_PAUSE:?}"
                );
                not_before = Instant::now() + LOCK_BUSY_PAUSE;
            }
            RunOutcome::Cancelled => {
                failures += 1;
                not_before = Instant::now() + backoff(failures);
                println!(
                    "  [BENCH] cancelled by traffic; next try in {:?}",
                    backoff(failures)
                );
            }
            RunOutcome::Completed {
                signed,
                submit_error,
                ..
            } => {
                failures = 0;
                match submit_error {
                    None => println!("  [BENCH] measured and submitted"),
                    Some(SubmitError::Retryable(e)) => {
                        eprintln!("  [BENCH] measured; submit failed, will retry: {e}");
                        next_submit = Instant::now() + RESUBMIT_EVERY;
                    }
                    Some(e @ SubmitError::Rejected(code, _)) => {
                        eprintln!("  [BENCH] measured; {e}");
                        let _ = run::save_last(&dir, &signed, run::SubmitState::Rejected(code));
                        not_before = Instant::now() + REJECTED_PAUSE;
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bench_node::SUITE;

    #[test]
    fn first_run_waits_for_thirty_idle_seconds() {
        assert!(matches!(
            decide(None, "fp", SUITE, Duration::from_secs(10), 0, true),
            Decision::Wait(_)
        ));
        assert!(matches!(
            decide(None, "fp", SUITE, Duration::from_secs(30), 0, true),
            Decision::RunNow
        ));
    }
    #[test]
    fn same_fingerprint_and_suite_never_reruns() {
        let l = LastRun {
            suite: SUITE.into(),
            fingerprint_sha256: "fp".into(),
            submitted: true,
            age: Duration::ZERO,
            partial: false,
            rejected: None,
            busy_streak: 0,
        };
        assert!(matches!(
            decide(Some(&l), "fp", SUITE, Duration::from_secs(999), 0, true),
            Decision::Never
        ));
    }
    #[test]
    fn a_fingerprint_change_right_after_a_run_waits_but_a_suite_change_does_not() {
        let l = LastRun {
            suite: SUITE.into(),
            fingerprint_sha256: "old".into(),
            submitted: true,
            age: Duration::from_secs(3600),
            partial: false,
            rejected: None,
            busy_streak: 0,
        };
        assert_eq!(
            decide(Some(&l), "new", SUITE, Duration::from_secs(60), 0, true),
            Decision::Wait(COMPLETED_HOLD_OFF - Duration::from_secs(3600))
        );
        let old_enough = LastRun {
            age: COMPLETED_HOLD_OFF,
            partial: false,
            rejected: None,
            busy_streak: 0,
            ..l.clone()
        };
        assert_eq!(
            decide(
                Some(&old_enough),
                "new",
                SUITE,
                Duration::from_secs(60),
                0,
                true
            ),
            Decision::RunNow
        );
        let other_suite = LastRun {
            suite: "zc-bench-node/0".into(),
            ..l
        };
        assert_eq!(
            decide(
                Some(&other_suite),
                "new",
                SUITE,
                Duration::from_secs(60),
                0,
                true
            ),
            Decision::RunNow
        );
    }
    #[test]
    fn hardware_or_suite_change_reruns() {
        let l = LastRun {
            suite: SUITE.into(),
            fingerprint_sha256: "old".into(),
            submitted: true,
            age: COMPLETED_HOLD_OFF,
            partial: false,
            rejected: None,
            busy_streak: 0,
        };
        assert!(matches!(
            decide(Some(&l), "new", SUITE, Duration::from_secs(60), 0, true),
            Decision::RunNow
        ));
        let l2 = LastRun {
            suite: "zc-bench-node/0".into(),
            fingerprint_sha256: "fp".into(),
            submitted: true,
            age: Duration::ZERO,
            partial: false,
            rejected: None,
            busy_streak: 0,
        };
        assert!(matches!(
            decide(Some(&l2), "fp", SUITE, Duration::from_secs(60), 0, true),
            Decision::RunNow
        ));
    }
    #[test]
    fn backoff_after_cancellations() {
        let waits: Vec<_> = (1..=5)
            .map(
                |f| match decide(None, "fp", SUITE, Duration::from_secs(60), f, true) {
                    Decision::Wait(d) => d.as_secs(),
                    _ => 0,
                },
            )
            .collect();
        assert_eq!(waits, vec![60, 300, 1800, 86400, 86400]);
    }
    #[test]
    fn auto_disabled_never_runs() {
        assert!(matches!(
            decide(None, "fp", SUITE, Duration::from_secs(60), 0, false),
            Decision::Never
        ));
    }
    fn last(partial: bool, rejected: Option<(u16, Duration)>, age: Duration) -> LastRun {
        LastRun {
            suite: SUITE.into(),
            fingerprint_sha256: "fp".into(),
            submitted: true,
            age,
            partial,
            rejected,
            busy_streak: 0,
        }
    }
    const IDLE: Duration = Duration::from_secs(60);
    #[test]
    fn a_partial_run_is_rerun_after_six_hours_not_never() {
        let h = |n: u64| Duration::from_secs(n * 3600);
        assert_eq!(
            decide(Some(&last(true, None, h(1))), "fp", SUITE, IDLE, 0, true),
            Decision::Wait(PARTIAL_RERUN_AFTER - h(1))
        );
        assert_eq!(
            decide(Some(&last(true, None, h(6))), "fp", SUITE, IDLE, 0, true),
            Decision::RunNow
        );
        // A complete one keeps the old rule.
        assert_eq!(
            decide(Some(&last(false, None, h(100))), "fp", SUITE, IDLE, 0, true),
            Decision::Never
        );
    }
    #[test]
    fn a_report_from_the_previous_suite_is_remeasured_at_once() {
        // zc#356 replaced the kernels; /1 numbers on disk must not stand.
        let old = LastRun {
            suite: "zc-bench-node/1".into(),
            ..last(false, None, Duration::from_secs(100 * 3600))
        };
        assert_ne!(old.suite, SUITE);
        assert_eq!(
            decide(Some(&old), "fp", SUITE, IDLE, 0, true),
            Decision::RunNow
        );
    }
    #[test]
    fn a_permanently_busy_gpu_backs_off_six_twelve_then_twenty_four_hours() {
        let h = |n: u64| Duration::from_secs(n * 3600);
        assert_eq!(partial_rerun_after(0), h(6));
        assert_eq!(partial_rerun_after(1), h(6));
        assert_eq!(partial_rerun_after(2), h(12));
        assert_eq!(partial_rerun_after(3), h(24));
        assert_eq!(partial_rerun_after(50), h(24));
        let streak = |n| LastRun {
            busy_streak: n,
            ..last(true, None, h(7))
        };
        // Seven hours after a first busy run: due. After a second: not yet.
        assert_eq!(
            decide(Some(&streak(1)), "fp", SUITE, IDLE, 0, true),
            Decision::RunNow
        );
        assert_eq!(
            decide(Some(&streak(2)), "fp", SUITE, IDLE, 0, true),
            Decision::Wait(h(5))
        );
        assert_eq!(
            decide(Some(&streak(3)), "fp", SUITE, IDLE, 0, true),
            Decision::Wait(h(17))
        );
    }
    #[test]
    fn a_refused_report_is_remeasured_a_400_at_once_and_other_4xx_after_a_day() {
        let rej = |c, since| Some((c, since));
        assert_eq!(
            decide(
                Some(&last(false, rej(400, Duration::ZERO), Duration::ZERO)),
                "fp",
                SUITE,
                IDLE,
                0,
                true
            ),
            Decision::RunNow
        );
        assert_eq!(
            decide(
                Some(&last(
                    false,
                    rej(403, Duration::from_secs(3600)),
                    Duration::ZERO
                )),
                "fp",
                SUITE,
                IDLE,
                0,
                true
            ),
            Decision::Wait(REJECTED_HOLD_OFF - Duration::from_secs(3600))
        );
        assert_eq!(
            decide(
                Some(&last(false, rej(403, REJECTED_HOLD_OFF), Duration::ZERO)),
                "fp",
                SUITE,
                IDLE,
                0,
                true
            ),
            Decision::RunNow
        );
    }
    #[test]
    fn start_jitter_stays_within_two_minutes() {
        for seed in [0u64, 1, 119, 120, 121, u64::MAX] {
            assert!(jitter_from(seed) < Duration::from_secs(120));
        }
        assert!(start_jitter() < Duration::from_secs(120));
    }
}