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
//! The hub-request claim loop (spec §b "The claim loop"). Runs only while
//! `[hub_allocation].enabled`. Polls `GET /api/hub/requests?open=1`, takes the
//! first request that the purposes allow and that fits the lent slice minus
//! what is already committed, and `POST`s `/api/hub/requests/{id}/claim`.
//!
//! The claim is advisory: nothing starts on the node until the hub dispatches.
//! After a won claim the loop waits for the dispatch (it polls the request's
//! state: `claimed` -> `served`, or back to `open` / `expired` when the hub
//! released it), up to the hub's own `confirm_by` ([`confirm_ttl`]). A served
//! request is settled in fake credits ([`Settler`], [`FakeCredits`]); a
//! released or expired one is dropped. While the owner is at the machine
//! (`policy::owner`, `when = "idle"`) the loop claims nothing and stops waiting
//! on a claim it already holds (the hub reopens it at `confirm_by`).
//!
//! The hub marks a request `served` itself (`POST .../served` is the hub
//! dispatcher's, service credential only), so "report served" here is the node
//! confirming it saw the state flip. Settlement against the hub is not
//! possible yet (no node-side settle route): see [`FakeCredits`].
//!
//! Every candidate also passes the node policy's one admission check
//! (`crate::policy::admit`) before it is claimed.

use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use serde::Deserialize;
use serde_json::{json, Value};

use super::HubAllocation;

pub const POLL_MIN: Duration = Duration::from_secs(15);
pub const POLL_MAX: Duration = Duration::from_secs(120);
/// Empty polls before the interval starts doubling.
pub const EMPTY_BEFORE_BACKOFF: u32 = 4;
/// How long a won claim is held when the hub names no `confirm_by`: the hub's
/// own confirmation window.
pub const CONFIRM_FALLBACK: Duration = Duration::from_secs(120);
/// A `confirm_by` further out than this is not believed.
pub const PENDING_MAX: Duration = Duration::from_secs(600);
const PENDING_MIN: Duration = Duration::from_secs(5);

/// How long to hold a won claim, from the claim reply's `confirm_by` (an
/// RFC 3339 time or Unix seconds): until then, within 5 s and
/// [`PENDING_MAX`]. [`CONFIRM_FALLBACK`] when the reply has none.
pub fn confirm_ttl(body: &str, now: chrono::DateTime<chrono::Utc>) -> Duration {
    let by = serde_json::from_str::<Value>(body)
        .ok()
        .and_then(|v| v.get("confirm_by").cloned());
    let at = match by {
        Some(Value::String(t)) => chrono::DateTime::parse_from_rfc3339(&t)
            .ok()
            .map(|d| d.with_timezone(&chrono::Utc)),
        Some(Value::Number(n)) => n
            .as_f64()
            .and_then(|s| chrono::DateTime::from_timestamp(s as i64, 0)),
        _ => None,
    };
    match at {
        Some(at) => (at - now)
            .to_std()
            .unwrap_or(PENDING_MIN)
            .clamp(PENDING_MIN, PENDING_MAX),
        None => CONFIRM_FALLBACK,
    }
}

/// Would the node policy let this request be claimed? (Squad: hub requests
/// carry no token yet, so they are public-squad work.)
pub fn admitted(gate: &crate::policy::Admission, r: &Request) -> bool {
    use crate::policy::admit::{Request as Ask, Source, Workload};
    let mut ask = Ask::new(Source::HubAllocation, Workload::HubServing);
    ask.memory_bytes = (r.needs.ram_gb * (1u64 << 30) as f64) as u64;
    gate.check(&ask).is_ok()
}

#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq)]
pub struct Needs {
    #[serde(default)]
    pub vram_gb: f64,
    #[serde(default)]
    pub ram_gb: f64,
    #[serde(default)]
    pub disk_gb: f64,
}

#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct Request {
    pub id: String,
    pub kind: String,
    #[serde(default)]
    pub needs: Needs,
}

/// Is a request of `kind` allowed by the opted-in purposes? `batch` rides on
/// `inference`.
pub fn kind_allowed(kind: &str, purpose: &[String]) -> bool {
    let has = |p: &str| purpose.iter().any(|x| x == p);
    match kind {
        "inference" | "batch" => has("inference"),
        "warmup" => has("warmup"),
        _ => false,
    }
}

/// Does `needs` fit the slice once `committed` (claims already held) is taken
/// out? A need the hub leaves out is 0.
pub fn fits(needs: &Needs, slice: &HubAllocation, committed: &Needs) -> bool {
    needs.vram_gb <= slice.vram_gb as f64 - committed.vram_gb
        && needs.ram_gb <= slice.ram_gb as f64 - committed.ram_gb
        && needs.disk_gb <= slice.disk_gb as f64 - committed.disk_gb
}

