zc2 0.0.53

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
//! The one admission check (ADR ZC-0017 ยง5): every job source asks the same
//! pure function before it runs anything for someone else, and a refusal
//! carries a machine-readable reason.
//!
//! | reason | refused because |
//! |---|---|
//! | `squad` | the job's squad is not in `sharing.squads` (no token yet = the public squad) |
//! | `workload` | its kind is switched off (`workloads.*`, Atelier's `gpu-only` and backend list) |
//! | `schedule` | `when = "schedule"` and now is outside every window |
//! | `idle` | the owner is at the machine and `when = "idle"` (or it is on battery with `on_ac_only`, or under memory pressure) |
//! | `price` | the offered price is below `sharing.min_price` (or the price is withdrawn) |
//! | `budget` | it does not fit the budget (or needs a GPU the budget does not grant) |
//!
//! `when = "idle"` is decided from the one owner-activity signal the agent
//! publishes (`policy::owner`, `owner.json`): every source honours it. With no
//! signal published (no agent on this machine) there is nothing to honour; a
//! stale signal counts as an active owner.
//!
//! Work from the node's own account is not foreign: it skips the squad,
//! schedule and price checks, and still has to fit the budget.

use super::owner::{self, Owner};
use super::schedule::{self, LocalTime};
use super::{Atelier, Live, MinPrice, Policy, PUBLIC_SQUAD};
use crate::sandbox::{Allocation, Gpus, HostResources, Limits};
use serde::Serialize;
use serde_json::{json, Value};
use std::collections::{BTreeMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Source {
    PeerOffer,
    SpacesLease,
    HubAllocation,
    EnvGuest,
    AtelierJob,
}

impl Source {
    pub fn as_str(&self) -> &'static str {
        match self {
            Source::PeerOffer => "peer_offer",
            Source::SpacesLease => "spaces_lease",
            Source::HubAllocation => "hub_allocation",
            Source::EnvGuest => "env_guest",
            Source::AtelierJob => "atelier_job",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Workload {
    /// A peer function job: governed by squads, price and budget only.
    Function,
    Environment,
    Space,
    HubServing,
    Atelier {
        backend: Option<String>,
        gpu: bool,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Reason {
    Squad,
    Workload,
    Budget,
    Price,
    Schedule,
    Idle,
}

impl Reason {
    pub const ALL: [Reason; 6] = [
        Reason::Squad,
        Reason::Workload,
        Reason::Budget,
        Reason::Price,
        Reason::Schedule,
        Reason::Idle,
    ];

    pub fn as_str(&self) -> &'static str {
        match self {
            Reason::Squad => "squad",
            Reason::Workload => "workload",
            Reason::Budget => "budget",
            Reason::Price => "price",
            Reason::Schedule => "schedule",
            Reason::Idle => "idle",
        }
    }
}

/// What a job source asks for.
#[derive(Debug, Clone)]
pub struct Request {
    pub source: Source,
    /// The squad from the job's workload token; `None` until tokens exist =
    /// the public squad only.
    pub squad: Option<String>,
    /// The job belongs to this node's own account.
    pub own: bool,
    pub workload: Workload,
    pub cpus: f64,
    pub memory_bytes: u64,
    pub gpus: u32,
    /// Yen per hour on offer, when the source knows it.
    pub price_per_hour: Option<f64>,
}

impl Request {
    pub fn new(source: Source, workload: Workload) -> Self {
        Self {
            source,
            squad: None,
            own: false,
            workload,
            cpus: 0.0,
            memory_bytes: 0,
            gpus: 0,
            price_per_hour: None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Refusal {
    pub reason: Reason,
    pub detail: String,
    pub source: Source,
    pub squad: String,
    /// Unix seconds.
    pub at: u64,
}

impl std::fmt::Display for Refusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "refused ({}): {}", self.reason.as_str(), self.detail)
    }
}

/// The budget a request is held against: the node's total, and what already
/// runs inside it. With nothing listed as running (a peer offer), the
/// smallest unit the router places (one core, one GiB) is never refused: a
/// small node's 50 % must not turn every default offer away.
pub struct BudgetView<'a> {
    pub total: &'a Limits,
    pub running: &'a [Allocation],
}

const MIN_UNIT_CPU_MILLIS: u64 = 1000;
const MIN_UNIT_MEMORY: u64 = 1 << 30;

fn refuse(req: &Request, reason: Reason, detail: String, now_secs: u64) -> Refusal {
    Refusal {
        reason,
        detail,
        source: req.source,
        squad: req
            .squad
            .clone()
            .unwrap_or_else(|| PUBLIC_SQUAD.to_string()),
        at: now_secs,
    }
}

/// The admission check with no owner signal (nothing to honour). Pure: the
/// policy, the request, the wall clock and the budget view are all arguments.
pub fn admit(
    policy: &Policy,
    req: &Request,
    now: LocalTime,
    budget: Option<&BudgetView>,
    now_secs: u64,
) -> Result<(), Refusal> {
    admit_with(policy, req, now, budget, now_secs, Owner::NoSignal)
}

/// [`admit`] with the owner-activity signal.
pub fn admit_with(
    policy: &Policy,
    req: &Request,
    now: LocalTime,
    budget: Option<&BudgetView>,
    now_secs: u64,
    owner: Owner,
) -> Result<(), Refusal> {
    let no = |reason, detail: String| Err(refuse(req, reason, detail, now_secs));

    // 1. squad
    if !req.own {
        let squad = req.squad.as_deref().unwrap_or(PUBLIC_SQUAD);
        if !policy.sharing.squads.iter().any(|s| s == squad) {
            return no(
                Reason::Squad,
                if policy.sharing.squads.is_empty() {
                    "this node serves no squad (sharing.squads is empty)".to_string()
                } else {
                    format!("squad {squad:?} is not in sharing.squads")
                },
            );
        }
    }

    // 2. workload switch
    let gpu_granted = match budget {
        Some(b) => b.total.gpus != Gpus::None,
        None => policy.budget.gpu,
    };
    match &req.workload {
        Workload::Function => {}
        Workload::Environment if !policy.workloads.environments => {
            return no(Reason::Workload, "environments are switched off".into())
        }
        Workload::Space if !policy.workloads.spaces => {
            return no(Reason::Workload, "Spaces are switched off".into())
        }
        Workload::HubServing if !policy.workloads.hub_serving => {
            return no(Reason::Workload, "hub serving is switched off".into())
        }
        Workload::Atelier { backend, gpu } => match &policy.workloads.atelier {
            Atelier::Off => return no(Reason::Workload, "Atelier is switched off".into()),
            Atelier::GpuOnly if !gpu_granted => {
                return no(
                    Reason::Workload,
                    "Atelier is gpu-only and the budget grants no GPU".into(),
                )
            }
            Atelier::GpuOnly if !gpu => {
                return no(
                    Reason::Workload,
                    "Atelier is gpu-only: this job uses no GPU".into(),
                )
            }
            Atelier::Backends(list) => {
                if let Some(b) = backend {
                    if !list.contains(b) {
                        return no(
                            Reason::Workload,
                            format!("Atelier backend {b:?} is not enabled"),
                        );
                    }
                }
            }
            _ => {}
        },
        _ => {}
    }

    // 3. schedule
    if !req.own
        && policy.sharing.when == "schedule"
        && !schedule::is_open(&policy.sharing.schedule, now)
    {
        return no(
            Reason::Schedule,
            "outside every window of sharing.schedule".into(),
        );
    }

    // 3b. the owner: `when = "idle"` (and battery / memory pressure) for every
    // source; the owner's own work never waits for the owner.
    if !req.own {
        if let Some(why) = owner.blocks(&policy.sharing.when) {
            return no(Reason::Idle, format!("the owner is not away ({why})"));
        }
    }

    // 4. price
    if !req.own {
        match (policy.sharing.min_price, req.price_per_hour) {
            (MinPrice::Withdrawn, _) => {
                return no(Reason::Price, "sharing.min_price is -1 (withdrawn)".into())
            }
            (MinPrice::PerHour(floor), Some(p)) if p < floor => {
                return no(
                    Reason::Price,
                    format!("{p} yen/hour is below sharing.min_price {floor}"),
                )
            }
            _ => {}
        }
    }

    // 5. budget
    if let Some(b) = budget {
        // A GPU is passed through to a container or to a peer function job's
        // worker: `budget.gpu = false` refuses both. The node's own account's
        // peer jobs stay exempt (they run on its own workers).
        if req.gpus > 0 && !gpu_granted && !(req.source == Source::PeerOffer && req.own) {
            return no(
                Reason::Budget,
                "it needs a GPU and budget.gpu is off".into(),
            );
        }
        let sum = |f: fn(&Allocation) -> u64| b.running.iter().map(f).sum::<u64>();
        let (cpu_floor, mem_floor) = if b.running.is_empty() {
            (MIN_UNIT_CPU_MILLIS, MIN_UNIT_MEMORY)
        } else {
            (0, 0)
        };
        let cpu_left = (b.total.cpu_millis as u64)
            .saturating_sub(sum(|a| a.cpu_millis as u64))
            .max(cpu_floor);
        let mem_left = b
            .total
            .memory_bytes
            .saturating_sub(sum(|a| a.memory_bytes))
            .max(mem_floor);
        let want_cpu = (req.cpus * 1000.0).round().max(0.0) as u64;
        if want_cpu > cpu_left {
            return no(
                Reason::Budget,
                format!("cpu: asks {} of the {} millicores left", want_cpu, cpu_left),
            );
        }
        if req.memory_bytes > mem_left {
            return no(
                Reason::Budget,
                format!(
                    "memory: asks {} MiB of the {} MiB left",
                    req.memory_bytes >> 20,
                    mem_left >> 20
                ),
            );
        }
    }
    Ok(())
}

// ---- the runtime: live policy + counters ------------------------------------------

const RECENT: usize = 20;
const PERSIST_EVERY: Duration = Duration::from_secs(1);
const SNAPSHOT_FILE: &str = "admission.json";

#[derive(Default)]
struct Stats {
    admitted: u64,
    refused: BTreeMap<Reason, u64>,
    recent: VecDeque<Refusal>,
}

struct Inner {
    live: Live,
    stats: Mutex<Stats>,
    /// Where the counters are mirrored for the agent (`admission.json`).
    persist: Option<PathBuf>,
    last_persist: Mutex<Option<Instant>>,
    /// Tests: a fixed budget instead of reading the host.
    fixed_budget: Mutex<Option<Limits>>,
    /// Where `owner.json` is read: `None` = the zakuro home.
    owner_home: Option<PathBuf>,
    /// The owner signal as last read, kept for [`OWNER_CACHE`] (a busy broker
    /// asks for every offer).
    owner_cache: Mutex<Option<(Instant, Owner)>>,
    /// Tests: a fixed owner instead of the file.
    fixed_owner: Mutex<Option<Owner>>,
}

const OWNER_CACHE: Duration = Duration::from_millis(250);

/// The node's admission state: the live policy, the refusal counters and the
/// last few refusals. Cheap to clone; every clone is the same state.
#[derive(Clone)]
pub struct Admission(Arc<Inner>);

impl Admission {
    /// The process-wide instance: policy from `credentials::dir()`, counters
    /// mirrored to `admission.json` there.
    pub fn process() -> Self {
        static P: OnceLock<Admission> = OnceLock::new();
        P.get_or_init(|| {
            Admission(Arc::new(Inner {
                live: Live::process(),
                stats: Mutex::default(),
                persist: Some(PathBuf::new()),
                last_persist: Mutex::new(None),
                // The unit-test binary must not size its budget from the
                // machine it runs on (CI runners have fewer cores than a dev
                // box, and a peer-offer test then fails on `budget`): a fixed,
                // generous budget there; tests about the budget use `pinned`.
                fixed_budget: Mutex::new(if cfg!(test) {
                    Some(Limits::new(64.0, 256.0, Gpus::All))
                } else {
                    None
                }),
                owner_home: None,
                owner_cache: Mutex::new(None),
                // Likewise the unit-test binary never reads a real owner.json.
                fixed_owner: Mutex::new(if cfg!(test) { Some(Owner::Calm) } else { None }),
            }))
        })
        .clone()
    }

    /// A separate instance over `home`, mirroring nothing.
    pub fn at(home: PathBuf) -> Self {
        Self(Arc::new(Inner {
            live: Live::at(home.clone()),
            stats: Mutex::default(),
            persist: None,
            last_persist: Mutex::new(None),
            fixed_budget: Mutex::new(None),
            owner_home: Some(home),
            owner_cache: Mutex::new(None),
            fixed_owner: Mutex::new(None),
        }))
    }

    /// Tests: serve exactly this policy and this budget.
    #[cfg(test)]
    pub fn pinned(policy: Policy, budget: Option<Limits>) -> Self {
        let a = Self::at(PathBuf::from("/nonexistent-zc-policy"));
        a.0.live.pin(policy);
        *a.0.fixed_budget.lock().unwrap() = budget;
        a
    }

    /// Tests: serve exactly this owner signal.
    #[cfg(test)]
    pub fn pin_owner(&self, owner: Owner) {
        *self.0.fixed_owner.lock().unwrap() = Some(owner);
    }

    /// Tests: serve exactly this policy from now on.
    #[cfg(test)]
    pub fn pin_policy(&self, policy: Policy) {
        self.0.live.pin(policy);
    }

    pub fn policy(&self) -> Arc<Policy> {
        self.0.live.current()
    }

    /// The owner-activity signal now (`owner.json`, see `policy::owner`).
    pub fn owner(&self) -> Owner {
        if let Some(o) = *self.0.fixed_owner.lock().unwrap_or_else(|e| e.into_inner()) {
            return o;
        }
        let mut cache = self.0.owner_cache.lock().unwrap_or_else(|e| e.into_inner());
        if let Some((at, o)) = *cache {
            if at.elapsed() < OWNER_CACHE {
                return o;
            }
        }
        let secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let home = self.0.owner_home.clone().or_else(crate::credentials::dir);
        let o = home.map_or(Owner::NoSignal, |h| {
            owner::read(&h, secs, owner::stale_secs())
        });
        *cache = Some((Instant::now(), o));
        o
    }

    /// Why foreign work is refused for the owner's sake right now, if it is:
    /// what running Spaces leases ask before they stop to make room.
    pub fn owner_yield(&self) -> Option<&'static str> {
        self.owner().blocks(&self.policy().sharing.when)
    }

    /// The node's effective budget total, `None` when it cannot be sized.
    fn total(&self, policy: &Policy) -> Option<Limits> {
        if let Some(l) = self.0.fixed_budget.lock().unwrap().clone() {
            return Some(l);
        }
        policy
            .effective_budget(&|k| std::env::var(k).ok())
            .and_then(|b| b.total(&HostResources::detect()))
            .ok()
    }

    /// The node's budget total now (the live policy, `ZAKURO_BUDGET_*` over it,
    /// sized against this host); `None` when it cannot be sized.
    pub fn budget_limits(&self) -> Option<Limits> {
        self.total(&self.policy())
    }

    /// Count and return a refusal the caller decided itself (a better offer
    /// took the capacity): same counters and `recent` list as a policy refusal.
    pub fn refuse(&self, req: &Request, reason: Reason, detail: String) -> Refusal {
        let secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let f = refuse(req, reason, detail, secs);
        self.record(&Err(f.clone()));
        f
    }

    /// Is this workload kind switched on at all? (The claim loops use it to
    /// stay idle without asking the hub.)
    pub fn workload_enabled(&self, w: &Workload) -> bool {
        let p = self.policy();
        match w {
            Workload::Function => true,
            Workload::Environment => p.workloads.environments,
            Workload::Space => p.workloads.spaces,
            Workload::HubServing => p.workloads.hub_serving,
            Workload::Atelier { .. } => p.workloads.atelier != Atelier::Off,
        }
    }

    /// Check `req` against the live policy now, and record the outcome.
    pub fn check(&self, req: &Request) -> Result<(), Refusal> {
        self.check_with(req, &[], LocalTime::now())
    }

    /// [`check`](Self::check) for a source that knows what already runs.
    pub fn check_with(
        &self,
        req: &Request,
        running: &[Allocation],
        now: LocalTime,
    ) -> Result<(), Refusal> {
        let policy = self.policy();
        let sized = req.cpus > 0.0 || req.memory_bytes > 0 || req.gpus > 0;
        let total = if sized { self.total(&policy) } else { None };
        let view = total.as_ref().map(|t| BudgetView { total: t, running });
        let secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let r = admit_with(&policy, req, now, view.as_ref(), secs, self.owner());
        self.record(&r);
        r
    }

    fn record(&self, r: &Result<(), Refusal>) {
        {
            let mut s = self.0.stats.lock().unwrap_or_else(|e| e.into_inner());
            match r {
                Ok(()) => s.admitted += 1,
                Err(f) => {
                    *s.refused.entry(f.reason).or_insert(0) += 1;
                    if s.recent.len() == RECENT {
                        s.recent.pop_front();
                    }
                    s.recent.push_back(f.clone());
                }
            }
        }
        if r.is_err() {
            self.persist();
        }
    }

    /// Counters by reason and the last refusals, for `/health` and the
    /// agent summary.
    pub fn snapshot(&self) -> Value {
        let s = self.0.stats.lock().unwrap_or_else(|e| e.into_inner());
        let mut refused = serde_json::Map::new();
        for r in Reason::ALL {
            refused.insert(
                r.as_str().to_string(),
                json!(s.refused.get(&r).copied().unwrap_or(0)),
            );
        }
        json!({
            "admitted": s.admitted,
            "refused": refused,
            "recent": s.recent.iter().collect::<Vec<_>>(),
        })
    }

    fn persist(&self) {
        let Some(base) = &self.0.persist else { return };
        {
            let mut last = self
                .0
                .last_persist
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            if last.is_some_and(|t| t.elapsed() < PERSIST_EVERY) {
                return;
            }
            *last = Some(Instant::now());
        }
        let home = if base.as_os_str().is_empty() {
            crate::credentials::dir()
        } else {
            Some(base.clone())
        };
        if let Some(home) = home {
            let tmp = home.join(".admission.json.tmp");
            if std::fs::write(&tmp, self.snapshot().to_string()).is_ok() {
                let _ = std::fs::rename(&tmp, home.join(SNAPSHOT_FILE));
            }
        }
    }
}

/// What the broker last mirrored to `admission.json`; `None` when it never
/// refused anything.
pub fn read_snapshot(home: &Path) -> Option<Value> {
    serde_json::from_str(&std::fs::read_to_string(home.join(SNAPSHOT_FILE)).ok()?).ok()
}

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

    const NOW: LocalTime = LocalTime {
        weekday: 2,
        minute: 12 * 60,
    };

    fn run(p: &Policy, r: &Request) -> Result<(), Refusal> {
        admit(p, r, NOW, None, 0)
    }

    fn req(src: Source, w: Workload) -> Request {
        Request::new(src, w)
    }

    fn reason(r: Result<(), Refusal>) -> &'static str {
        r.unwrap_err().reason.as_str()
    }

    #[test]
    fn the_default_policy_admits_public_work_from_every_source() {
        let p = Policy::default();
        for (s, w) in [
            (Source::PeerOffer, Workload::Function),
            (Source::SpacesLease, Workload::Space),
            (Source::HubAllocation, Workload::HubServing),
            (Source::EnvGuest, Workload::Environment),
        ] {
            assert!(run(&p, &req(s, w)).is_ok(), "{s:?}");
        }
    }

    #[test]
    fn an_empty_squad_list_refuses_foreign_work_but_not_the_owners() {
        let mut p = Policy::default();
        p.sharing.squads = Vec::new();
        assert_eq!(
            reason(run(&p, &req(Source::PeerOffer, Workload::Function))),
            "squad"
        );
        let mut own = req(Source::PeerOffer, Workload::Function);
        own.own = true;
        assert!(run(&p, &own).is_ok());
    }

    #[test]
    fn a_job_from_a_squad_not_listed_is_refused_and_a_listed_one_is_taken() {
        let mut p = Policy::default();
        p.sharing.squads = vec!["lab".into()];
        // No token: the public squad, which this node does not serve.
        assert_eq!(
            reason(run(&p, &req(Source::SpacesLease, Workload::Space))),
            "squad"
        );
        let mut r = req(Source::SpacesLease, Workload::Space);
        r.squad = Some("lab".into());
        assert!(run(&p, &r).is_ok());
        r.squad = Some("other".into());
        assert_eq!(reason(run(&p, &r)), "squad");
    }

    #[test]
    fn each_workload_switch_refuses_only_its_own_kind() {
        let mut p = Policy::default();
        p.workloads.environments = false;
        assert_eq!(
            reason(run(&p, &req(Source::EnvGuest, Workload::Environment))),
            "workload"
        );
        assert!(run(&p, &req(Source::SpacesLease, Workload::Space)).is_ok());
        p.workloads.spaces = false;
        assert_eq!(
            reason(run(&p, &req(Source::SpacesLease, Workload::Space))),
            "workload"
        );
        p.workloads.hub_serving = false;
        assert_eq!(
            reason(run(&p, &req(Source::HubAllocation, Workload::HubServing))),
            "workload"
        );
        assert!(
            run(&p, &req(Source::PeerOffer, Workload::Function)).is_ok(),
            "peer functions have no workload switch"
        );
    }

    #[test]
    fn atelier_gpu_only_needs_a_gpu_job_and_a_gpu_budget() {
        let atelier = |gpu| Workload::Atelier {
            backend: Some("peft".into()),
            gpu,
        };
        let mut p = Policy::default();
        p.workloads.atelier = Atelier::GpuOnly;
        p.budget.gpu = false;
        // gpu-only, budget without GPU.
        assert_eq!(
            reason(run(&p, &req(Source::AtelierJob, atelier(true)))),
            "workload"
        );
        p.budget.gpu = true;
        assert!(run(&p, &req(Source::AtelierJob, atelier(true))).is_ok());
        assert_eq!(
            reason(run(&p, &req(Source::AtelierJob, atelier(false)))),
            "workload"
        );
        p.workloads.atelier = Atelier::On;
        assert!(run(&p, &req(Source::AtelierJob, atelier(false))).is_ok());
        p.workloads.atelier = Atelier::Backends(vec!["ludwig".into()]);
        assert_eq!(
            reason(run(&p, &req(Source::AtelierJob, atelier(true)))),
            "workload"
        );
        p.workloads.atelier = Atelier::Off;
        assert_eq!(
            reason(run(&p, &req(Source::AtelierJob, atelier(true)))),
            "workload"
        );
    }

    #[test]
    fn min_price_is_a_floor_against_the_offered_price() {
        let mut p = Policy::default();
        p.sharing.min_price = MinPrice::PerHour(10.0);
        let mut r = req(Source::PeerOffer, Workload::Function);
        r.price_per_hour = Some(9.99);
        assert_eq!(reason(run(&p, &r)), "price");
        r.price_per_hour = Some(10.0);
        assert!(run(&p, &r).is_ok(), "at the floor is enough");
        r.price_per_hour = None;
        assert!(run(&p, &r).is_ok(), "no price known: nothing to compare");
        p.sharing.min_price = MinPrice::Default;
        r.price_per_hour = Some(0.0);
        assert!(run(&p, &r).is_ok(), "default sets no floor of its own");
        p.sharing.min_price = MinPrice::Withdrawn;
        r.price_per_hour = Some(1e9);
        assert_eq!(
            reason(run(&p, &r)),
            "price",
            "-1 withdraws the node at any price"
        );
    }

    #[test]
    fn the_schedule_only_matters_when_when_says_schedule() {
        let mut p = Policy::default();
        p.sharing.schedule = vec!["mon-fri 19:00-08:00".into()];
        assert!(
            run(&p, &req(Source::PeerOffer, Workload::Function)).is_ok(),
            "idle ignores it"
        );
        p.sharing.when = "schedule".into();
        // Wednesday noon: closed.
        assert_eq!(
            reason(run(&p, &req(Source::PeerOffer, Workload::Function))),
            "schedule"
        );
        let night = LocalTime {
            weekday: 2,
            minute: 22 * 60,
        };
        assert!(admit(
            &p,
            &req(Source::PeerOffer, Workload::Function),
            night,
            None,
            0
        )
        .is_ok());
        // The owner's own work ignores it.
        let mut own = req(Source::PeerOffer, Workload::Function);
        own.own = true;
        assert!(run(&p, &own).is_ok());
    }

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

    #[test]
    fn budget_fit_is_against_the_total_and_what_runs() {
        let p = Policy::default();
        let total = limits(4000, 8, false);
        let mut r = req(Source::EnvGuest, Workload::Environment);
        r.cpus = 2.0;
        r.memory_bytes = 4 << 30;
        let none: [Allocation; 0] = [];
        let v = BudgetView {
            total: &total,
            running: &none,
        };
        assert!(admit(&p, &r, NOW, Some(&v), 0).is_ok());
        r.memory_bytes = 9 << 30;
        assert_eq!(
            admit(&p, &r, NOW, Some(&v), 0).unwrap_err().reason,
            Reason::Budget
        );
        // With a workload already holding 3 of the 4 cores.
        let held = [Allocation::from_label("zk-dep-a", "3000m,1073741824").unwrap()];
        let v = BudgetView {
            total: &total,
            running: &held,
        };
        r.memory_bytes = 1 << 30;
        let e = admit(&p, &r, NOW, Some(&v), 0).unwrap_err();
        assert_eq!(e.reason, Reason::Budget);
        assert!(e.detail.contains("cpu"), "{}", e.detail);
    }

    #[test]
    fn a_gpu_job_needs_a_gpu_budget_and_only_the_owners_peer_jobs_are_exempt() {
        let p = Policy::default();
        let none: [Allocation; 0] = [];
        let mut r = req(Source::EnvGuest, Workload::Environment);
        r.gpus = 1;
        let total = limits(4000, 8, false);
        let v = BudgetView {
            total: &total,
            running: &none,
        };
        assert_eq!(
            admit(&p, &r, NOW, Some(&v), 0).unwrap_err().reason,
            Reason::Budget
        );
        let gpu = limits(4000, 8, true);
        let v = BudgetView {
            total: &gpu,
            running: &none,
        };
        assert!(admit(&p, &r, NOW, Some(&v), 0).is_ok());
        // budget.gpu = false refuses a foreign peer offer for a GPU...
        let mut peer = req(Source::PeerOffer, Workload::Function);
        peer.gpus = 1;
        let v = BudgetView {
            total: &total,
            running: &none,
        };
        let e = admit(&p, &peer, NOW, Some(&v), 0).unwrap_err();
        assert_eq!(e.reason, Reason::Budget);
        assert!(e.detail.contains("budget.gpu"), "{}", e.detail);
        // ...but not the node's own account's.
        peer.own = true;
        assert!(admit(&p, &peer, NOW, Some(&v), 0).is_ok());
    }

    fn at_owner(p: &Policy, r: &Request, o: Owner) -> Result<(), Refusal> {
        admit_with(p, r, NOW, None, 0, o)
    }

    #[test]
    fn when_idle_refuses_every_source_while_the_owner_is_active() {
        let p = Policy::default();
        assert_eq!(p.sharing.when, "idle");
        for (s, w) in [
            (Source::PeerOffer, Workload::Function),
            (Source::SpacesLease, Workload::Space),
            (Source::HubAllocation, Workload::HubServing),
            (Source::EnvGuest, Workload::Environment),
        ] {
            let e = at_owner(&p, &req(s, w.clone()), Owner::Active("owner-active")).unwrap_err();
            assert_eq!(e.reason, Reason::Idle, "{s:?}");
            assert!(e.detail.contains("owner-active"), "{}", e.detail);
            assert!(
                at_owner(&p, &req(s, w.clone()), Owner::Calm).is_ok(),
                "{s:?}"
            );
            assert!(
                at_owner(&p, &req(s, w), Owner::NoSignal).is_ok(),
                "no agent, nothing to honour"
            );
        }
    }

    #[test]
    fn a_stale_signal_is_an_active_owner_but_only_for_when_idle() {
        let mut p = Policy::default();
        let r = req(Source::PeerOffer, Workload::Function);
        let stale = Owner::Active("signal-stale");
        assert_eq!(at_owner(&p, &r, stale).unwrap_err().reason, Reason::Idle);
        p.sharing.when = "always".into();
        assert!(at_owner(&p, &r, stale).is_ok());
    }

    #[test]
    fn battery_and_pressure_refuse_whatever_when_says() {
        let mut p = Policy::default();
        p.sharing.when = "always".into();
        let r = req(Source::SpacesLease, Workload::Space);
        assert_eq!(
            at_owner(&p, &r, Owner::Yielding("on-battery"))
                .unwrap_err()
                .reason,
            Reason::Idle
        );
    }

    #[test]
    fn the_owners_own_work_never_waits_for_the_owner() {
        let p = Policy::default();
        let mut own = req(Source::PeerOffer, Workload::Function);
        own.own = true;
        assert!(at_owner(&p, &own, Owner::Active("owner-active")).is_ok());
        assert!(at_owner(&p, &own, Owner::Yielding("on-battery")).is_ok());
        let mut atelier = req(
            Source::AtelierJob,
            Workload::Atelier {
                backend: None,
                gpu: false,
            },
        );
        atelier.own = true;
        assert!(at_owner(&p, &atelier, Owner::Active("owner-active")).is_ok());
    }

    #[test]
    fn the_admission_reads_the_published_signal_and_counts_idle_refusals() {
        let home = crate::policy::test_home();
        let a = Admission::at(home.clone());
        let r = req(Source::EnvGuest, Workload::Environment);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert!(a.check(&r).is_ok(), "no file: nothing to honour");
        owner::write(
            &home,
            &owner::Snapshot {
                idle: false,
                on_battery: false,
                memory_pressure: false,
                cpu_pressure: false,
                at: now,
                source: "test".into(),
            },
        )
        .unwrap();
        // The signal is cached for a second; a fresh instance reads it.
        let a = Admission::at(home);
        assert_eq!(a.check(&r).unwrap_err().reason, Reason::Idle);
        assert_eq!(a.snapshot()["refused"]["idle"], 1);
        assert_eq!(a.owner_yield(), Some("owner-active"));
    }

    #[test]
    fn a_default_sized_offer_is_never_refused_on_a_small_node() {
        let p = Policy::default();
        let none: [Allocation; 0] = [];
        let tiny = limits(500, 1, false); // half of a 1-core, 2 GiB pod
        let v = BudgetView {
            total: &tiny,
            running: &none,
        };
        let mut r = req(Source::PeerOffer, Workload::Function);
        r.cpus = 1.0;
        r.memory_bytes = 1 << 30;
        assert!(admit(&p, &r, NOW, Some(&v), 0).is_ok());
        r.cpus = 2.0;
        assert_eq!(
            admit(&p, &r, NOW, Some(&v), 0).unwrap_err().reason,
            Reason::Budget
        );
    }

    #[test]
    fn counters_and_the_recent_list_track_refusals_by_reason() {
        let mut p = Policy::default();
        p.sharing.squads = Vec::new();
        let a = Admission::pinned(p, None);
        let r = req(Source::PeerOffer, Workload::Function);
        for _ in 0..25 {
            assert!(a.check(&r).is_err());
        }
        let mut own = r.clone();
        own.own = true;
        assert!(a.check(&own).is_ok());
        let s = a.snapshot();
        assert_eq!(s["admitted"], 1);
        assert_eq!(s["refused"]["squad"], 25);
        assert_eq!(s["refused"]["price"], 0);
        assert_eq!(s["recent"].as_array().unwrap().len(), RECENT, "bounded");
        assert_eq!(s["recent"][0]["reason"], "squad");
        assert_eq!(s["recent"][0]["source"], "peer_offer");
    }

    #[test]
    fn a_sized_check_reads_the_budget_from_the_admission() {
        let a = Admission::pinned(Policy::default(), Some(limits(2000, 2, false)));
        let mut r = req(Source::SpacesLease, Workload::Space);
        r.cpus = 4.0;
        assert_eq!(a.check(&r).unwrap_err().reason, Reason::Budget);
        r.cpus = 1.0;
        assert!(a.check(&r).is_ok());
    }

    #[test]
    fn workload_enabled_follows_the_policy() {
        let mut p = Policy::default();
        p.workloads.spaces = false;
        let a = Admission::pinned(p, None);
        assert!(!a.workload_enabled(&Workload::Space));
        assert!(a.workload_enabled(&Workload::HubServing));
    }
}