zc2 0.0.51

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
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
//! The broker works for its owner (ADR ZC-0025): offers are admitted against
//! free capacity, competing offers are ranked by revenue per budget-hour,
//! capacity is advertised as it is, and the owner can see what was refused and
//! what was missed.
//!
//! Logic lives here; `server.rs` carries only small hooks (`run_peer_offer`,
//! `cancel_offer`, the commit handler, `/health`, the advert and the tick).

use super::capacity::{self, Capacity, Held};
use super::task_board::{TaskOffer, TaskReject};
use super::BrokerState;
use crate::policy::admit::{Reason, Refusal, Source};
use crate::policy::schedule::{self, LocalTime};
use crate::policy::{MinPrice, Policy};
use crate::sandbox::{Allocation, Limits};
use serde_json::{json, Value};
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

const SNAPSHOT_FILE: &str = "revenue.json";
/// How long an offer that took the last slot waits for a better one to show
/// up (`ZAKURO_OFFER_RANK_WINDOW_MS`, 0 turns ranking off).
const DEFAULT_RANK_WINDOW_MS: u64 = 20;
/// The capacity view is pushed at most this often on a change...
pub const PUSH_FLOOR: Duration = Duration::from_secs(15);
/// ...and at least this often whatever changed (the old tick).
pub const PUSH_CEILING: Duration = Duration::from_secs(60);
/// A hold the commit/cancel never released is dropped this long after its
/// offer's own timeout.
const HOLD_GRACE: Duration = Duration::from_secs(120);
/// The default hold when an offer states no timeout.
const DEFAULT_HOLD: Duration = Duration::from_secs(300);

// ---- what an offer needs, and what it is worth ----------------------------------------

/// The size of an offer (or of a lease): what it holds while it runs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Need {
    pub cpus: f64,
    pub memory_bytes: u64,
    pub gpus: u32,
}

impl Need {
    pub fn of_offer(o: &TaskOffer) -> Self {
        Self {
            cpus: o.cpus.max(0.0),
            memory_bytes: o.memory_bytes,
            gpus: o.gpus,
        }
    }
}

/// The node's budget as the ranking and the lease packer see it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BudgetTotals {
    pub cpus: f64,
    pub memory_bytes: u64,
    pub gpus: u32,
}

impl BudgetTotals {
    pub fn of(l: &Limits, gpus: u32) -> Self {
        Self {
            cpus: l.cpu_millis as f64 / 1000.0,
            memory_bytes: l.memory_bytes,
            gpus,
        }
    }
}

/// Expected revenue per budget-hour of one offer (ADR ZC-0025 §5): what it
/// pays (`price_per_hour` for its expected duration, never below
/// `min_charge`) over the share of the budget it holds for that time. The
/// share is the dominant one (cpu, memory or GPUs), so a job that holds the
/// whole GPU is not cheap because it uses little memory.
pub fn revenue_per_budget_hour(
    price_per_hour: f64,
    min_charge: f64,
    expected_secs: f64,
    need: &Need,
    budget: &BudgetTotals,
) -> f64 {
    let hours = expected_secs.max(1.0) / 3600.0;
    let revenue = (price_per_hour.max(0.0) * hours).max(min_charge.max(0.0));
    let frac = |want: f64, have: f64| if have > 0.0 { want / have } else { 0.0 };
    let share = frac(need.cpus, budget.cpus)
        .max(frac(need.memory_bytes as f64, budget.memory_bytes as f64))
        .max(frac(need.gpus as f64, budget.gpus as f64))
        .max(1e-6);
    revenue / (share * hours)
}

// ---- holds ----------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct Hold {
    need: Need,
    expires: Instant,
}

#[derive(Debug, Clone)]
struct Waiter {
    id: String,
    need: Need,
    score: f64,
    seq: u64,
}

/// `cpu_millis`/`memory` left of `budget` after `held`, never below the
/// smallest unit the router places while nothing is held (so a small node's
/// share does not turn every default offer away: the same rule as `admit`).
fn remaining(budget: &Limits, held: &Held, nothing_held: bool) -> (u64, u64) {
    let cpu = (budget.cpu_millis as u64).saturating_sub((held.cpus * 1000.0).round() as u64);
    let mem = budget.memory_bytes.saturating_sub(held.memory_bytes);
    if nothing_held {
        (cpu.max(1000), mem.max(1 << 30))
    } else {
        (cpu, mem)
    }
}

fn fits(need: &Need, left: (u64, u64)) -> bool {
    ((need.cpus * 1000.0).round() as u64) <= left.0 && need.memory_bytes <= left.1
}

/// The offers to take, best first, when `left` cannot hold them all: greedy by
/// score, ties by arrival. An offer that does not fit is skipped and a
/// smaller, worse-paying one behind it may still be taken.
pub fn pick_ranked(waiting: &[(String, Need, f64, u64)], mut left: (u64, u64)) -> Vec<String> {
    let mut order: Vec<&(String, Need, f64, u64)> = waiting.iter().collect();
    order.sort_by(|a, b| {
        b.2.partial_cmp(&a.2)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.3.cmp(&b.3))
    });
    let mut chosen = Vec::new();
    for (id, need, _, _) in order {
        if fits(need, left) {
            left.0 -= ((need.cpus * 1000.0).round() as u64).min(left.0);
            left.1 -= need.memory_bytes.min(left.1);
            chosen.push(id.clone());
        }
    }
    chosen
}

// ---- eligible-idle accounting ---------------------------------------------------------

#[derive(Debug, Default)]
struct Idle {
    /// The union of the intervals the node sat eligible and idle.
    seconds: f64,
    by_source: BTreeMap<&'static str, f64>,
    /// End of the last interval added, so overlapping sources count once.
    covered_to: Option<Instant>,
    /// Time-weighted budget use, for the utilisation average.
    used_weighted: f64,
    observed: f64,
    last_used: f64,
}

/// Decides when the capacity view goes to the hub: on a change, at most every
/// [`PUSH_FLOOR`]; whatever changed, at least every [`PUSH_CEILING`].
#[derive(Debug, Default)]
pub struct PushGate {
    pub(crate) last: Option<(Instant, u64)>,
}

impl PushGate {
    pub fn due(&mut self, now: Instant, signature: u64) -> bool {
        let due = match self.last {
            None => true,
            Some((at, sig)) => {
                let age = now.saturating_duration_since(at);
                age >= PUSH_CEILING || (sig != signature && age >= PUSH_FLOOR)
            }
        };
        if due {
            self.last = Some((now, signature));
        }
        due
    }
}