/// Requests to try, in the hub's order (oldest first), that this node may take.
pub fn candidates<'a>(
    open: &'a [Request],
    slice: &HubAllocation,
    committed: &Needs,
) -> Vec<&'a Request> {
    open.iter()
        .filter(|r| kind_allowed(&r.kind, &slice.purpose) && fits(&r.needs, slice, committed))
        .collect()
}

pub fn parse_requests(body: &str) -> Vec<Request> {
    let Ok(v) = serde_json::from_str::<Value>(body) else {
        return Vec::new();
    };
    v.get("requests")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|r| serde_json::from_value(r.clone()).ok())
                .collect()
        })
        .unwrap_or_default()
}

/// Poll interval: 15 s while requests fit; after four empty polls it doubles
/// per empty poll (30, 60, 120 s cap); any claim resets it.
#[derive(Debug, Default)]
pub struct Cadence {
    empty: u32,
}

impl Cadence {
    pub fn base(&self) -> Duration {
        if self.empty < EMPTY_BEFORE_BACKOFF {
            return POLL_MIN;
        }
        let doublings = (self.empty - EMPTY_BEFORE_BACKOFF + 1).min(6);
        (POLL_MIN * 2u32.pow(doublings)).min(POLL_MAX)
    }
    pub fn empty_poll(&mut self) {
        self.empty = self.empty.saturating_add(1);
    }
    pub fn claimed(&mut self) {
        self.empty = 0;
    }
    /// `base` with +/-20 % jitter from `unit` in [0, 1), clamped to 15..=120 s.
    pub fn with_jitter(&self, unit: f64) -> Duration {
        let f = 0.8 + 0.4 * unit.clamp(0.0, 1.0);
        self.base().mul_f64(f).clamp(POLL_MIN, POLL_MAX)
    }
}

fn jitter_unit() -> f64 {
    let n = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    (n % 1000) as f64 / 1000.0
}

#[derive(Debug, Clone, PartialEq)]
pub enum ClaimOutcome {
    Won,
    /// 409: someone else got it, or it is no longer open.
    Taken,
    /// 403: the opt-in is misconfigured on the hub side.
    Forbidden,
    Failed(String),
}

pub fn outcome_for_status(code: u16) -> ClaimOutcome {
    match code {
        200 => ClaimOutcome::Won,
        409 => ClaimOutcome::Taken,
        403 => ClaimOutcome::Forbidden,
        c => ClaimOutcome::Failed(format!("HTTP {c}")),
    }
}

pub struct HubApi {
    api_url: String,
    api_key: String,
    node_pubkey: String,
}

impl HubApi {
    pub fn new(api_url: &str, api_key: &str, node_pubkey: &str) -> HubApi {
        HubApi {
            api_url: api_url.trim_end_matches('/').to_string(),
            api_key: api_key.to_string(),
            node_pubkey: node_pubkey.to_string(),
        }
    }

    pub fn open_requests(&self) -> Result<Vec<Request>, String> {
        let resp = ureq::get(format!("{}/api/hub/requests?open=1", self.api_url))
            .config()
            .timeout_global(Some(Duration::from_secs(10)))
            .http_status_as_error(false)
            .build()
            .header("X-Broker-Api-Key", &self.api_key)
            .call()
            .map_err(|e| e.to_string())?;
        let code = resp.status().as_u16();
        if !(200..300).contains(&code) {
            return Err(format!("requests HTTP {code}"));
        }
        let body = resp
            .into_body()
            .read_to_string()
            .map_err(|e| e.to_string())?;
        Ok(parse_requests(&body))
    }

    /// The outcome, and for a win how long to hold it (`confirm_ttl`).
    pub fn claim(&self, id: &str) -> (ClaimOutcome, Duration) {
        let body = json!({ "node_pubkey": self.node_pubkey });
        let r = ureq::post(format!("{}/api/hub/requests/{id}/claim", self.api_url))
            .config()
            .timeout_global(Some(Duration::from_secs(10)))
            .http_status_as_error(false)
            .build()
            .header("X-Broker-Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .send(body.to_string().as_str());
        match r {
            Ok(mut resp) => {
                let outcome = outcome_for_status(resp.status().as_u16());
                let hold = if outcome == ClaimOutcome::Won {
                    let body = resp.body_mut().read_to_string().unwrap_or_default();
                    confirm_ttl(&body, chrono::Utc::now())
                } else {
                    CONFIRM_FALLBACK
                };
                (outcome, hold)
            }
            Err(e) => (ClaimOutcome::Failed(e.to_string()), CONFIRM_FALLBACK),
        }
    }
}

/// Where a request is in the hub's lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestState {
    Open,
    Claimed,
    Served,
    Expired,
    /// Not in the feed any more (older than its 24 h window), or a state
    /// this build does not know.
    Gone,
}