struct Inner {
    holds: Mutex<HashMap<String, Hold>>,
    waiting: Mutex<Vec<Waiter>>,
    seq: AtomicU64,
    idle: Mutex<Idle>,
    gate: Mutex<PushGate>,
    since: std::time::SystemTime,
    /// Tests: a fixed ranking window instead of the environment.
    window_override: Mutex<Option<Duration>>,
    /// What running workloads (sandboxes, environment guests, Space leases,
    /// Atelier jobs) hold of the budget, as last scanned.
    workloads: Mutex<WorkloadScan>,
    /// Signalled when a scan stores its result (see [`Revenue::workloads`]).
    workloads_scanned: std::sync::Condvar,
    /// Spaces leases stopped to make room or for the owner, by reason.
    preempted: Mutex<BTreeMap<&'static str, u64>>,
    /// The best offer the budget turned away lately: Spaces may free room
    /// for it by stopping a lease that pays less.
    room_wanted: Mutex<Option<RoomWanted>>,
}

/// How long a scan of running workloads is reused: a busy broker admits
/// offers by the dozen and `docker ps` is a process spawn.
const WORKLOAD_SCAN_TTL: Duration = Duration::from_secs(2);
/// A refused offer asks for room for this long.
const ROOM_WANTED_TTL: Duration = Duration::from_secs(30);

pub type AllocSource = Arc<dyn Fn() -> Vec<Allocation> + Send + Sync>;

#[derive(Default)]
struct WorkloadScan {
    at: Option<Instant>,
    list: Vec<Allocation>,
    /// A scan is running (outside the lock).
    scanning: bool,
    /// Tests: what the scan reports instead of asking the sandbox engine.
    source: Option<AllocSource>,
    /// Tests: a shorter reuse window than [`WORKLOAD_SCAN_TTL`].
    ttl: Option<Duration>,
}

/// What is running on the node besides peer offers: the sandbox engine's
/// labelled containers and per-job instances (`sandbox::engine::allocations`,
/// which Atelier jobs and T1/T2 workloads are in) and the host Docker's
/// labelled containers (environment guests, Space leases), by name. The unit
/// tests never shell out.
/// One workload scan: the test source when set, else the real one. A scan
/// that panics counts as an empty one rather than leaving `scanning` set.
fn run_scan(source: Option<AllocSource>) -> Vec<Allocation> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match source {
        Some(f) => f(),
        None => scan_workloads(),
    }))
    .unwrap_or_default()
}

fn scan_workloads() -> Vec<Allocation> {
    if cfg!(test) {
        return Vec::new();
    }
    let mut all = crate::sandbox::engine::allocations().unwrap_or_default();
    if let Ok(more) =
        crate::broker::deploy::ContainerRuntime::allocations(&crate::broker::deploy::DockerCli)
    {
        for a in more {
            if !all.iter().any(|x| x.name == a.name) {
                all.push(a);
            }
        }
    }
    all
}

/// An offer that did not fit, and what it would pay.
#[derive(Debug, Clone, Copy)]
pub struct RoomWanted {
    pub need: Need,
    pub price_per_hour: f64,
    at: Instant,
}

/// The broker's revenue state. Cheap to clone; every clone is the same state.
#[derive(Clone)]
pub struct Revenue(Arc<Inner>);

impl Default for Revenue {
    fn default() -> Self {
        Self::new()
    }
}

/// An admitted offer's claim on the budget. Dropping it releases the claim;
/// [`keep`](Self::keep) hands it to the two-phase flow, which releases it on
/// commit or cancel.
#[must_use]
pub struct HoldGuard {
    rev: Revenue,
    id: String,
    keep: bool,
}

impl HoldGuard {
    pub fn keep(mut self) {
        self.keep = true;
    }
}

impl Drop for HoldGuard {
    fn drop(&mut self) {
        if !self.keep {
            self.rev.release(&self.id);
        }
    }
}

impl Revenue {
    pub fn new() -> Self {
        Self(Arc::new(Inner {
            holds: Mutex::default(),
            waiting: Mutex::default(),
            seq: AtomicU64::new(0),
            idle: Mutex::default(),
            gate: Mutex::default(),
            since: std::time::SystemTime::now(),
            window_override: Mutex::new(None),
            workloads: Mutex::default(),
            workloads_scanned: std::sync::Condvar::new(),
            preempted: Mutex::default(),
            room_wanted: Mutex::new(None),
        }))
    }

    #[cfg(test)]
    pub fn with_window(self, w: Duration) -> Self {
        *self.0.window_override.lock().unwrap() = Some(w);
        self
    }

    fn window(&self) -> Duration {
        if let Some(w) = *self.0.window_override.lock().unwrap() {
            return w;
        }
        let ms = std::env::var("ZAKURO_OFFER_RANK_WINDOW_MS")
            .ok()
            .and_then(|v| v.trim().parse().ok())
            .unwrap_or(DEFAULT_RANK_WINDOW_MS);
        Duration::from_millis(ms.min(500))
    }

    fn holds(&self) -> std::sync::MutexGuard<'_, HashMap<String, Hold>> {
        self.0.holds.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// What admitted, unfinished offers hold now.
    pub fn held(&self) -> Held {
        held_of(&self.holds())
    }

    pub fn held_count(&self) -> usize {
        self.holds().len()
    }

    /// What running workloads hold of the budget (one source of truth for
    /// peer-offer admission and the capacity view; Spaces counts its own
    /// containers itself and must not add this).
    ///
    /// Never blocks on a scan once one has finished: a stale list is
    /// returned at once and refreshed in the background. The scan shells out
    /// to the sandbox engine and host Docker, which on a Mac is `limactl
    /// shell ... nerdctl ps` plus `docker ps` -- about 5 s, longer than
    /// [`WORKLOAD_SCAN_TTL`]. Scanning inline under the lock meant nearly
    /// every caller rescanned and the rest queued behind it, so `/health`
    /// (via the capacity view) took up to 8 s, the agent's 2 s probe timed
    /// out, and the broker read as "starting" and was eventually restarted
    /// as unresponsive. Only the first call, before any scan has finished,
    /// waits: admission must not see an empty node that is in fact full.
    pub fn workloads(&self) -> Vec<Allocation> {
        let inner = &self.0;
        let mut w = inner.workloads.lock().unwrap_or_else(|e| e.into_inner());
        loop {
            let ttl = w.ttl.unwrap_or(WORKLOAD_SCAN_TTL);
            match w.at {
                Some(t) if t.elapsed() < ttl => return w.list.clone(),
                Some(_) => {
                    if !w.scanning {
                        w.scanning = true;
                        let source = w.source.clone();
                        let inner = self.0.clone();
                        let spawned = std::thread::Builder::new()
                            .name("zc-workload-scan".into())
                            .spawn(move || Self::store_scan(&inner, run_scan(source)));
                        if spawned.is_err() {
                            w.scanning = false;
                        }
                    }
                    return w.list.clone();
                }
                None if w.scanning => {
                    w = inner
                        .workloads_scanned
                        .wait(w)
                        .unwrap_or_else(|e| e.into_inner());
                }
                None => {
                    w.scanning = true;
                    let source = w.source.clone();
                    drop(w);
                    let list = run_scan(source);
                    Self::store_scan(inner, list.clone());
                    return list;
                }
            }
        }
    }

    /// Store a finished scan and wake anyone waiting for the first one.
    fn store_scan(inner: &Inner, list: Vec<Allocation>) {
        let mut w = inner.workloads.lock().unwrap_or_else(|e| e.into_inner());
        w.list = list;
        w.at = Some(Instant::now());
        w.scanning = false;
        inner.workloads_scanned.notify_all();
    }

    /// Everything held against the budget: admitted offers and workloads.
    pub fn held_all(&self) -> Held {
        let mut h = self.held();
        for a in self.workloads() {
            h.cpus += a.cpu_millis as f64 / 1000.0;
            h.memory_bytes = h.memory_bytes.saturating_add(a.memory_bytes);
        }
        h
    }

    /// Tests: what the workload scan reports.
    #[cfg(test)]
    pub fn with_workloads(self, f: AllocSource) -> Self {
        self.0.workloads.lock().unwrap().source = Some(f);
        self
    }

    /// Tests: reuse a workload scan for `ttl` instead of [`WORKLOAD_SCAN_TTL`].
    #[cfg(test)]
    pub fn with_workload_ttl(self, ttl: Duration) -> Self {
        self.0.workloads.lock().unwrap().ttl = Some(ttl);
        self
    }

    /// A Spaces lease was stopped (`owner_active` or `better_offer`).
    pub fn record_preempted(&self, reason: &'static str, leases: u64) {
        *self
            .0
            .preempted
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .entry(reason)
            .or_insert(0) += leases;
    }

    pub fn preempted(&self) -> Value {
        let p = self.0.preempted.lock().unwrap_or_else(|e| e.into_inner());
        let get = |k: &str| p.get(k).copied().unwrap_or(0);
        json!({ "owner_active": get("owner_active"), "better_offer": get("better_offer") })
    }

    /// An offer was turned away for want of budget: remember the best one.
    pub fn want_room(&self, need: Need, price_per_hour: f64) {
        let mut w = self.0.room_wanted.lock().unwrap_or_else(|e| e.into_inner());
        let keep = w.as_ref().is_some_and(|c| {
            c.at.elapsed() < ROOM_WANTED_TTL && c.price_per_hour >= price_per_hour
        });
        if !keep {
            *w = Some(RoomWanted {
                need,
                price_per_hour,
                at: Instant::now(),
            });
        }
    }

    /// The room an offer asked for lately, once (Spaces acts on it).
    pub fn take_room_wanted(&self) -> Option<RoomWanted> {
        self.0
            .room_wanted
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .take()
            .filter(|w| w.at.elapsed() < ROOM_WANTED_TTL)
    }

    /// Release an offer's claim (idempotent).
    pub fn release(&self, id: &str) {
        self.holds().remove(id);
    }

    /// Release a claim when the returned guard drops: the two-phase commit
    /// path, which keeps its hold until the committed work is done.
    pub fn release_on_drop(&self, id: &str) -> HoldGuard {
        HoldGuard {
            rev: self.clone(),
            id: id.to_string(),
            keep: false,
        }
    }

    /// Drop claims nobody released (a lost commit/cancel).
    pub fn sweep(&self, now: Instant) {
        self.holds().retain(|_, h| h.expires > now);
    }

    fn insert(&self, holds: &mut HashMap<String, Hold>, id: &str, need: Need, timeout_secs: f64) {
        let ttl = if timeout_secs > 0.0 {
            Duration::from_secs_f64(timeout_secs.min(86_400.0))
        } else {
            DEFAULT_HOLD
        };
        holds.insert(
            id.to_string(),
            Hold {
                need,
                expires: Instant::now() + ttl + HOLD_GRACE,
            },
        );
    }

    /// Take a claim on the budget for `id`, after `check` (the policy's
    /// admission check, given what is already held) accepts it.
    ///
    /// When `budget` is known and this offer would take the last slot of its
    /// size, it waits up to the ranking window for a better-paying offer that
    /// is arriving at the same moment, and steps aside if one outranks it
    /// (ADR ZC-0025 §5). An offer that leaves room for another does not wait:
    /// the window costs a lone offer on an idle node nothing.
    #[allow(clippy::too_many_arguments)]
    pub fn acquire(
        &self,
        id: &str,
        need: Need,
        score: f64,
        timeout_secs: f64,
        budget: Option<&Limits>,
        check: &dyn Fn(&[Allocation]) -> Result<(), Refusal>,
        outranked: &dyn Fn(String) -> Refusal,
    ) -> Result<HoldGuard, Refusal> {
        let guard = |me: &Self| HoldGuard {
            rev: me.clone(),
            id: id.to_string(),
            keep: false,
        };
        let Some(budget) = budget else {
            let mut holds = self.holds();
            check(&allocations_of(&holds))?;
            self.insert(&mut holds, id, need, timeout_secs);
            return Ok(guard(self));
        };

        // Contended: after this offer, another of its size would not fit.
        let contended = {
            let holds = self.holds();
            let held = held_of(&holds);
            let left = remaining(budget, &held, holds.is_empty());
            fits(&need, left) && {
                let after = (
                    left.0.saturating_sub((need.cpus * 1000.0).round() as u64),
                    left.1.saturating_sub(need.memory_bytes),
                );
                !fits(&need, after)
            }
        };
        let window = self.window();
        let mut registered = false;
        if contended && !window.is_zero() {
            let seq = self.0.seq.fetch_add(1, Ordering::SeqCst);
            self.0
                .waiting
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(Waiter {
                    id: id.to_string(),
                    need,
                    score,
                    seq,
                });
            registered = true;
            std::thread::sleep(window);
        }
        let unregister = |me: &Self| {
            if registered {
                me.0.waiting
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .retain(|w| w.id != id);
            }
        };

        let waiters: Vec<(String, Need, f64, u64)> = self
            .0
            .waiting
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .map(|w| (w.id.clone(), w.need, w.score, w.seq))
            .collect();
        let mut holds = self.holds();
        if registered {
            let left = remaining(budget, &held_of(&holds), holds.is_empty());
            let chosen = pick_ranked(&waiters, left);
            if !chosen.iter().any(|c| c == id) && fits(&need, left) {
                drop(holds);
                unregister(self);
                return Err(outranked(
                    "a better-paying offer took the capacity (revenue per budget-hour)".into(),
                ));
            }
        }
        let verdict = check(&allocations_of(&holds));
        if verdict.is_ok() {
            self.insert(&mut holds, id, need, timeout_secs);
        }
        drop(holds);
        unregister(self);
        verdict.map(|_| guard(self))
    }