/// The state of request `id` in the feed body (`GET /api/hub/requests`).
pub fn parse_state(body: &str, id: &str) -> RequestState {
    let Ok(v) = serde_json::from_str::<Value>(body) else {
        return RequestState::Gone;
    };
    let state = v
        .get("requests")
        .and_then(Value::as_array)
        .and_then(|a| {
            a.iter()
                .find(|r| r.get("id").and_then(Value::as_str) == Some(id))
        })
        .and_then(|r| r.get("state"))
        .and_then(Value::as_str);
    match state {
        Some("open") => RequestState::Open,
        Some("claimed") => RequestState::Claimed,
        Some("served") => RequestState::Served,
        Some("expired") => RequestState::Expired,
        _ => RequestState::Gone,
    }
}

/// What the loop needs of the hub; tests inject a fake.
pub trait Hub {
    fn open_requests(&self) -> Result<Vec<Request>, String>;
    /// The outcome, and for a win how long to hold it.
    fn claim(&self, id: &str) -> (ClaimOutcome, Duration);
    fn state_of(&self, id: &str) -> Result<RequestState, String>;
}

impl Hub for HubApi {
    fn open_requests(&self) -> Result<Vec<Request>, String> {
        HubApi::open_requests(self)
    }
    fn claim(&self, id: &str) -> (ClaimOutcome, Duration) {
        HubApi::claim(self, id)
    }
    fn state_of(&self, id: &str) -> Result<RequestState, String> {
        let resp = ureq::get(format!("{}/api/hub/requests", self.api_url))
            .config()
            .timeout_global(Some(Duration::from_secs(10)))
            .http_status_as_error(false)
            .build()
            .header("X-Broker-Api-Key", &self.api_key)
            .call()
            .map_err(|e| e.to_string())?;
        let code = resp.status().as_u16();
        if !(200..300).contains(&code) {
            return Err(format!("requests HTTP {code}"));
        }
        let body = resp
            .into_body()
            .read_to_string()
            .map_err(|e| e.to_string())?;
        Ok(parse_state(&body, id))
    }
}

/// How often the wait looks at the owner signal (a typed key must stop the
/// wait within this), and how many of those ticks pass between hub polls.
pub const WAIT_TICK: Duration = Duration::from_secs(1);
pub const STATE_EVERY_TICKS: u32 = 5;

#[derive(Debug, Clone, PartialEq)]
pub enum Dispatch {
    /// The hub moved the request to `served`.
    Served,
    /// The hub released the claim (the request is open again).
    Released,
    Expired,
    /// `hold` passed without a dispatch.
    TimedOut,
    /// The owner came back: the wait was dropped.
    Yielded(&'static str),
}

/// Wait for the hub's dispatch of a won claim: one owner check per `tick`, a
/// hub poll every `state_every` ticks, until `hold`. `sleep` is injected so
/// tests run instantly (elapsed time is counted in ticks).
pub fn wait_for_dispatch(
    hub: &dyn Hub,
    id: &str,
    hold: Duration,
    tick: Duration,
    state_every: u32,
    yield_now: &dyn Fn() -> Option<&'static str>,
    sleep: &dyn Fn(Duration),
) -> Dispatch {
    let every = state_every.max(1);
    let mut elapsed = Duration::ZERO;
    let mut n: u32 = 0;
    loop {
        if n.is_multiple_of(every) {
            match hub.state_of(id) {
                Ok(RequestState::Served) => return Dispatch::Served,
                Ok(RequestState::Open) => return Dispatch::Released,
                Ok(RequestState::Expired) | Ok(RequestState::Gone) => return Dispatch::Expired,
                Ok(RequestState::Claimed) | Err(_) => {}
            }
        }
        if let Some(why) = yield_now() {
            return Dispatch::Yielded(why);
        }
        if elapsed >= hold {
            return Dispatch::TimedOut;
        }
        sleep(tick);
        elapsed += tick;
        n += 1;
    }
}

/// A served request, as settled.
#[derive(Debug, Clone, PartialEq)]
pub struct Settlement {
    pub id: String,
    pub kind: String,
    pub needs: Needs,
    pub credits: f64,
}

pub trait Settler {
    /// Settle a served request once; settling the same id again is a no-op
    /// returning `Ok(None)`.
    fn settle(&self, req: &Request) -> Result<Option<Settlement>, String>;
}

/// Fake credits per GB-hour of each resource, for a nominal one-hour serve
/// (the hub gives no duration yet).
pub const FAKE_CREDITS_VRAM_GB_H: f64 = 0.5;
pub const FAKE_CREDITS_RAM_GB_H: f64 = 0.05;
pub const FAKE_CREDITS_DISK_GB_H: f64 = 0.005;

pub fn fake_credits(n: &Needs) -> f64 {
    let c = n.vram_gb * FAKE_CREDITS_VRAM_GB_H
        + n.ram_gb * FAKE_CREDITS_RAM_GB_H
        + n.disk_gb * FAKE_CREDITS_DISK_GB_H;
    (c * 10_000.0).round() / 10_000.0
}

/// Settles in fake credits into `<dir>/hub_settlements.jsonl`, one line per
/// request. MISSING on the hub side: a route to settle real credits for a
/// served request (the hub books its own side when it dispatches); until one
/// exists nothing here moves money.
pub struct FakeCredits {
    pub path: PathBuf,
}

impl FakeCredits {
    pub fn in_dir(dir: &std::path::Path) -> Self {
        Self {
            path: dir.join("hub_settlements.jsonl"),
        }
    }
}

impl Settler for FakeCredits {
    fn settle(&self, req: &Request) -> Result<Option<Settlement>, String> {
        use std::io::Write;
        let seen = std::fs::read_to_string(&self.path).unwrap_or_default();
        let already = seen.lines().any(|l| {
            serde_json::from_str::<Value>(l)
                .ok()
                .and_then(|v| v.get("id").and_then(Value::as_str).map(|i| i == req.id))
                .unwrap_or(false)
        });
        if already {
            return Ok(None);
        }
        let credits = fake_credits(&req.needs);
        let line = json!({
            "id": req.id,
            "kind": req.kind,
            "credits": credits,
            "fake": true,
            "at": chrono::Utc::now().to_rfc3339(),
        });
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
        }
        let mut f = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.path)
            .map_err(|e| e.to_string())?;
        writeln!(f, "{line}").map_err(|e| e.to_string())?;
        Ok(Some(Settlement {
            id: req.id.clone(),
            kind: req.kind.clone(),
            needs: req.needs,
            credits,
        }))
    }
}