    // ---- eligible-idle ----------------------------------------------------------------

    /// A claim loop that is allowed to take work and has free budget came back
    /// with nothing it could take, covering the last `covers` of wall time.
    /// Overlapping sources count once in the total and each in its own line.
    pub fn eligible_idle(&self, source: Source, covers: Duration) {
        self.eligible_idle_at(source, covers, Instant::now());
    }

    pub fn eligible_idle_at(&self, source: Source, covers: Duration, now: Instant) {
        let mut i = self.0.idle.lock().unwrap_or_else(|e| e.into_inner());
        *i.by_source.entry(source.as_str()).or_insert(0.0) += covers.as_secs_f64();
        let start = now.checked_sub(covers).unwrap_or(now);
        let start = match i.covered_to {
            Some(end) if end > start => end,
            _ => start,
        };
        if now > start {
            i.seconds += now.duration_since(start).as_secs_f64();
        }
        i.covered_to = Some(i.covered_to.map_or(now, |e| e.max(now)));
    }

    /// One observation of how much of the budget is in use (0..=1), `dt` long.
    pub fn observe_use(&self, dt: Duration, used: f64) {
        let used = used.clamp(0.0, 1.0);
        let mut i = self.0.idle.lock().unwrap_or_else(|e| e.into_inner());
        i.used_weighted += used * dt.as_secs_f64();
        i.observed += dt.as_secs_f64();
        i.last_used = used;
    }

    pub fn eligible_idle_seconds(&self) -> f64 {
        self.0
            .idle
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .seconds
    }

    /// The counters the owner sees, without the capacity view.
    pub fn counters(&self) -> Value {
        let i = self.0.idle.lock().unwrap_or_else(|e| e.into_inner());
        let by_source: serde_json::Map<String, Value> = i
            .by_source
            .iter()
            .map(|(k, v)| (k.to_string(), json!(round1(*v))))
            .collect();
        let avg = if i.observed > 0.0 {
            i.used_weighted / i.observed
        } else {
            0.0
        };
        let since = self
            .0
            .since
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        json!({
            "eligible_idle_seconds": round1(i.seconds),
            "eligible_idle_by_source": by_source,
            "utilisation": { "now": round3(i.last_used), "avg": round3(avg), "observed_seconds": round1(i.observed) },
            "since": since,
            "preempted": self.preempted(),
        })
    }

    /// Record a push made for another reason.
    pub fn push_sent(&self, now: Instant, signature: u64) {
        self.0.gate.lock().unwrap_or_else(|e| e.into_inner()).last = Some((now, signature));
    }

    /// Whether the capacity view is due at the hub now (see [`PushGate`]).
    pub fn push_due(&self, now: Instant, signature: u64) -> bool {
        self.0
            .gate
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .due(now, signature)
    }
}

fn round1(v: f64) -> f64 {
    (v * 10.0).round() / 10.0
}
fn round3(v: f64) -> f64 {
    (v * 1000.0).round() / 1000.0
}

fn held_of(holds: &HashMap<String, Hold>) -> Held {
    holds.values().fold(Held::default(), |mut h, x| {
        h.cpus += x.need.cpus;
        h.memory_bytes = h.memory_bytes.saturating_add(x.need.memory_bytes);
        h.gpus += x.need.gpus;
        h
    })
}

/// What the holds look like to the admission check: one allocation per
/// admitted offer, so the budget sums are the same ones a container's are.
fn allocations_of(holds: &HashMap<String, Hold>) -> Vec<Allocation> {
    holds
        .iter()
        .map(|(id, h)| Allocation {
            name: id.clone(),
            cpu_millis: (h.need.cpus * 1000.0).round() as u32,
            memory_bytes: h.need.memory_bytes,
        })
        .collect()
}

// ---- the broker's side ----------------------------------------------------------------

/// Is the node open to foreign work at all right now: squads served, not
/// withdrawn, and inside its `when = "schedule"` windows.
pub fn sharing_allowed(p: &Policy, now: LocalTime) -> bool {
    !p.sharing.squads.is_empty()
        && p.sharing.min_price != MinPrice::Withdrawn
        && (p.sharing.when != "schedule" || schedule::is_open(&p.sharing.schedule, now))
}

/// The capacity view of this broker now.
pub fn capacity(state: &BrokerState) -> Capacity {
    capacity::compute(
        &state.workers.list(),
        state.admission.budget_limits().as_ref(),
        state.revenue.held_all(),
    )
}

/// The price the node announces and bills: the cheapest healthy local
/// worker's effective price; `BrokerPrice` only when it has no worker (ADR
/// ZC-0025 §3).
pub fn advert_price(state: &BrokerState, cap: &Capacity) -> f64 {
    cap.price_per_hour.unwrap_or_else(|| state.price.get())
}

/// What an offer would pay: the cheapest healthy local worker that is within
/// the offer's ceiling, else the ceiling itself.
fn quote(state: &BrokerState, offer: &TaskOffer) -> (f64, f64) {
    state
        .workers
        .healthy()
        .into_iter()
        .filter(|w| w.source_node.is_none() && w.pricing.price_per_hour <= offer.max_price_per_hour)
        .map(|w| (w.pricing.price_per_hour, w.pricing.min_charge))
        .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
        .unwrap_or((offer.max_price_per_hour.min(1e6), 0.0))
}