/// What one pass of the loop did.
#[derive(Debug, Clone, PartialEq)]
pub enum Round {
    /// The owner is at the machine (or the battery / memory yields): nothing
    /// claimed, nothing waited on.
    Paused(&'static str),
    /// Nothing in the feed this node could take.
    Nothing,
    PollFailed(String),
    Forbidden,
    ClaimFailed(String),
    /// A claim was won and then ran its course.
    Won {
        id: String,
        dispatch: Dispatch,
        settled: Option<Settlement>,
    },
}

/// One pass: yield check, poll, claim the first admitted candidate, and on a
/// win wait for the dispatch and settle a served request.
#[allow(clippy::too_many_arguments)]
pub fn round(
    hub: &dyn Hub,
    gate: &crate::policy::Admission,
    slice: &HubAllocation,
    settler: &dyn Settler,
    tick: Duration,
    state_every: u32,
    sleep: &dyn Fn(Duration),
) -> Round {
    if let Some(why) = gate.owner_yield() {
        return Round::Paused(why);
    }
    let open = match hub.open_requests() {
        Ok(o) => o,
        Err(e) => return Round::PollFailed(e),
    };
    let none = Needs::default();
    for r in candidates(&open, slice, &none) {
        if !admitted(gate, r) {
            continue;
        }
        let (outcome, hold) = hub.claim(&r.id);
        match outcome {
            ClaimOutcome::Won => {
                println!("  [HUB_ALLOC] claimed request {} ({})", r.id, r.kind);
                let dispatch = wait_for_dispatch(
                    hub,
                    &r.id,
                    hold,
                    tick,
                    state_every,
                    &|| gate.owner_yield(),
                    sleep,
                );
                let settled = if dispatch == Dispatch::Served {
                    settler.settle(r).unwrap_or_else(|e| {
                        eprintln!("  [HUB_ALLOC] settle {} failed: {e}", r.id);
                        None
                    })
                } else {
                    None
                };
                return Round::Won {
                    id: r.id.clone(),
                    dispatch,
                    settled,
                };
            }
            ClaimOutcome::Taken => continue,
            ClaimOutcome::Forbidden => return Round::Forbidden,
            ClaimOutcome::Failed(e) => return Round::ClaimFailed(e),
        }
    }
    Round::Nothing
}

/// Start the loop once per process. Idle (re-reads the config each round)
/// until the machine opts in.
pub fn spawn_once(state: Arc<crate::broker::BrokerState>) {
    static STARTED: AtomicBool = AtomicBool::new(false);
    let (Some(api_url), Some(api_key)) =
        (state.config.api_url.clone(), state.config.api_key.clone())
    else {
        return;
    };
    let Some(dir) = crate::credentials::dir() else {
        return;
    };
    if STARTED.swap(true, Ordering::SeqCst) {
        return;
    }
    let pubkey = state.node_key.public_b64();
    let gate = state.admission.clone();
    let revenue = state.revenue.clone();
    let _ = std::thread::Builder::new()
        .name("hub-alloc-claim".into())
        .spawn(move || {
            let api = HubApi::new(&api_url, &api_key, &pubkey);
            let settler = FakeCredits::in_dir(&dir);
            let mut cadence = Cadence::default();
            let mut warned_forbidden = false;
            let mut paused: Option<&'static str> = None;
            let sleep = |d: Duration| std::thread::sleep(d);
            loop {
                std::thread::sleep(cadence.with_jitter(jitter_unit()));
                let Some(slice) = super::load(&dir).filter(|a| a.enabled) else {
                    continue;
                };
                if !gate.workload_enabled(&crate::policy::admit::Workload::HubServing) {
                    continue;
                }
                let r = round(&api, &gate, &slice, &settler, WAIT_TICK, STATE_EVERY_TICKS, &sleep);
                if let Round::Paused(why) = &r {
                    if paused != Some(*why) {
                        eprintln!("  [HUB_ALLOC] paused: {why}");
                    }
                    paused = Some(*why);
                } else if paused.take().is_some() {
                    eprintln!("  [HUB_ALLOC] resumed");
                }
                match r {
                    Round::Won { id, dispatch, settled } => {
                        match (&dispatch, &settled) {
                            (Dispatch::Served, Some(s)) => println!(
                                "  [HUB_ALLOC] request {id} served; settled {} fake credits",
                                s.credits
                            ),
                            (Dispatch::Served, None) => {
                                println!("  [HUB_ALLOC] request {id} served")
                            }
                            (d, _) => eprintln!(
                                "  [HUB_ALLOC] claim {id} not served ({d:?}); released"
                            ),
                        }
                        cadence.claimed();
                    }
                    Round::Paused(_) => cadence.empty_poll(),
                    Round::PollFailed(e) => {
                        eprintln!("  [HUB_ALLOC] poll failed: {e}");
                        cadence.empty_poll();
                    }
                    Round::Forbidden => {
                        if !warned_forbidden {
                            eprintln!("  [HUB_ALLOC] claim refused (403): the opt-in is not accepted by the hub; check `zc hub allocate`");
                            warned_forbidden = true;
                        }
                        cadence.empty_poll();
                    }
                    Round::ClaimFailed(e) => {
                        eprintln!("  [HUB_ALLOC] claim failed: {e}");
                        cadence.empty_poll();
                    }
                    Round::Nothing => {
                        revenue.eligible_idle(
                            crate::policy::admit::Source::HubAllocation,
                            cadence.base(),
                        );
                        cadence.empty_poll();
                    }
                }
            }
        });
}

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

    fn slice(vram: u64, ram: u64, disk: u64, purpose: &[&str]) -> HubAllocation {
        HubAllocation {
            enabled: true,
            vram_gb: vram,
            ram_gb: ram,
            disk_gb: disk,
            purpose: purpose.iter().map(|s| s.to_string()).collect(),
        }
    }
    fn req(id: &str, kind: &str, v: f64, r: f64, d: f64) -> Request {
        Request {
            id: id.into(),
            kind: kind.into(),
            needs: Needs {
                vram_gb: v,
                ram_gb: r,
                disk_gb: d,
            },
        }
    }

    #[test]
    fn fit_checks_each_dimension_against_the_slice_minus_committed() {
        let s = slice(8, 16, 50, &["inference"]);
        let none = Needs::default();
        assert!(fits(
            &req("a", "inference", 8.0, 16.0, 50.0).needs,
            &s,
            &none
        ));
        assert!(!fits(
            &req("a", "inference", 10.0, 16.0, 20.0).needs,
            &s,
            &none
        ));
        assert!(!fits(
            &req("a", "inference", 1.0, 17.0, 1.0).needs,
            &s,
            &none
        ));
        let held = Needs {
            vram_gb: 4.0,
            ram_gb: 0.0,
            disk_gb: 0.0,
        };
        assert!(!fits(
            &req("a", "inference", 5.0, 1.0, 1.0).needs,
            &s,
            &held
        ));
        assert!(fits(&req("a", "inference", 4.0, 1.0, 1.0).needs, &s, &held));
    }