/// Admit a peer offer against the node: the policy's one check with what is
/// already held counted against the budget, then a claim on that budget, with
/// competing offers ranked (ADR ZC-0025 §1, §5). A refusal is counted by
/// reason under `admission`, like every other.
pub fn admit_peer_offer(state: &BrokerState, offer: &TaskOffer) -> Result<HoldGuard, TaskReject> {
    let req = super::admission::offer_request(offer, state.config.owner_user_id.as_deref());
    let need = Need::of_offer(offer);
    let budget = state.admission.budget_limits();
    // Read before the claim: the claim holds the holds lock while it checks.
    let workloads = state.revenue.workloads();
    let cap = capacity(state);
    let (price, min_charge) = quote(state, offer);
    let score = match &budget {
        Some(b) => {
            let gpus = cap.gpu.iter().map(|c| c.gpus.budget).sum();
            revenue_per_budget_hour(
                price,
                min_charge,
                offer.estimated_duration_secs,
                &need,
                &BudgetTotals::of(b, gpus),
            )
        }
        None => 0.0,
    };
    let now = LocalTime::now();
    let admitted = state.revenue.acquire(
        &offer.task_id,
        need,
        score,
        offer.timeout_secs,
        budget.as_ref(),
        &|running| {
            // What other offers hold, plus what sandboxes, guests, leases and
            // jobs hold: one budget for everything.
            let mut all = running.to_vec();
            all.extend(workloads.iter().cloned());
            state.admission.check_with(&req, &all, now)?;
            match vram_shortfall(&cap, offer) {
                Some(why) => Err(state.admission.refuse(&req, Reason::Budget, why)),
                None => Ok(()),
            }
        },
        &|why| state.admission.refuse(&req, Reason::Budget, why),
    );
    admitted.map_err(|r| {
        if r.reason == Reason::Budget && !req.own {
            // A Spaces lease that pays less may give way (`spaces::preempt`).
            state.revenue.want_room(need, price);
        }
        TaskReject {
            task_id: offer.task_id.clone(),
            reason: format!("policy refused ({}): {}", r.reason.as_str(), r.detail),
        }
    })
}

/// An offer that asks for a card size (`min_vram_gb`) no free GPU of the
/// capacity view has. Absent = no floor (every offer before the field).
pub fn vram_shortfall(cap: &Capacity, offer: &TaskOffer) -> Option<String> {
    let min = offer.min_vram_gb?;
    if offer.gpus == 0 || cap.free_gpus(Some(min)) >= offer.gpus {
        return None;
    }
    Some(format!(
        "vram: asks {} GPU(s) of at least {min} GiB, {} free",
        offer.gpus,
        cap.free_gpus(Some(min))
    ))
}

/// A worker-level refusal: the router found no worker with the free CPU,
/// memory, GPUs or VRAM the offer asked for. Counted as `budget`.
pub fn refuse_no_capacity(state: &BrokerState, offer: &TaskOffer, detail: &str) -> TaskReject {
    let req = super::admission::offer_request(offer, state.config.owner_user_id.as_deref());
    let r = state
        .admission
        .refuse(&req, Reason::Budget, detail.to_string());
    TaskReject {
        task_id: offer.task_id.clone(),
        reason: format!("policy refused ({}): {}", r.reason.as_str(), r.detail),
    }
}

/// Everything the owner sees under `revenue` on `/health` and in the agent
/// summary: the capacity view, idle time, utilisation, what is held, and the
/// refusals by reason.
pub fn snapshot(state: &BrokerState) -> Value {
    let cap = capacity(state);
    let mut v = state.revenue.counters();
    let admission = state.admission.snapshot();
    v["capacity"] = serde_json::to_value(&cap).unwrap_or(Value::Null);
    v["held_offers"] = json!(state.revenue.held_count());
    v["refusals"] = admission["refused"].clone();
    v["admitted"] = admission["admitted"].clone();
    let policy = state.admission.policy();
    let owner_blocks = state.admission.owner().blocks(&policy.sharing.when);
    v["sharing_allowed"] =
        json!(sharing_allowed(&policy, LocalTime::now()) && owner_blocks.is_none());
    // Why the owner closes sharing now (`owner-active`, `on-battery`, ...).
    v["owner_yield"] = json!(owner_blocks);
    v["held_workloads"] = json!(state.revenue.workloads().len());
    v["price_per_hour"] = json!(advert_price(state, &cap));
    v
}

/// One broker tick (5 s): expire stale holds, sample utilisation and mirror
/// the snapshot for the agent. Returns whether the capacity view is due at
/// the hub (a change, 15 s floor; 60 s ceiling).
pub fn tick(state: &BrokerState, dt: Duration, home: Option<&Path>, periodic: bool) -> bool {
    let rev = &state.revenue;
    rev.sweep(Instant::now());
    let cap = capacity(state);
    let used = if cap.cpu_cores.budget > 0.0 {
        1.0 - cap.cpu_cores.free / cap.cpu_cores.budget
    } else {
        0.0
    };
    rev.observe_use(dt, used);
    if let Some(home) = home {
        let tmp = home.join(".revenue.json.tmp");
        if std::fs::write(&tmp, snapshot(state).to_string()).is_ok() {
            let _ = std::fs::rename(&tmp, home.join(SNAPSHOT_FILE));
        }
    }
    let now = Instant::now();
    let due = rev.push_due(now, cap.signature());
    if periodic && !due {
        // The old periodic sync goes out regardless; the gate must know, or it
        // would send again one tick later.
        rev.push_sent(now, cap.signature());
    }
    due || periodic
}

/// What the broker last mirrored to `revenue.json`.
pub fn read_snapshot(home: &Path) -> Option<Value> {
    serde_json::from_str(&std::fs::read_to_string(home.join(SNAPSHOT_FILE)).ok()?).ok()
}

// ---- Spaces: how many leases the free budget fits -------------------------------------

/// The Spaces hub accepts at most this many leases per claim.
pub const HUB_MAX_LEASES: usize = 16;