    #[test]
    fn purposes_gate_kinds_and_batch_rides_on_inference() {
        let inf = vec!["inference".to_string()];
        let warm = vec!["warmup".to_string()];
        assert!(kind_allowed("inference", &inf));
        assert!(kind_allowed("batch", &inf));
        assert!(!kind_allowed("warmup", &inf));
        assert!(kind_allowed("warmup", &warm));
        assert!(!kind_allowed("batch", &warm));
        assert!(!kind_allowed("mystery", &inf));
    }

    #[test]
    fn candidates_keep_hub_order_and_skip_misfits() {
        let s = slice(8, 16, 50, &["inference"]);
        let open = vec![
            req("big", "inference", 24.0, 16.0, 20.0),
            req("warm", "warmup", 0.0, 4.0, 5.0),
            req("ok1", "inference", 6.0, 8.0, 10.0),
            req("ok2", "batch", 2.0, 2.0, 2.0),
        ];
        let ids: Vec<&str> = candidates(&open, &s, &Needs::default())
            .iter()
            .map(|r| r.id.as_str())
            .collect();
        assert_eq!(ids, ["ok1", "ok2"]);
    }

    #[test]
    fn parses_the_open_feed_and_tolerates_missing_needs() {
        let body = r#"{"requests":[
            {"id":"req-1","kind":"inference","model_id":"m","needs":{"vram_gb":10,"ram_gb":16,"disk_gb":20},"state":"open"},
            {"id":"req-2","kind":"warmup","template_id":"t","state":"open"},
            {"nonsense":true}]}"#;
        let r = parse_requests(body);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].needs.vram_gb, 10.0);
        assert_eq!(r[1].needs, Needs::default());
        assert!(parse_requests("not json").is_empty());
    }

    #[test]
    fn cadence_is_15s_then_doubles_to_120s_and_resets_on_claim() {
        let mut c = Cadence::default();
        for _ in 0..4 {
            assert_eq!(c.base(), POLL_MIN);
            c.empty_poll();
        }
        let mut seen = Vec::new();
        for _ in 0..6 {
            seen.push(c.base().as_secs());
            c.empty_poll();
        }
        assert_eq!(seen, [30, 60, 120, 120, 120, 120]);
        c.claimed();
        assert_eq!(c.base(), POLL_MIN);
    }

    #[test]
    fn jitter_stays_within_bounds() {
        let mut c = Cadence::default();
        for _ in 0..20 {
            for u in [0.0, 0.5, 0.999] {
                let d = c.with_jitter(u);
                assert!(d >= POLL_MIN && d <= POLL_MAX, "{d:?}");
            }
            c.empty_poll();
        }
    }

    #[test]
    fn status_codes_map_to_outcomes() {
        assert_eq!(outcome_for_status(200), ClaimOutcome::Won);
        assert_eq!(outcome_for_status(409), ClaimOutcome::Taken);
        assert_eq!(outcome_for_status(403), ClaimOutcome::Forbidden);
        assert!(matches!(outcome_for_status(500), ClaimOutcome::Failed(_)));
    }

    #[test]
    fn a_won_claim_is_held_until_the_hubs_confirm_by_not_ten_minutes() {
        use chrono::{TimeZone, Utc};
        let now = Utc.with_ymd_and_hms(2026, 11, 10, 12, 0, 0).unwrap();
        let by = |s: &str| confirm_ttl(&format!(r#"{{"confirm_by":"{s}"}}"#), now).as_secs();
        assert_eq!(by("2026-11-10T12:02:00Z"), 120);
        assert_eq!(by("2026-11-10T14:02:00+02:00"), 120, "any offset");
        assert_eq!(by("2026-11-10T12:00:30Z"), 30);
        assert_eq!(
            by("2026-11-10T11:59:00Z"),
            5,
            "already past: shortly, never negative"
        );
        assert_eq!(by("2026-11-10T20:00:00Z"), 600, "capped");
        let epoch = now.timestamp() + 90;
        assert_eq!(
            confirm_ttl(&format!(r#"{{"confirm_by": {epoch}}}"#), now).as_secs(),
            90
        );
        // No confirm_by (or no body): the hub's own 120 s.
        for body in [
            "{}",
            "",
            "not json",
            r#"{"confirm_by": null}"#,
            r#"{"confirm_by": "soon"}"#,
        ] {
            assert_eq!(confirm_ttl(body, now), CONFIRM_FALLBACK, "{body}");
        }
    }

    #[test]
    fn the_policy_gates_each_candidate() {
        use crate::policy::{Admission, Policy};
        let r = req("a", "inference", 0.0, 4.0, 1.0);
        assert!(admitted(&Admission::pinned(Policy::default(), None), &r));
        let mut closed = Policy::default();
        closed.sharing.squads = Vec::new();
        let gate = Admission::pinned(closed, None);
        assert!(!admitted(&gate, &r));
        assert_eq!(gate.snapshot()["refused"]["squad"], 1);
        let mut off = Policy::default();
        off.workloads.hub_serving = false;
        assert!(!admitted(&Admission::pinned(off, None), &r));
    }

    // ---- dispatch, served, settle (fakes) ----

    use std::cell::RefCell;

    struct FakeHub {
        open: Vec<Request>,
        /// claim outcomes by id; default Won with a 120 s hold.
        taken: Vec<String>,
        /// states returned by successive `state_of` calls (last repeats).
        states: RefCell<Vec<RequestState>>,
        claims: RefCell<Vec<String>>,
    }
    impl FakeHub {
        fn new(open: Vec<Request>, states: Vec<RequestState>) -> Self {
            FakeHub {
                open,
                taken: vec![],
                states: RefCell::new(states),
                claims: RefCell::new(vec![]),
            }
        }
    }
    impl Hub for FakeHub {
        fn open_requests(&self) -> Result<Vec<Request>, String> {
            Ok(self.open.clone())
        }
        fn claim(&self, id: &str) -> (ClaimOutcome, Duration) {
            self.claims.borrow_mut().push(id.to_string());
            if self.taken.iter().any(|t| t == id) {
                (ClaimOutcome::Taken, CONFIRM_FALLBACK)
            } else {
                (ClaimOutcome::Won, Duration::from_secs(120))
            }
        }
        fn state_of(&self, _id: &str) -> Result<RequestState, String> {
            let mut s = self.states.borrow_mut();
            Ok(if s.len() > 1 { s.remove(0) } else { s[0] })
        }
    }

    #[derive(Default)]
    struct MemSettler {
        seen: RefCell<Vec<String>>,
    }
    impl Settler for MemSettler {
        fn settle(&self, req: &Request) -> Result<Option<Settlement>, String> {
            if self.seen.borrow().contains(&req.id) {
                return Ok(None);
            }
            self.seen.borrow_mut().push(req.id.clone());
            Ok(Some(Settlement {
                id: req.id.clone(),
                kind: req.kind.clone(),
                needs: req.needs,
                credits: fake_credits(&req.needs),
            }))
        }
    }

    fn no_sleep(_: Duration) {}

    #[test]
    fn parse_state_reads_the_feed_by_id() {
        let body = r#"{"requests":[{"id":"a","state":"open"},{"id":"b","state":"claimed"},
            {"id":"c","state":"served"},{"id":"d","state":"expired"},{"id":"e","state":"???"}]}"#;
        assert_eq!(parse_state(body, "a"), RequestState::Open);
        assert_eq!(parse_state(body, "b"), RequestState::Claimed);
        assert_eq!(parse_state(body, "c"), RequestState::Served);
        assert_eq!(parse_state(body, "d"), RequestState::Expired);
        assert_eq!(parse_state(body, "e"), RequestState::Gone);
        assert_eq!(parse_state(body, "zz"), RequestState::Gone);
        assert_eq!(parse_state("junk", "a"), RequestState::Gone);
    }

    #[test]
    fn a_won_claim_waits_past_ten_minutes_worth_of_nothing_then_sees_served() {
        // claimed for 3 polls, then served.
        let hub = FakeHub::new(
            vec![],
            vec![
                RequestState::Claimed,
                RequestState::Claimed,
                RequestState::Claimed,
                RequestState::Served,
            ],
        );
        let d = wait_for_dispatch(
            &hub,
            "r",
            Duration::from_secs(120),
            WAIT_TICK,
            STATE_EVERY_TICKS,
            &|| None,
            &no_sleep,
        );
        assert_eq!(d, Dispatch::Served);
    }

    #[test]
    fn wait_ends_on_release_expiry_and_timeout() {
        let go = |states: Vec<RequestState>, hold: u64| {
            let hub = FakeHub::new(vec![], states);
            wait_for_dispatch(
                &hub,
                "r",
                Duration::from_secs(hold),
                WAIT_TICK,
                STATE_EVERY_TICKS,
                &|| None,
                &no_sleep,
            )
        };
        assert_eq!(go(vec![RequestState::Open], 120), Dispatch::Released);
        assert_eq!(go(vec![RequestState::Expired], 120), Dispatch::Expired);
        assert_eq!(go(vec![RequestState::Claimed], 30), Dispatch::TimedOut);
    }

    #[test]
    fn typing_stops_the_wait_within_one_tick() {
        let hub = FakeHub::new(vec![], vec![RequestState::Claimed]);
        let ticks = RefCell::new(0u32);
        let d = wait_for_dispatch(
            &hub,
            "r",
            Duration::from_secs(120),
            WAIT_TICK,
            STATE_EVERY_TICKS,
            // The owner shows up on the third look.
            &|| {
                *ticks.borrow_mut() += 1;
                (*ticks.borrow() >= 3).then_some("owner-active")
            },
            &no_sleep,
        );
        assert_eq!(d, Dispatch::Yielded("owner-active"));
        assert_eq!(
            *ticks.borrow(),
            3,
            "stopped at the first look after the key"
        );
    }

    #[test]
    fn a_won_claim_is_dispatched_served_and_settled_once() {
        use crate::policy::{Admission, Policy};
        let gate = Admission::pinned(Policy::default(), None);
        let s = slice(8, 16, 50, &["inference"]);
        let hub = FakeHub::new(
            vec![
                req("big", "inference", 24.0, 1.0, 1.0),
                req("r1", "inference", 4.0, 1.0, 10.0),
            ],
            vec![RequestState::Claimed, RequestState::Served],
        );
        let settler = MemSettler::default();
        let r = round(&hub, &gate, &s, &settler, WAIT_TICK, 1, &no_sleep);
        let Round::Won {
            id,
            dispatch,
            settled,
        } = r
        else {
            panic!("{r:?}")
        };
        assert_eq!(id, "r1");
        assert_eq!(dispatch, Dispatch::Served);
        let st = settled.expect("settled");
        assert_eq!(
            st.credits,
            fake_credits(&req("r1", "inference", 4.0, 1.0, 10.0).needs)
        );
        assert!(st.credits > 0.0);
        // A second pass over the same request settles nothing more.
        let hub2 = FakeHub::new(
            vec![req("r1", "inference", 4.0, 1.0, 10.0)],
            vec![RequestState::Served],
        );
        let again = round(&hub2, &gate, &s, &settler, WAIT_TICK, 1, &no_sleep);
        assert!(
            matches!(again, Round::Won { settled: None, .. }),
            "{again:?}"
        );
    }

    #[test]
    fn a_taken_request_moves_on_and_an_unserved_claim_is_not_settled() {
        use crate::policy::{Admission, Policy};
        let gate = Admission::pinned(Policy::default(), None);
        let s = slice(8, 16, 50, &["inference"]);
        let mut hub = FakeHub::new(
            vec![
                req("a", "inference", 1.0, 1.0, 1.0),
                req("b", "inference", 1.0, 1.0, 1.0),
            ],
            vec![RequestState::Open],
        );
        hub.taken = vec!["a".into()];
        let settler = MemSettler::default();
        let r = round(&hub, &gate, &s, &settler, WAIT_TICK, 1, &no_sleep);
        assert_eq!(*hub.claims.borrow(), ["a", "b"]);
        assert!(
            matches!(
                r,
                Round::Won { ref id, dispatch: Dispatch::Released, settled: None } if id == "b"
            ),
            "{r:?}"
        );
        assert!(settler.seen.borrow().is_empty());
    }

    #[test]
    fn the_owner_at_the_machine_pauses_claiming_and_resuming_claims_again() {
        use crate::policy::owner::Owner;
        use crate::policy::{Admission, Policy};
        let gate = Admission::pinned(Policy::default(), None);
        let s = slice(8, 16, 50, &["inference"]);
        let hub = FakeHub::new(
            vec![req("r1", "inference", 1.0, 1.0, 1.0)],
            vec![RequestState::Served],
        );
        let settler = MemSettler::default();
        gate.pin_owner(Owner::Active("owner-active"));
        gate.pin_policy({
            let mut p = Policy::default();
            p.sharing.when = "idle".into();
            p
        });
        assert_eq!(
            round(&hub, &gate, &s, &settler, WAIT_TICK, 1, &no_sleep),
            Round::Paused("owner-active")
        );
        assert!(
            hub.claims.borrow().is_empty(),
            "nothing claimed while paused"
        );
        gate.pin_owner(Owner::Calm);
        assert!(matches!(
            round(&hub, &gate, &s, &settler, WAIT_TICK, 1, &no_sleep),
            Round::Won {
                dispatch: Dispatch::Served,
                ..
            }
        ));
    }

    #[test]
    fn fake_credits_settle_to_a_file_once_per_request() {
        let dir = crate::policy::test_home();
        let f = FakeCredits::in_dir(&dir);
        let r = req("r9", "batch", 2.0, 10.0, 20.0);
        let first = f.settle(&r).unwrap().unwrap();
        assert!((first.credits - 1.6).abs() < 1e-9);
        assert_eq!(f.settle(&r).unwrap(), None);
        let text = std::fs::read_to_string(&f.path).unwrap();
        assert_eq!(text.lines().count(), 1);
        assert!(text.contains(r#""fake":true"#));
    }
}