/// How many leases of `unit` size fit what is left of the budget after
/// `held_cpu_millis` / `held_memory`, capped at `ceiling` (ADR ZC-0025 §4).
/// A unit below one core and one GiB counts as that smallest unit, as in the
/// admission check.
pub fn lease_slots(
    budget: &Limits,
    held_cpu_millis: u64,
    held_memory: u64,
    unit: &Need,
    ceiling: usize,
) -> usize {
    let left_cpu = (budget.cpu_millis as u64).saturating_sub(held_cpu_millis);
    let left_mem = budget.memory_bytes.saturating_sub(held_memory);
    let unit_cpu = ((unit.cpus * 1000.0).round() as u64).max(1000);
    let unit_mem = unit.memory_bytes.max(1 << 30);
    let by_cpu = left_cpu / unit_cpu;
    let by_mem = left_mem / unit_mem;
    (by_cpu.min(by_mem) as usize).min(ceiling)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::admit::Request;
    use crate::policy::{Admission, Policy};
    use crate::sandbox::Gpus;

    fn limits(cpu: u32, mem_gib: u64) -> Limits {
        Limits {
            cpu_millis: cpu,
            memory_bytes: mem_gib << 30,
            gpus: Gpus::None,
        }
    }

    fn need(cpus: f64, mem_gib: u64) -> Need {
        Need {
            cpus,
            memory_bytes: mem_gib << 30,
            gpus: 0,
        }
    }

    fn peer_req() -> Request {
        Request::new(Source::PeerOffer, crate::policy::admit::Workload::Function)
    }

    fn acquire(
        rev: &Revenue,
        a: &Admission,
        id: &str,
        n: Need,
        score: f64,
        b: &Limits,
    ) -> Result<HoldGuard, Refusal> {
        let mut req = peer_req();
        req.cpus = n.cpus;
        req.memory_bytes = n.memory_bytes;
        rev.acquire(
            id,
            n,
            score,
            10.0,
            Some(b),
            &|running| a.check_with(&req, running, LocalTime::now()),
            &|why| a.refuse(&req, Reason::Budget, why),
        )
    }

    #[test]
    fn revenue_per_budget_hour_prefers_the_smaller_share_at_the_same_price() {
        let b = BudgetTotals {
            cpus: 8.0,
            memory_bytes: 32 << 30,
            gpus: 0,
        };
        let small = revenue_per_budget_hour(540.0, 0.0, 600.0, &need(1.0, 2), &b);
        let big = revenue_per_budget_hour(540.0, 0.0, 600.0, &need(4.0, 2), &b);
        assert!(small > big * 3.9 && small < big * 4.1, "{small} vs {big}");
        // Paying twice as much for the same hold is twice as good.
        let rich = revenue_per_budget_hour(1080.0, 0.0, 600.0, &need(4.0, 2), &b);
        assert!((rich / big - 2.0).abs() < 1e-9);
    }

    #[test]
    fn the_dominant_share_and_the_minimum_charge_count() {
        let b = BudgetTotals {
            cpus: 8.0,
            memory_bytes: 32 << 30,
            gpus: 1,
        };
        let cpu_only = revenue_per_budget_hour(100.0, 0.0, 3600.0, &need(1.0, 1), &b);
        let whole_gpu = revenue_per_budget_hour(
            100.0,
            0.0,
            3600.0,
            &Need {
                cpus: 1.0,
                memory_bytes: 1 << 30,
                gpus: 1,
            },
            &b,
        );
        assert!(whole_gpu < cpu_only, "holding the only GPU is a full share");
        // A 1 s job on a 1 yen minimum beats its metered price by a lot.
        let metered = revenue_per_budget_hour(540.0, 0.0, 1.0, &need(1.0, 1), &b);
        let floor = revenue_per_budget_hour(540.0, 1.0, 1.0, &need(1.0, 1), &b);
        assert!(floor > metered);
        // No budget size known: the share floor keeps it finite.
        assert!(revenue_per_budget_hour(1.0, 0.0, 1.0, &need(0.0, 0), &b).is_finite());
    }

    #[test]
    fn ranked_picking_takes_the_best_payer_that_fits() {
        let w = |id: &str, cpus, score, seq| (id.to_string(), need(cpus, 1), score, seq);
        let waiting = [
            w("low", 2.0, 10.0, 0),
            w("high", 2.0, 99.0, 1),
            w("mid", 2.0, 50.0, 2),
        ];
        // Room for two 2-core offers.
        assert_eq!(pick_ranked(&waiting, (4000, 8 << 30)), vec!["high", "mid"]);
        // Room for one.
        assert_eq!(pick_ranked(&waiting, (2000, 8 << 30)), vec!["high"]);
        // A big offer that does not fit is skipped, a small worse one is taken.
        let waiting = [w("huge", 8.0, 99.0, 0), w("small", 1.0, 5.0, 1)];
        assert_eq!(pick_ranked(&waiting, (2000, 8 << 30)), vec!["small"]);
        // Equal scores: first come first served.
        let waiting = [w("b", 2.0, 5.0, 1), w("a", 2.0, 5.0, 0)];
        assert_eq!(pick_ranked(&waiting, (2000, 8 << 30)), vec!["a"]);
    }

    #[test]
    fn a_lone_offer_is_admitted_at_once_and_holds_its_share_until_dropped() {
        let b = limits(4000, 8);
        let a = Admission::pinned(Policy::default(), Some(b.clone()));
        let rev = Revenue::new().with_window(Duration::from_secs(5));
        let t = Instant::now();
        // Leaves room for another of its size: no window, no waiting.
        let g = acquire(&rev, &a, "o1", need(1.0, 1), 1.0, &b).unwrap();
        assert!(
            t.elapsed() < Duration::from_secs(2),
            "a lone offer must not wait"
        );
        assert_eq!(rev.held().cpus, 1.0);
        assert_eq!(rev.held_count(), 1);
        drop(g);
        assert_eq!(rev.held_count(), 0);
        assert_eq!(rev.held().cpus, 0.0);
    }

    #[test]
    fn what_is_held_comes_off_the_budget_and_a_refusal_says_budget() {
        let b = limits(4000, 8);
        let a = Admission::pinned(Policy::default(), Some(b.clone()));
        let rev = Revenue::new().with_window(Duration::ZERO);
        let g1 = acquire(&rev, &a, "o1", need(3.0, 2), 1.0, &b).unwrap();
        let e = acquire(&rev, &a, "o2", need(2.0, 2), 1.0, &b)
            .err()
            .unwrap();
        assert_eq!(e.reason, Reason::Budget);
        assert!(e.detail.contains("cpu"), "{}", e.detail);
        assert_eq!(a.snapshot()["refused"]["budget"], 1);
        assert_eq!(rev.held_count(), 1, "a refusal holds nothing");
        // One core is still free.
        let g2 = acquire(&rev, &a, "o3", need(1.0, 1), 1.0, &b).unwrap();
        assert_eq!(rev.held().cpus, 4.0);
        // Finishing the first frees its share.
        drop(g1);
        assert!(acquire(&rev, &a, "o4", need(3.0, 1), 1.0, &b).is_ok());
        drop(g2);
    }

    #[test]
    fn a_kept_hold_lives_until_released_or_swept() {
        let b = limits(4000, 8);
        let a = Admission::pinned(Policy::default(), Some(b.clone()));
        let rev = Revenue::new().with_window(Duration::ZERO);
        acquire(&rev, &a, "two-phase", need(2.0, 1), 1.0, &b)
            .unwrap()
            .keep();
        assert_eq!(rev.held_count(), 1, "reserved, not yet committed");
        {
            let _commit = rev.release_on_drop("two-phase");
            assert_eq!(rev.held_count(), 1, "held while the committed work runs");
        }
        assert_eq!(rev.held_count(), 0);
        // A reservation nobody committed or cancelled is swept after its timeout.
        acquire(&rev, &a, "lost", need(1.0, 1), 1.0, &b)
            .unwrap()
            .keep();
        rev.sweep(Instant::now());
        assert_eq!(rev.held_count(), 1);
        rev.sweep(Instant::now() + Duration::from_secs(10 + 121));
        assert_eq!(rev.held_count(), 0);
    }

    #[test]
    fn the_better_payer_wins_the_last_slot_when_two_arrive_together() {
        let b = limits(2000, 4);
        let a = Admission::pinned(Policy::default(), Some(b.clone()));
        let rev = Revenue::new().with_window(Duration::from_millis(150));
        // Both ask for what is left after the first: only one fits.
        let hold = acquire(&rev, &a, "base", need(1.0, 1), 1.0, &b).unwrap();
        let r1 = rev.clone();
        let (a1, b1) = (a.clone(), b.clone());
        let cheap = std::thread::spawn(move || {
            acquire(&r1, &a1, "cheap", need(1.0, 1), 1.0, &b1).map(|g| {
                g.keep();
            })
        });
        std::thread::sleep(Duration::from_millis(20));
        let rich = acquire(&rev, &a, "rich", need(1.0, 1), 500.0, &b);
        let cheap = cheap.join().unwrap();
        assert!(rich.is_ok(), "the better payer is admitted");
        let e = cheap.unwrap_err();
        assert_eq!(e.reason, Reason::Budget);
        assert!(e.detail.contains("better-paying"), "{}", e.detail);
        assert_eq!(a.snapshot()["refused"]["budget"], 1);
        drop(hold);
    }

    #[test]
    fn eligible_idle_time_is_a_union_with_a_line_per_source() {
        let rev = Revenue::new();
        let t0 = Instant::now();
        let s = |n| Duration::from_secs(n);
        rev.eligible_idle_at(Source::SpacesLease, s(15), t0 + s(15));
        assert!((rev.eligible_idle_seconds() - 15.0).abs() < 1e-6);
        // Another source over the same 10 s adds nothing to the total.
        rev.eligible_idle_at(Source::HubAllocation, s(10), t0 + s(15));
        assert!((rev.eligible_idle_seconds() - 15.0).abs() < 1e-6);
        // The next Spaces claim, 15 s later, adds its 15 s.
        rev.eligible_idle_at(Source::SpacesLease, s(15), t0 + s(30));
        assert!((rev.eligible_idle_seconds() - 30.0).abs() < 1e-6);
        let c = rev.counters();
        assert_eq!(c["eligible_idle_seconds"], 30.0);
        assert_eq!(c["eligible_idle_by_source"]["spaces_lease"], 30.0);
        assert_eq!(c["eligible_idle_by_source"]["hub_allocation"], 10.0);
    }

    #[test]
    fn utilisation_is_time_weighted() {
        let rev = Revenue::new();
        rev.observe_use(Duration::from_secs(30), 0.0);
        rev.observe_use(Duration::from_secs(10), 1.0);
        let u = rev.counters()["utilisation"].clone();
        assert_eq!(u["avg"], 0.25);
        assert_eq!(u["now"], 1.0);
    }

    #[test]
    fn the_push_gate_floors_changes_and_ceilings_silence() {
        let mut g = PushGate::default();
        let t = Instant::now();
        let s = |n| Duration::from_secs(n);
        assert!(g.due(t, 1), "the first view goes out");
        assert!(!g.due(t + s(5), 2), "a change inside the floor waits");
        assert!(g.due(t + s(15), 2), "and goes at the floor");
        assert!(!g.due(t + s(40), 2), "nothing changed");
        assert!(g.due(t + s(75), 2), "the ceiling sends it anyway");
    }

    #[test]
    fn sharing_is_allowed_by_squads_price_and_schedule() {
        let noon = LocalTime {
            weekday: 2,
            minute: 12 * 60,
        };
        let mut p = Policy::default();
        assert!(sharing_allowed(&p, noon));
        p.sharing.schedule = vec!["mon-fri 19:00-08:00".into()];
        p.sharing.when = "schedule".into();
        assert!(!sharing_allowed(&p, noon));
        let night = LocalTime {
            weekday: 2,
            minute: 22 * 60,
        };
        assert!(sharing_allowed(&p, night));
        p.sharing.when = "always".into();
        p.sharing.min_price = MinPrice::Withdrawn;
        assert!(!sharing_allowed(&p, noon));
        let mut p = Policy::default();
        p.sharing.squads = Vec::new();
        assert!(!sharing_allowed(&p, noon));
    }

    #[test]
    fn lease_slots_follow_the_free_budget() {
        let b = limits(16_000, 64);
        let unit = need(2.0, 4);
        assert_eq!(lease_slots(&b, 0, 0, &unit, 16), 8, "cpu bound: 16 / 2");
        assert_eq!(lease_slots(&b, 6000, 0, &unit, 16), 5);
        assert_eq!(
            lease_slots(&b, 0, 40 << 30, &unit, 16),
            6,
            "memory bound: 24 / 4"
        );
        assert_eq!(lease_slots(&b, 0, 0, &unit, 3), 3, "the ceiling holds");
        assert_eq!(lease_slots(&b, 16_000, 0, &unit, 16), 0, "budget used up");
        // A unit of nothing counts as the smallest one.
        assert_eq!(lease_slots(&b, 0, 0, &need(0.0, 0), 16), 16);
        assert_eq!(lease_slots(&limits(500, 1), 0, 0, &need(1.0, 1), 16), 0);
    }

    #[test]
    fn preempted_leases_are_counted_by_reason_in_the_counters() {
        let rev = Revenue::new();
        assert_eq!(rev.counters()["preempted"]["owner_active"], 0);
        rev.record_preempted("owner_active", 2);
        rev.record_preempted("better_offer", 1);
        rev.record_preempted("owner_active", 1);
        let c = rev.counters();
        assert_eq!(c["preempted"]["owner_active"], 3);
        assert_eq!(c["preempted"]["better_offer"], 1);
    }

    #[test]
    fn the_best_refused_offer_is_remembered_once() {
        let rev = Revenue::new();
        rev.want_room(need(1.0, 1), 10.0);
        rev.want_room(need(2.0, 2), 5.0); // pays less: ignored
        rev.want_room(need(4.0, 4), 40.0); // pays more: replaces
        let w = rev.take_room_wanted().unwrap();
        assert_eq!((w.need.cpus, w.price_per_hour), (4.0, 40.0));
        assert!(rev.take_room_wanted().is_none());
    }

    #[test]
    fn the_workload_scan_is_reused_for_a_moment_and_feeds_the_held_total() {
        let calls = Arc::new(AtomicU64::new(0));
        let c = calls.clone();
        let rev = Revenue::new().with_workloads(Arc::new(move || {
            c.fetch_add(1, Ordering::SeqCst);
            vec![Allocation::from_label("zk-sbx", "2000m,1073741824").unwrap()]
        }));
        assert_eq!(rev.workloads().len(), 1);
        let h = rev.held_all();
        assert_eq!((h.cpus, h.memory_bytes), (2.0, 1 << 30));
        assert_eq!(calls.load(Ordering::SeqCst), 1, "one scan serves both");
    }

    #[test]
    fn a_stale_workload_scan_is_served_at_once_and_refreshed_in_the_background() {
        // A scan slower than its reuse window (a Mac: limactl + docker ps).
        let calls = Arc::new(AtomicU64::new(0));
        let c = calls.clone();
        let rev = Revenue::new()
            .with_workloads(Arc::new(move || {
                let n = c.fetch_add(1, Ordering::SeqCst);
                if n > 0 {
                    std::thread::sleep(Duration::from_millis(400));
                }
                let name = format!("zk-sbx-{n}");
                vec![Allocation::from_label(&name, "1000m,1073741824").unwrap()]
            }))
            .with_workload_ttl(Duration::from_millis(20));
        // The first call waits for the first scan: there is nothing else.
        assert_eq!(rev.workloads()[0].name, "zk-sbx-0");
        std::thread::sleep(Duration::from_millis(40));
        // Stale: answered from the last scan without waiting for the next.
        let t = Instant::now();
        for _ in 0..5 {
            assert_eq!(rev.workloads()[0].name, "zk-sbx-0");
        }
        assert!(
            t.elapsed() < Duration::from_millis(200),
            "a stale read waited for the scan: {:?}",
            t.elapsed()
        );
        // The refresh runs on its own thread: wait for it to start (CI
        // runners can be slower to schedule it than five cached reads)...
        let deadline = Instant::now() + Duration::from_secs(5);
        while calls.load(Ordering::SeqCst) < 2 {
            assert!(Instant::now() < deadline, "no refresh was started");
            std::thread::sleep(Duration::from_millis(5));
        }
        // ...then, while it is still in flight (it takes 400 ms), more stale
        // reads neither wait for it nor start another.
        let t = Instant::now();
        for _ in 0..5 {
            assert_eq!(rev.workloads()[0].name, "zk-sbx-0");
        }
        assert!(
            t.elapsed() < Duration::from_millis(200),
            "{:?}",
            t.elapsed()
        );
        assert_eq!(calls.load(Ordering::SeqCst), 2, "one refresh in flight");
        // It lands.
        let deadline = Instant::now() + Duration::from_secs(5);
        while rev.workloads()[0].name != "zk-sbx-1" {
            assert!(Instant::now() < deadline, "the refresh never landed");
            std::thread::sleep(Duration::from_millis(10));
        }
    }

    #[test]
    fn callers_racing_the_first_scan_wait_for_it_instead_of_seeing_an_empty_node() {
        let calls = Arc::new(AtomicU64::new(0));
        let c = calls.clone();
        let rev = Revenue::new().with_workloads(Arc::new(move || {
            c.fetch_add(1, Ordering::SeqCst);
            std::thread::sleep(Duration::from_millis(100));
            vec![Allocation::from_label("zk-sbx", "4000m,8589934592").unwrap()]
        }));
        let seen: Vec<usize> = (0..4)
            .map(|_| {
                let r = rev.clone();
                std::thread::spawn(move || r.workloads().len())
            })
            .collect::<Vec<_>>()
            .into_iter()
            .map(|h| h.join().unwrap())
            .collect();
        assert_eq!(seen, vec![1, 1, 1, 1]);
        assert_eq!(calls.load(Ordering::SeqCst), 1, "one first scan, shared");
    }

    #[test]
    fn a_panicking_scan_does_not_wedge_the_next_one() {
        let calls = Arc::new(AtomicU64::new(0));
        let c = calls.clone();
        let rev = Revenue::new()
            .with_workloads(Arc::new(move || {
                if c.fetch_add(1, Ordering::SeqCst) == 0 {
                    panic!("engine went away");
                }
                vec![Allocation::from_label("zk-sbx", "1000m,1073741824").unwrap()]
            }))
            .with_workload_ttl(Duration::from_millis(1));
        assert!(rev.workloads().is_empty());
        let deadline = Instant::now() + Duration::from_secs(5);
        while rev.workloads().is_empty() {
            assert!(
                Instant::now() < deadline,
                "scanning stayed set after a panic"
            );
            std::thread::sleep(Duration::from_millis(5));
        }
    }
}