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
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
//! The dispatcher: one agent task that drives every outbox job through
//! `queued → uploading → publishing → running → collecting → done | failed |
//! cancelled` against the hub's Spaces queue (ADR ZC-0021 §3-§5).
//!
//! The rule that matters: before any call that changes something on the hub,
//! the job file records the intent; after it, the result (the hub's own ids).
//! A step that is ambiguous after a crash (the call may or may not have
//! happened) is resolved by READING the hub, never by repeating the call:
//! a Space is found again by the marker in its description, a batch upload by
//! the Space's batch count, a publish by the Space's status.
//!
//! Failures are transient (backoff, the job stays where it is) unless the hub
//! answered 4xx other than 408/429, which is a refusal and ends the job.

use super::spaces_hub::{HubErr, SpacesHub};
use super::spec::{self, visibility_and_squad};
use super::store::{
    now_rfc3339, write_atomic, BatchResult, Counts, Job, JobError, OutFile, ReceiptState,
    Retention, State, Store,
};
use crate::receipt_verify as rv;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::{watch, Notify};

/// `(hub base URL, bearer token)` of the signed-in account, re-read each time
/// so a fresh `zc login` takes effect without a restart.
pub type Creds = Option<(String, String)>;
/// Where `submission.state` events go (`/v2/events` in the agent).
pub type Emit = Arc<dyn Fn(&str, Value) + Send + Sync>;

pub struct Config {
    /// How often the dispatcher looks for work.
    pub tick: Duration,
    /// How long a job waits between hub polls while it runs or mirrors.
    pub poll: Duration,
    pub backoff_base: Duration,
    pub backoff_cap: Duration,
    /// How long a job waits for a login before looking again.
    pub login_retry: Duration,
    pub retention: Retention,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            tick: Duration::from_secs(2),
            poll: Duration::from_secs(10),
            backoff_base: Duration::from_secs(2),
            backoff_cap: Duration::from_secs(300),
            login_retry: Duration::from_secs(15),
            retention: Retention::from_env(),
        }
    }
}

pub struct Dispatcher {
    store: Store,
    creds: Arc<dyn Fn() -> Creds + Send + Sync>,
    emit: Emit,
    cfg: Config,
    wake: Arc<Notify>,
    inflight: Mutex<HashSet<String>>,
    due: Mutex<HashMap<String, Instant>>,
    last_prune: Mutex<Option<Instant>>,
}

enum Flow {
    /// Run the next step now.
    Next,
    /// Nothing to do until this long from now.
    Wait(Duration),
    Stop,
}

enum StepErr {
    Transient(String),
    NoCreds,
    Permanent { code: String, message: String },
}

impl From<HubErr> for StepErr {
    fn from(e: HubErr) -> Self {
        match e {
            HubErr::Transient(m) => StepErr::Transient(m),
            HubErr::Permanent { status, message } => {
                let (code, message) = match status {
                    401 => (
                        "hub_credential_refused",
                        format!(
                            "the hub refused this agent's credential (401: {message}). The Spaces \
                             routes take a hub session token; the `zk_` key `zc login` saves is \
                             not accepted there"
                        ),
                    ),
                    402 => (
                        "insufficient_funds",
                        format!("the hub refused the hold: {message}"),
                    ),
                    403 => ("hub_forbidden", format!("the hub forbids this: {message}")),
                    404 => (
                        "hub_not_found",
                        format!("the hub has no such route or Space: {message}"),
                    ),
                    409 => ("hub_conflict", format!("the hub refused (409): {message}")),
                    400 | 413 | 422 => (
                        "hub_rejected",
                        format!("the hub rejected the job ({status}): {message}"),
                    ),
                    _ => (
                        "hub_refused",
                        format!("the hub refused ({status}): {message}"),
                    ),
                };
                StepErr::Permanent {
                    code: code.into(),
                    message,
                }
            }
        }
    }
}

fn permanent(code: &str, message: impl Into<String>) -> StepErr {
    StepErr::Permanent {
        code: code.into(),
        message: message.into(),
    }
}

fn local(e: std::io::Error) -> StepErr {
    StepErr::Transient(format!("local disk: {e}"))
}

fn counts_of(space: &Value) -> Counts {
    let n = |k: &str| space["counts"][k].as_u64().unwrap_or(0);
    Counts {
        pending: n("pending"),
        claimed: n("claimed"),
        succeeded: n("succeeded"),
        failed: n("failed"),
    }
}

/// The hub only ever names an output file by a safe name; refuse anything
/// else rather than write outside the batch directory.
fn safe_name(n: &str) -> bool {
    !n.is_empty() && n.len() <= 255 && !n.starts_with('.') && !n.contains(['/', '\\', '\0'])
}

impl Dispatcher {
    pub fn new(
        store: Store,
        creds: Arc<dyn Fn() -> Creds + Send + Sync>,
        emit: Emit,
        cfg: Config,
        wake: Arc<Notify>,
    ) -> Arc<Self> {
        Arc::new(Self {
            store,
            creds,
            emit,
            cfg,
            wake,
            inflight: Mutex::new(HashSet::new()),
            due: Mutex::new(HashMap::new()),
            last_prune: Mutex::new(None),
        })
    }

    /// The agent task: look for work every tick (or when woken by a
    /// submission) until told to stop.
    pub async fn run(self: Arc<Self>, mut stop: watch::Receiver<bool>) {
        loop {
            self.tick().await;
            tokio::select! {
                biased;
                _ = stop.wait_for(|s| *s) => break,
                _ = self.wake.notified() => {}
                _ = tokio::time::sleep(self.cfg.tick) => {}
            }
        }
    }

    /// Start a pass over every job that is due and not already being driven.
    pub async fn tick(self: &Arc<Self>) {
        let now = Instant::now();
        for job in self.store.list() {
            let live = !job.state.terminal() || (job.cleanup_cancel && !job.hub.cancel_done);
            if !live {
                continue;
            }
            if self
                .due
                .lock()
                .unwrap()
                .get(&job.id)
                .is_some_and(|t| *t > now)
            {
                continue;
            }
            if !self.inflight.lock().unwrap().insert(job.id.clone()) {
                continue;
            }
            let me = self.clone();
            let id = job.id.clone();
            tokio::spawn(async move {
                me.advance(&id).await;
                me.inflight.lock().unwrap().remove(&id);
            });
        }
        let prune_now = {
            let mut last = self.last_prune.lock().unwrap();
            let due = last.is_none_or(|t| t.elapsed() > Duration::from_secs(3600));
            if due {
                *last = Some(now);
            }
            due
        };
        if prune_now {
            let store = self.store.clone();
            let r = self.cfg.retention;
            let _ = tokio::task::spawn_blocking(move || store.prune(r, chrono::Utc::now())).await;
        }
    }

    /// Run one job as far as it can go right now: until it must wait, has
    /// finished, or hit a failure.
    pub async fn advance(&self, id: &str) {
        let Some(mut job) = self.store.load(id) else {
            return;
        };
        loop {
            match self.step(&mut job).await {
                Ok(Flow::Next) => {
                    self.clear_waiting(&mut job);
                }
                Ok(Flow::Wait(d)) => {
                    self.clear_waiting(&mut job);
                    self.set_due(id, d);
                    return;
                }
                Ok(Flow::Stop) => return,
                Err(StepErr::Transient(m)) => {
                    job.attempts += 1;
                    let shift = (job.attempts - 1).min(16);
                    let delay = self
                        .cfg
                        .backoff_base
                        .checked_mul(1u32 << shift)
                        .unwrap_or(self.cfg.backoff_cap)
                        .min(self.cfg.backoff_cap);
                    self.set_due(id, delay);
                    self.set_waiting(&mut job, m);
                    return;
                }
                Err(StepErr::NoCreds) => {
                    self.set_due(id, self.cfg.login_retry);
                    self.set_waiting(&mut job, "not signed in to the hub: run `zc login`".into());
                    return;
                }
                Err(StepErr::Permanent { code, message }) => {
                    self.fail(&mut job, &code, message);
                    return;
                }
            }
        }
    }

    fn set_due(&self, id: &str, d: Duration) {
        self.due
            .lock()
            .unwrap()
            .insert(id.to_string(), Instant::now() + d);
    }

    fn emit(&self, job: &Job) {
        (self.emit)(
            "submission.state",
            job.summary(self.store.cancel_requested(&job.id)),
        );
    }

    /// Save and tell `/v2/events`: for a change a client can see.
    fn save_emit(&self, job: &mut Job) -> Result<(), StepErr> {
        job.updated_at = now_rfc3339();
        self.store.save(job).map_err(local)?;
        self.emit(job);
        Ok(())
    }

    fn save(&self, job: &mut Job) -> Result<(), StepErr> {
        job.updated_at = now_rfc3339();
        self.store.save(job).map_err(local)
    }

    fn set_waiting(&self, job: &mut Job, why: String) {
        let changed = job.waiting.as_deref() != Some(why.as_str());
        job.waiting = Some(why);
        job.updated_at = now_rfc3339();
        let _ = self.store.save(job);
        if changed {
            self.emit(job);
        }
    }

    fn clear_waiting(&self, job: &mut Job) {
        if job.waiting.is_some() || job.attempts > 0 {
            let had = job.waiting.take().is_some();
            job.attempts = 0;
            let _ = self.save(job);
            if had {
                self.emit(job);
            }
        }
    }

    fn set_state(&self, job: &mut Job, s: State) -> Result<(), StepErr> {
        job.state = s;
        job.waiting = None;
        job.attempts = 0;
        if s.terminal() {
            job.finished_at = Some(now_rfc3339());
        }
        self.save_emit(job)
    }

    /// End a job on a refusal. A job that already made a Space before it ran
    /// leaves the hub holding money for it until the Space is cancelled, so
    /// that is queued as a cleanup.
    fn fail(&self, job: &mut Job, code: &str, message: String) {
        job.error = Some(JobError {
            code: code.into(),
            message,
        });
        let before_run = matches!(job.state, State::Uploading | State::Publishing);
        let may_have_space = job.hub.space_id.is_some() || job.hub.create_intent;
        if before_run && may_have_space && code != "hub_changed" {
            job.cleanup_cancel = true;
        }
        let _ = self.set_state(job, State::Failed);
    }

    fn hub(&self, job: &mut Job) -> Result<SpacesHub, StepErr> {
        let (base, token) = (self.creds)().ok_or(StepErr::NoCreds)?;
        let base = base.trim_end_matches('/').to_string();
        match &job.hub.base {
            Some(b) if *b != base => {
                return Err(permanent(
                    "hub_changed",
                    format!(
                        "this job was made on {b}, but the agent is now signed in to {base}; \
                         it is not moved between hubs"
                    ),
                ))
            }
            Some(_) => {}
            None => {
                job.hub.base = Some(base.clone());
                self.save(job)?;
            }
        }
        Ok(SpacesHub::new(&base, &token))
    }

    async fn step(&self, job: &mut Job) -> Result<Flow, StepErr> {
        if job.state.terminal() {
            return self.cleanup(job).await;
        }
        // A job that is already collecting has finished its work on the hub
        // and been paid for; a cancel then would throw results away.
        if job.state != State::Collecting && self.store.cancel_requested(&job.id) {
            return self.cancel(job).await;
        }
        match job.state {
            State::Queued => {
                self.set_state(job, State::Uploading)?;
                Ok(Flow::Next)
            }
            State::Uploading => self.uploading(job).await,
            State::Publishing => self.publishing(job).await,
            State::Running => self.running(job).await,
            State::Collecting => self.collecting(job).await,
            State::Done | State::Failed | State::Cancelled => Ok(Flow::Stop),
        }
    }

    // ---- uploading -----------------------------------------------------------

    fn space_body(&self, job: &Job) -> Value {
        let (visibility, squad) = visibility_and_squad(&job.spec);
        let r = &job.spec.resources;
        let desc = format!(
            "{}\n\nzc-job:{}",
            job.spec.description.clone().unwrap_or_default().trim(),
            job.id
        );
        let mut body = serde_json::json!({
            "name": job.spec.name,
            "description": desc.trim(),
            "image_ref": job.image.as_given,
            "requirements": {
                "cpus": r.cpus,
                "memory_gb": r.memory_gb,
                "gpus": r.gpus,
                "min_vram_gb": r.min_vram_gb,
                "max_runtime_s": r.max_runtime_s,
                "est_runtime_s": r.est_runtime_s.unwrap_or(r.max_runtime_s),
            },
            // The ceiling, exactly: the hub holds this times the batch count.
            "price_per_batch": job.spec.max_price_per_batch,
            "data_mode": "hub",
            "visibility": visibility,
        });
        if let Some(s) = squad {
            body["squad_id"] = Value::String(s);
        }
        body
    }

    /// The Space this job made, found again by the marker in its description.
    async fn find_by_marker(&self, job: &Job, hub: &SpacesHub) -> Result<Option<Value>, StepErr> {
        let marker = format!("zc-job:{}", job.id);
        Ok(hub.list_spaces().await?.into_iter().find(|s| {
            s["mine"].as_bool().unwrap_or(true)
                && s["description"]
                    .as_str()
                    .is_some_and(|d| d.contains(&marker))
        }))
    }

    fn adopt_space(&self, job: &mut Job, space: &Value) -> Result<String, StepErr> {
        let id = space["id"]
            .as_str()
            .ok_or_else(|| StepErr::Transient("the hub's Space has no id".into()))?
            .to_string();
        job.hub.space_id = Some(id.clone());
        job.hub.image_digest = space["image_digest"].as_str().map(str::to_string);
        if job.image.pinned_digest.is_none() {
            job.image.pinned_digest = job.hub.image_digest.clone();
        }
        self.save_emit(job)?;
        if let (Some(want), Some(got)) = (&job.image.pinned_digest, &job.hub.image_digest) {
            if want != got {
                return Err(permanent(
                    "image_digest_mismatch",
                    format!("the job pins {want} but the hub resolved the image to {got}"),
                ));
            }
        }
        Ok(id)
    }

    async fn ensure_space(&self, job: &mut Job, hub: &SpacesHub) -> Result<String, StepErr> {
        if let Some(id) = &job.hub.space_id {
            return Ok(id.clone());
        }
        // The intent is on disk before the call. If it already was, an
        // earlier attempt may have created the Space and lost the answer:
        // look for it instead of making a second one.
        if job.hub.create_intent {
            if let Some(s) = self.find_by_marker(job, hub).await? {
                return self.adopt_space(job, &s);
            }
        } else {
            job.hub.create_intent = true;
            self.save(job)?;
        }
        let space = hub.create_space(&self.space_body(job)).await?;
        self.adopt_space(job, &space)
    }

    async fn uploading(&self, job: &mut Job) -> Result<Flow, StepErr> {
        let hub = self.hub(job)?;
        let space_id = self.ensure_space(job, &hub).await?;

        let todo: Vec<usize> = (0..job.files.len())
            .filter(|i| !job.files[*i].uploaded)
            .collect();
        for chunk in todo.chunks(500) {
            let req: Vec<(String, String, u64)> = chunk
                .iter()
                .map(|i| {
                    let f = &job.files[*i];
                    (f.upload_name.clone(), f.sha256.clone(), f.size)
                })
                .collect();
            let uploads = hub.presign(&space_id, &req).await?;
            for i in chunk {
                if self.store.cancel_requested(&job.id) {
                    return Ok(Flow::Next);
                }
                let (name, path, sha) = {
                    let f = &job.files[*i];
                    (f.upload_name.clone(), f.path.clone(), f.sha256.clone())
                };
                let up = uploads
                    .iter()
                    .find(|u| u.name == name)
                    .ok_or_else(|| StepErr::Transient(format!("the hub did not presign {name}")))?;
                let bytes = read_verified(&path, &sha).await?;
                hub.put_object(&up.url, &sha, bytes).await?;
                job.files[*i].key = Some(up.key.clone());
                job.files[*i].uploaded = true;
                self.save(job)?;
            }
        }

        if !job.hub.batches_added {
            let n = job.batches.len() as u64;
            let mut post = true;
            if job.hub.batches_intent {
                // The POST may have landed before the crash: it is
                // all-or-nothing, so the Space holds all of them or none.
                let have = counts_of(&hub.get_space(&space_id).await?).total();
                if have == n {
                    post = false;
                } else if have != 0 {
                    return Err(permanent(
                        "batch_count_mismatch",
                        format!("the Space holds {have} batches but this job has {n}"),
                    ));
                }
            } else {
                job.hub.batches_intent = true;
                self.save(job)?;
            }
            if post {
                let mut nd = String::new();
                for b in &job.batches {
                    let inputs: serde_json::Map<String, Value> = b
                        .iter()
                        .map(|(name, idx)| {
                            (
                                name.clone(),
                                Value::String(job.files[*idx].key.clone().unwrap_or_default()),
                            )
                        })
                        .collect();
                    nd.push_str(&serde_json::json!({ "inputs": inputs }).to_string());
                    nd.push('\n');
                }
                let res = hub.add_batches(&space_id, nd).await?;
                if res["added"].as_u64() != Some(n) {
                    return Err(permanent(
                        "batch_count_mismatch",
                        format!("the hub added {} of {n} batches", res["added"]),
                    ));
                }
            }
            job.hub.batches_added = true;
            self.save(job)?;
        }
        self.set_state(job, State::Publishing)?;
        Ok(Flow::Next)
    }

    // ---- publishing ----------------------------------------------------------

    async fn publishing(&self, job: &mut Job) -> Result<Flow, StepErr> {
        let hub = self.hub(job)?;
        let space_id = job.hub.space_id.clone().ok_or_else(|| {
            permanent(
                "internal",
                "a job in `publishing` has no Space; this is a bug",
            )
        })?;
        let space = hub.get_space(&space_id).await?;
        let status = space["status"].as_str().unwrap_or("");
        if status != "draft" {
            // Published already (this attempt, or one before a crash).
            job.hub.published = true;
            job.counts = Some(counts_of(&space));
            self.save(job)?;
            self.set_state(job, State::Running)?;
            return Ok(Flow::Next);
        }
        match space["mirror"]["status"].as_str() {
            Some("ready") => {}
            Some("failed") => {
                return Err(permanent(
                    "mirror_failed",
                    format!(
                        "the hub could not mirror the image: {}",
                        space["mirror"]["error"]
                            .as_str()
                            .unwrap_or("no reason given")
                    ),
                ))
            }
            _ => return Ok(Flow::Wait(self.cfg.poll)),
        }
        job.hub.publish_intent = true;
        self.save(job)?;
        match hub.publish(&space_id).await {
            Ok(_) => {}
            // Lost a race with our own earlier publish: the Space says so.
            Err(HubErr::Permanent { status: 409, .. }) => {
                let again = hub.get_space(&space_id).await?;
                if again["status"].as_str() == Some("draft") {
                    return Err(HubErr::Permanent {
                        status: 409,
                        message: "the Space cannot be published".into(),
                    }
                    .into());
                }
            }
            Err(e) => return Err(e.into()),
        }
        job.hub.published = true;
        self.save(job)?;
        self.set_state(job, State::Running)?;
        Ok(Flow::Next)
    }

    // ---- running -------------------------------------------------------------

    async fn running(&self, job: &mut Job) -> Result<Flow, StepErr> {
        let hub = self.hub(job)?;
        let space_id = job.hub.space_id.clone().unwrap_or_default();
        let space = hub.get_space(&space_id).await?;
        let counts = counts_of(&space);
        if job.counts.as_ref() != Some(&counts) {
            job.counts = Some(counts.clone());
            self.save_emit(job)?;
        }
        let n = job.batches.len() as u64;
        match space["status"].as_str().unwrap_or("") {
            "cancelled" => {
                job.error = Some(JobError {
                    code: "cancelled_by_hub".into(),
                    message: "the Space was cancelled on the hub".into(),
                });
                self.set_state(job, State::Cancelled)?;
                Ok(Flow::Stop)
            }
            status => {
                let settled = counts.pending == 0 && counts.claimed == 0 && counts.total() == n;
                if status == "done" || settled {
                    self.set_state(job, State::Collecting)?;
                    return Ok(Flow::Next);
                }
                let why =
                    (status == "paused").then(|| "the Space is paused on the hub".to_string());
                if job.waiting != why {
                    job.waiting = why;
                    self.save_emit(job)?;
                }
                Ok(Flow::Wait(self.cfg.poll))
            }
        }
    }

    // ---- collecting ----------------------------------------------------------

    async fn all_succeeded(&self, hub: &SpacesHub, id: &str) -> Result<Vec<Value>, StepErr> {
        let mut out = vec![];
        let mut cursor: Option<String> = None;
        loop {
            let page = hub
                .list_batches(id, Some("succeeded"), cursor.as_deref())
                .await?;
            out.extend(page["items"].as_array().cloned().unwrap_or_default());
            match page["next_cursor"].as_str() {
                Some(c) => cursor = Some(c.to_string()),
                None => return Ok(out),
            }
        }
    }

    async fn collecting(&self, job: &mut Job) -> Result<Flow, StepErr> {
        let hub = self.hub(job)?;
        let space_id = job.hub.space_id.clone().unwrap_or_default();
        let items = self.all_succeeded(&hub, &space_id).await?;
        let mut keys: Option<(Vec<rv::TrustedKey>, rv::KeySource)> = None;
        for item in &items {
            let seq = item["seq"].as_u64().unwrap_or(0);
            if job.results.iter().any(|r| r.seq == seq) {
                continue;
            }
            let res = self.collect_batch(job, &hub, item, &mut keys).await?;
            job.results.push(res);
            self.save_emit(job)?;
        }
        let succeeded = job.counts.as_ref().map(|c| c.succeeded).unwrap_or(0);
        if (job.results.len() as u64) < succeeded {
            // The listing lags the counts: look again shortly.
            return Ok(Flow::Wait(self.cfg.poll));
        }
        let failed = job.counts.as_ref().map(|c| c.failed).unwrap_or(0);
        if failed > 0 {
            let dir = self.store.results_dir(&job.id);
            let message = format!(
                "{failed} of {} batches failed on the hub; the outputs of the other {} are in {}",
                job.batches.len(),
                job.results.len(),
                dir.display()
            );
            self.fail(job, "batches_failed", message);
            return Ok(Flow::Stop);
        }
        self.set_state(job, State::Done)?;
        Ok(Flow::Stop)
    }

    async fn collect_batch(
        &self,
        job: &Job,
        hub: &SpacesHub,
        item: &Value,
        keys: &mut Option<(Vec<rv::TrustedKey>, rv::KeySource)>,
    ) -> Result<BatchResult, StepErr> {
        let seq = item["seq"].as_u64().unwrap_or(0);
        let dir = self.store.results_dir(&job.id).join(seq.to_string());
        std::fs::create_dir_all(&dir).map_err(local)?;
        let declared = item["output_hashes"]
            .as_object()
            .cloned()
            .unwrap_or_default();
        let mut names: Vec<&String> = declared.keys().collect();
        names.sort();
        let mut files = vec![];
        for name in names {
            if !safe_name(name) {
                return Err(permanent(
                    "hub_output_name",
                    format!("the hub named an output `{name}`, which is not a plain file name"),
                ));
            }
            let want = declared[name].as_str().unwrap_or("").to_ascii_lowercase();
            let dest = dir.join(name);
            // A file left by an earlier attempt that is already right is kept.
            if let Ok((sha, size)) = spec::sha256_file(&dest) {
                if sha == want {
                    files.push(OutFile {
                        name: name.clone(),
                        sha256: sha,
                        size,
                    });
                    continue;
                }
            }
            let url = item["outputs"][name.as_str()].as_str().ok_or_else(|| {
                permanent(
                    "hub_output_missing",
                    format!("the hub lists output `{name}` but gave no link to it"),
                )
            })?;
            let tmp = dir.join(format!(".{name}.part"));
            let (sha, size) = hub.download(url, &tmp).await?;
            if sha != want {
                let _ = std::fs::remove_file(&tmp);
                return Err(permanent(
                    "output_digest_mismatch",
                    format!(
                        "batch {seq} output `{name}` hashes to {sha}, but the hub declared {want}"
                    ),
                ));
            }
            std::fs::rename(&tmp, &dest).map_err(local)?;
            files.push(OutFile {
                name: name.clone(),
                sha256: sha,
                size,
            });
        }
        let receipt = self.receipt_for(job, hub, item, &dir, &files, keys).await?;
        Ok(BatchResult {
            seq,
            dir: dir.display().to_string(),
            files,
            receipt,
        })
    }

    /// Fetch, verify and store the batch's receipt, then compare each
    /// output's digest with it (ADR ZC-0026 §2).
    async fn receipt_for(
        &self,
        job: &Job,
        hub: &SpacesHub,
        item: &Value,
        dir: &Path,
        files: &[OutFile],
        keys: &mut Option<(Vec<rv::TrustedKey>, rv::KeySource)>,
    ) -> Result<ReceiptState, StepErr> {
        let seq = item["seq"].as_u64().unwrap_or(0);
        let unavailable = |detail: String| -> Result<ReceiptState, StepErr> {
            if job.spec.require_receipts {
                return Err(permanent(
                    "receipt_unavailable",
                    format!("batch {seq}: {detail}, and this job requires receipts"),
                ));
            }
            Ok(ReceiptState {
                status: "unavailable".into(),
                hash: None,
                file: None,
                detail: Some(detail),
                key_source: None,
            })
        };
        let Some(hash) = item["receipt_hash"].as_str().map(str::to_string) else {
            return unavailable(
                "the hub's batch listing carries no receipt hash, and the hub has no route that \
                 finds a batch's receipt"
                    .into(),
            );
        };
        let base = hub.base().to_string();
        let h = hash.clone();
        let fetched = tokio::task::spawn_blocking(move || rv::fetch_receipt(&base, &h))
            .await
            .map_err(|e| StepErr::Transient(e.to_string()))?;
        let signed = match fetched {
            Ok(s) => s,
            Err(e) if e.permanent() => return unavailable(format!("receipt {hash}: {e}")),
            Err(e) => return Err(StepErr::Transient(format!("receipt {hash}: {e}"))),
        };
        if keys.is_none() {
            let base = hub.base().to_string();
            let got = tokio::task::spawn_blocking(move || rv::fetch_pubkeys(&base))
                .await
                .map_err(|e| StepErr::Transient(e.to_string()))?;
            match got {
                Ok(k) => *keys = Some(k),
                Err(e) if e.permanent() => {
                    return unavailable(format!("the hub's receipt keys: {e}"))
                }
                Err(e) => return Err(StepErr::Transient(format!("the hub's receipt keys: {e}"))),
            }
        }
        let (trusted, source) = keys.as_ref().expect("fetched above");
        let verified = rv::verify(&signed, trusted).map_err(|e| {
            permanent(
                "receipt_invalid",
                format!("batch {seq}: receipt {hash} does not verify: {e}"),
            )
        })?;
        if verified.receipt_hash != hash {
            return Err(permanent(
                "receipt_invalid",
                format!("batch {seq}: the receipt does not hash to {hash}"),
            ));
        }
        let local_digests: Vec<String> = files.iter().map(|f| f.sha256.clone()).collect();
        rv::check_output_digests(&verified.body, &local_digests).map_err(|e| {
            permanent(
                "receipt_mismatch",
                format!("batch {seq}: receipt {hash}: {e}"),
            )
        })?;
        let doc = serde_json::json!({
            "receipt_hash": verified.receipt_hash,
            "receipt_json": signed.receipt_json,
            "signature": signed.signature,
        });
        write_atomic(
            &dir.join("receipt.json"),
            serde_json::to_string_pretty(&doc)
                .unwrap_or_default()
                .as_bytes(),
        )
        .map_err(local)?;
        Ok(ReceiptState {
            status: "verified".into(),
            hash: Some(verified.receipt_hash),
            file: Some("receipt.json".into()),
            detail: if verified.legacy {
                Some("legacy v1 receipt".into())
            } else {
                None
            },
            key_source: Some(match source {
                rv::KeySource::Given => "given".into(),
                rv::KeySource::Fetched(_) => "fetched".into(),
            }),
        })
    }

    // ---- cancel and cleanup --------------------------------------------------

    /// Cancel the job's Space on the hub, once. A Space that is already over
    /// (409) or gone (404) needs nothing more.
    async fn cancel_space(&self, job: &mut Job) -> Result<(), StepErr> {
        if job.hub.cancel_done {
            return Ok(());
        }
        if job.hub.space_id.is_some() || job.hub.create_intent {
            let hub = self.hub(job)?;
            let id = match job.hub.space_id.clone() {
                Some(i) => Some(i),
                None => self
                    .find_by_marker(job, &hub)
                    .await?
                    .and_then(|s| s["id"].as_str().map(str::to_string)),
            };
            if let Some(id) = id {
                match hub.cancel(&id).await {
                    Ok(_) => {}
                    Err(HubErr::Permanent {
                        status: 404 | 409, ..
                    }) => {}
                    Err(e) => return Err(e.into()),
                }
            }
        }
        job.hub.cancel_done = true;
        self.save(job)
    }

    async fn cancel(&self, job: &mut Job) -> Result<Flow, StepErr> {
        self.cancel_space(job).await?;
        self.set_state(job, State::Cancelled)?;
        Ok(Flow::Stop)
    }

    /// A job that already ended but left a Space holding money.
    async fn cleanup(&self, job: &mut Job) -> Result<Flow, StepErr> {
        if !job.cleanup_cancel || job.hub.cancel_done {
            return Ok(Flow::Stop);
        }
        match self.cancel_space(job).await {
            Ok(()) => {
                self.save_emit(job)?;
                Ok(Flow::Stop)
            }
            // The hub refuses the cancel: say so on the job and stop trying.
            Err(StepErr::Permanent { message, .. }) => {
                job.hub.cancel_done = true;
                if let Some(e) = &mut job.error {
                    e.message.push_str(&format!(
                        " (the Space could not be cancelled afterwards: {message})"
                    ));
                }
                self.save_emit(job)?;
                Ok(Flow::Stop)
            }
            Err(e) => Err(e),
        }
    }
}

/// Read an input and check it is still what was recorded at submit: a file
/// edited since would otherwise be uploaded under the old digest.
async fn read_verified(path: &str, sha256: &str) -> Result<Vec<u8>, StepErr> {
    let p = path.to_string();
    let want = sha256.to_string();
    let res = tokio::task::spawn_blocking(move || -> std::io::Result<Option<Vec<u8>>> {
        let bytes = std::fs::read(&p)?;
        let got = rv::sha256_hex(&bytes);
        Ok((got == want).then_some(bytes))
    })
    .await
    .map_err(|e| StepErr::Transient(e.to_string()))?;
    match res {
        Ok(Some(b)) => Ok(b),
        Ok(None) => Err(permanent(
            "input_changed",
            format!("{path} changed after the job was submitted"),
        )),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(permanent(
            "input_changed",
            format!("{path} is gone: it was there when the job was submitted"),
        )),
        Err(e) => Err(StepErr::Transient(format!("{path}: {e}"))),
    }
}

#[cfg(test)]
mod tests {
    use super::super::fakehub::FakeHub;
    use super::super::spec::{sample_spec, test_dir};
    use super::super::Outbox;
    use super::*;
    use crate::receipt_verify::testkit::Hub as Signer;

    type Cell = Arc<Mutex<Creds>>;
    type Events = Arc<Mutex<Vec<(String, Value)>>>;

    struct Rig {
        hub: FakeHub,
        home: std::path::PathBuf,
        inputs: std::path::PathBuf,
        outbox: Outbox,
        creds: Cell,
        events: Events,
    }

    fn fast() -> Config {
        Config {
            tick: Duration::from_millis(5),
            poll: Duration::from_millis(2),
            backoff_base: Duration::from_millis(1),
            backoff_cap: Duration::from_millis(4),
            login_retry: Duration::from_millis(1),
            retention: Retention::default(),
        }
    }

    fn rig() -> Rig {
        let hub = FakeHub::start(Some("tok"));
        let home = test_dir("disp-home");
        let creds: Cell = Arc::new(Mutex::new(Some((hub.base.clone(), "tok".to_string()))));
        Rig {
            outbox: Outbox::new(&home),
            hub,
            home,
            inputs: test_dir("disp-in"),
            creds,
            events: Arc::new(Mutex::new(vec![])),
        }
    }

    impl Rig {
        /// A dispatcher, as the agent makes one at start (a restart makes another).
        fn dispatcher(&self) -> Arc<Dispatcher> {
            let c = self.creds.clone();
            let ev = self.events.clone();
            Dispatcher::new(
                Store::new(&self.home),
                Arc::new(move || c.lock().unwrap().clone()),
                Arc::new(move |k, d| ev.lock().unwrap().push((k.to_string(), d))),
                fast(),
                Arc::new(Notify::new()),
            )
        }

        fn submit(&self) -> String {
            self.submit_with(|_| {})
        }

        fn submit_with(&self, f: impl FnOnce(&mut spec::JobSpec)) -> String {
            let mut s = sample_spec(&self.inputs);
            f(&mut s);
            self.outbox.submit(s).unwrap().0.id
        }

        fn job(&self, id: &str) -> Job {
            Store::new(&self.home).load(id).unwrap()
        }

        /// Advance until `until` holds (or fail after a bounded number of passes).
        async fn drive(&self, d: &Dispatcher, id: &str, until: impl Fn(&Job) -> bool) -> Job {
            for _ in 0..300 {
                d.advance(id).await;
                let j = self.job(id);
                if until(&j) {
                    return j;
                }
                tokio::time::sleep(Duration::from_millis(3)).await;
            }
            panic!("job never reached the state: {:?}", self.job(id));
        }

        async fn done(&self, d: &Dispatcher, id: &str) -> Job {
            self.drive(d, id, |j| j.state.terminal()).await
        }
    }

    #[tokio::test]
    async fn a_two_batch_job_goes_through_every_state_to_done_with_verified_receipts() {
        let r = rig();
        let d = r.dispatcher();
        let id = r.submit();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Done, "{:?}", j.error);
        assert_eq!(j.results.len(), 2);
        for (i, res) in j.results.iter().enumerate() {
            let seq = i as u64 + 1;
            assert_eq!(res.seq, seq);
            let dir = Store::new(&r.home).results_dir(&id).join(seq.to_string());
            assert_eq!(
                std::fs::read_to_string(dir.join("out.txt")).unwrap(),
                format!("result-{seq}")
            );
            assert_eq!(res.receipt.status, "verified");
            assert_eq!(res.receipt.key_source.as_deref(), Some("fetched"));
            // The stored receipt is a file `zc verify` takes.
            let doc = std::fs::read_to_string(dir.join("receipt.json")).unwrap();
            let signed = rv::parse_signed(&doc).unwrap();
            let key = r.hub.with(|s| s.signer.trusted());
            rv::verify(&signed, &[key]).unwrap();
        }
        // Each hub step happened once.
        for (k, n) in [
            ("create", 1),
            ("publish", 1),
            ("batches_post", 1),
            ("put", 2),
        ] {
            assert_eq!(r.hub.count(k), n, "{k}");
        }
        // Money: the ceiling, exactly, per batch.
        let body = r.hub.with(|s| s.spaces[0].req.clone());
        assert_eq!(body["price_per_batch"], 50.0);
        assert_eq!(body["image_ref"], "registry.example/app:1");
        // The tag was pinned to what the hub resolved.
        assert!(j
            .image
            .pinned_digest
            .as_deref()
            .unwrap()
            .starts_with("sha256:cccc"));
        // The hub token never went to the object store.
        assert!(!r.hub.with(|s| s.object_auth_seen));
        // States were announced in order.
        let states: Vec<String> = r
            .events
            .lock()
            .unwrap()
            .iter()
            .filter(|(k, _)| k == "submission.state")
            .map(|(_, d)| d["state"].as_str().unwrap().to_string())
            .collect();
        let mut order: Vec<&str> = vec![];
        for s in &states {
            if order.last() != Some(&s.as_str()) {
                order.push(s);
            }
        }
        assert_eq!(
            order,
            ["uploading", "publishing", "running", "collecting", "done"]
        );
    }

    #[tokio::test]
    async fn running_carries_the_hubs_batch_counts() {
        let r = rig();
        r.hub.with(|s| s.auto_complete = false);
        let d = r.dispatcher();
        let id = r.submit();
        let j = r
            .drive(&d, &id, |j| j.state == State::Running && j.counts.is_some())
            .await;
        assert_eq!(
            j.counts.unwrap(),
            Counts {
                pending: 2,
                claimed: 0,
                succeeded: 0,
                failed: 0
            }
        );
        r.hub.with(|s| s.complete_all(0));
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Done);
        assert_eq!(j.counts.unwrap().succeeded, 2);
    }

    #[tokio::test]
    async fn a_restart_resumes_and_never_repeats_a_completed_step() {
        let r = rig();
        r.hub.with(|s| {
            s.fail.insert("presign".into(), [503, 503].into());
        });
        let d1 = r.dispatcher();
        let id = r.submit();
        d1.advance(&id).await;
        let j = r.job(&id);
        assert_eq!(j.state, State::Uploading);
        assert!(
            j.waiting.as_deref().unwrap().contains("503"),
            "{:?}",
            j.waiting
        );
        assert_eq!(j.attempts, 1);
        let space = j.hub.space_id.clone().unwrap();
        // The agent restarts: a new dispatcher over the same outbox.
        let d2 = r.dispatcher();
        let j = r.done(&d2, &id).await;
        assert_eq!(j.state, State::Done, "{:?}", j.error);
        assert_eq!(j.hub.space_id.unwrap(), space);
        assert_eq!(r.hub.count("create"), 1, "never a second Space");
        assert_eq!(r.hub.count("publish"), 1);
        assert_eq!(r.hub.with(|s| s.spaces.len()), 1);
    }

    #[tokio::test]
    async fn a_lost_create_answer_adopts_the_space_by_its_marker() {
        let r = rig();
        r.hub.with(|s| {
            s.fail.insert("create".into(), [503].into());
            s.apply_then_fail.insert("create".into());
        });
        let id = r.submit();
        let d1 = r.dispatcher();
        d1.advance(&id).await;
        assert!(r.job(&id).hub.space_id.is_none());
        assert!(r.job(&id).hub.create_intent, "the intent was on disk first");
        let d2 = r.dispatcher();
        let j = r.done(&d2, &id).await;
        assert_eq!(j.state, State::Done, "{:?}", j.error);
        assert_eq!(r.hub.with(|s| s.spaces.len()), 1, "never a second Space");
        assert_eq!(r.hub.count("create"), 1);
    }

    #[tokio::test]
    async fn a_lost_batches_answer_does_not_post_twice() {
        let r = rig();
        r.hub.with(|s| {
            s.fail.insert("batches_post".into(), [503].into());
            s.apply_then_fail.insert("batches_post".into());
        });
        let id = r.submit();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Done, "{:?}", j.error);
        assert_eq!(r.hub.count("batches_post"), 1);
        assert_eq!(r.hub.with(|s| s.spaces[0].batches.len()), 2);
    }

    #[tokio::test]
    async fn a_lost_publish_answer_does_not_publish_twice() {
        let r = rig();
        r.hub.with(|s| {
            s.fail.insert("publish".into(), [503].into());
            s.apply_then_fail.insert("publish".into());
        });
        let id = r.submit();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Done, "{:?}", j.error);
        assert_eq!(r.hub.count("publish"), 1);
    }

    #[tokio::test]
    async fn a_hub_that_is_down_keeps_the_job_in_its_state_and_it_recovers() {
        let r = rig();
        r.hub.with(|s| {
            s.fail.insert("create".into(), [503, 500, 429, 408].into());
        });
        let id = r.submit();
        let d = r.dispatcher();
        for _ in 0..4 {
            d.advance(&id).await;
            let j = r.job(&id);
            assert_eq!(j.state, State::Uploading, "transient never fails a job");
            assert!(j.waiting.is_some());
        }
        assert_eq!(r.job(&id).attempts, 4);
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Done);
        assert_eq!(j.attempts, 0);
        assert!(j.waiting.is_none());
    }

    #[tokio::test]
    async fn a_refusal_fails_the_job_at_once_and_the_hubs_words_are_kept() {
        let r = rig();
        r.hub.with(|s| {
            s.fail.insert("publish".into(), [402].into());
        });
        let id = r.submit();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        let e = j.error.unwrap();
        assert_eq!(e.code, "insufficient_funds");
        assert_eq!(r.hub.count("publish"), 1, "not retried");
        // The Space it made holds nothing but is cancelled so it cannot linger.
        d.advance(&id).await;
        assert_eq!(r.hub.count("cancel"), 1);
        assert_eq!(r.hub.with(|s| s.spaces[0].status.clone()), "cancelled");
        d.advance(&id).await;
        assert_eq!(r.hub.count("cancel"), 1, "cleanup runs once");
    }

    #[tokio::test]
    async fn the_hub_refusing_the_agents_credential_is_a_clear_permanent_failure() {
        let r = rig();
        *r.creds.lock().unwrap() = Some((r.hub.base.clone(), "zk_1_not-a-session".into()));
        let id = r.submit();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        let e = j.error.unwrap();
        assert_eq!(e.code, "hub_credential_refused");
        assert!(
            e.message.contains("session token") && e.message.contains("zk_"),
            "{}",
            e.message
        );
        assert_eq!(r.hub.with(|s| s.spaces.len()), 0);
    }

    #[tokio::test]
    async fn without_a_login_the_job_waits_and_goes_on_after_one() {
        let r = rig();
        *r.creds.lock().unwrap() = None;
        let id = r.submit();
        let d = r.dispatcher();
        d.advance(&id).await;
        let j = r.job(&id);
        assert_eq!(j.state, State::Uploading);
        assert!(j.waiting.unwrap().contains("zc login"));
        assert_eq!(r.hub.with(|s| s.calls.len()), 0);
        *r.creds.lock().unwrap() = Some((r.hub.base.clone(), "tok".into()));
        assert_eq!(r.done(&d, &id).await.state, State::Done);
    }

    #[tokio::test]
    async fn a_job_is_not_moved_to_another_hub() {
        let r = rig();
        r.hub.with(|s| s.auto_complete = false);
        let d = r.dispatcher();
        let id = r.submit();
        r.drive(&d, &id, |j| j.state == State::Running).await;
        let other = FakeHub::start(Some("tok"));
        *r.creds.lock().unwrap() = Some((other.base.clone(), "tok".into()));
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        assert_eq!(j.error.unwrap().code, "hub_changed");
        assert_eq!(other.with(|s| s.calls.len()), 0);
    }

    #[tokio::test]
    async fn cancel_while_running_cancels_the_space_once() {
        let r = rig();
        r.hub.with(|s| s.auto_complete = false);
        let d = r.dispatcher();
        let id = r.submit();
        r.drive(&d, &id, |j| j.state == State::Running).await;
        Store::new(&r.home).request_cancel(&id).unwrap();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Cancelled);
        assert_eq!(r.hub.count("cancel"), 1);
        assert_eq!(r.hub.with(|s| s.spaces[0].status.clone()), "cancelled");
        d.advance(&id).await;
        assert_eq!(r.hub.count("cancel"), 1);
    }

    #[tokio::test]
    async fn cancel_before_anything_ran_never_touches_the_hub() {
        let r = rig();
        let id = r.submit();
        Store::new(&r.home).request_cancel(&id).unwrap();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Cancelled);
        assert_eq!(r.hub.with(|s| s.calls.len()), 0);
    }

    #[tokio::test]
    async fn a_digest_the_hub_resolves_differently_fails_and_cancels_the_space() {
        let r = rig();
        let id =
            r.submit_with(|s| s.image = format!("registry.example/app@sha256:{}", "a".repeat(64)));
        // The fake echoes a pinned digest, so make the pin disagree.
        let want = format!("sha256:{}", "b".repeat(64));
        let mut job = r.job(&id);
        job.image.pinned_digest = Some(want.clone());
        Store::new(&r.home).save(&job).unwrap();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        assert_eq!(j.error.unwrap().code, "image_digest_mismatch");
        assert_eq!(r.hub.count("put"), 0, "nothing uploaded");
        d.advance(&id).await;
        assert_eq!(r.hub.with(|s| s.spaces[0].status.clone()), "cancelled");
    }

    #[tokio::test]
    async fn an_input_edited_after_submit_is_not_uploaded() {
        let r = rig();
        let id = r.submit();
        std::fs::write(r.inputs.join("b.txt"), "changed after submit").unwrap();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        let e = j.error.unwrap();
        assert_eq!(e.code, "input_changed");
        assert!(e.message.contains("b.txt"));
        d.advance(&id).await;
        assert_eq!(r.hub.with(|s| s.spaces[0].status.clone()), "cancelled");
    }

    #[tokio::test]
    async fn an_output_that_does_not_match_the_hubs_digest_fails_the_job() {
        let r = rig();
        r.hub.with(|s| s.tamper_output = true);
        let id = r.submit();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        assert_eq!(j.error.unwrap().code, "output_digest_mismatch");
        assert!(!Store::new(&r.home)
            .results_dir(&id)
            .join("1/out.txt")
            .exists());
    }

    #[tokio::test]
    async fn a_receipt_that_does_not_cover_the_outputs_blocks_done() {
        let r = rig();
        r.hub.with(|s| s.bad_receipt_outputs = true);
        let id = r.submit();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        assert_eq!(j.error.unwrap().code, "receipt_mismatch");
    }

    #[tokio::test]
    async fn a_receipt_signed_by_an_unknown_key_blocks_done() {
        let r = rig();
        r.hub.with(|s| s.auto_complete = false);
        let d = r.dispatcher();
        let id = r.submit();
        r.drive(&d, &id, |j| j.state == State::Running).await;
        r.hub.with(|s| {
            s.complete_all(0);
            // The hub now publishes a different key than the one that signed.
            s.signer = Signer::new();
        });
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        assert_eq!(j.error.unwrap().code, "receipt_invalid");
    }

    #[tokio::test]
    async fn without_a_receipt_hash_the_job_is_done_and_says_the_receipt_is_unavailable() {
        let r = rig();
        r.hub.with(|s| s.with_receipt_hash = false);
        let id = r.submit();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Done);
        assert!(j.results.iter().all(|x| x.receipt.status == "unavailable"));
        assert!(j.results[0]
            .receipt
            .detail
            .as_deref()
            .unwrap()
            .contains("no route"));
        assert_eq!(j.summary(false)["receipts_verified"], 0);
    }

    #[tokio::test]
    async fn require_receipts_makes_a_missing_receipt_a_failure() {
        let r = rig();
        r.hub.with(|s| s.with_receipt_hash = false);
        let id = r.submit_with(|s| s.require_receipts = true);
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        assert_eq!(j.error.unwrap().code, "receipt_unavailable");
    }

    #[tokio::test]
    async fn a_failed_batch_fails_the_job_but_keeps_what_finished() {
        let r = rig();
        r.hub.with(|s| s.fail_second_batch = true);
        let id = r.submit();
        let d = r.dispatcher();
        let j = r.done(&d, &id).await;
        assert_eq!(j.state, State::Failed);
        assert_eq!(j.error.unwrap().code, "batches_failed");
        assert_eq!(j.results.len(), 1);
        assert!(Store::new(&r.home)
            .results_dir(&id)
            .join("1/out.txt")
            .exists());
        d.advance(&id).await;
        assert_eq!(r.hub.count("cancel"), 0, "finished work is not cancelled");
    }

    #[tokio::test]
    async fn a_half_collected_job_resumes_after_a_restart_without_a_second_space() {
        let r = rig();
        // One download fails once; the agent restarts; the job finishes.
        r.hub.with(|s| {
            s.fail.insert("download".into(), [503].into());
        });
        let id = r.submit();
        let d = r.dispatcher();
        let j = r
            .drive(&d, &id, |j| {
                j.state == State::Collecting && j.waiting.is_some()
            })
            .await;
        assert!(j.results.is_empty());
        let d2 = r.dispatcher();
        let j = r.done(&d2, &id).await;
        assert_eq!(j.state, State::Done, "{:?}", j.error);
        assert_eq!(j.results.len(), 2);
        assert_eq!(r.hub.count("create"), 1);
        assert_eq!(r.hub.count("publish"), 1);
    }

    /// Against a real hub: `ZAKURO_TEST_HUB_URL`, `ZAKURO_TEST_HUB_TOKEN` (a
    /// hub session token: the Spaces routes refuse a `zk_` key) and
    /// `ZAKURO_TEST_JOB_IMAGE` (an image whose entrypoint writes an output
    /// file from `part.txt`). Run with `--ignored`.
    #[tokio::test]
    #[ignore = "needs a real hub: ZAKURO_TEST_HUB_URL, ZAKURO_TEST_HUB_TOKEN, ZAKURO_TEST_JOB_IMAGE"]
    async fn end_to_end_against_a_real_hub_two_batches() {
        let var = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("{k} is not set"));
        let (url, token, image) = (
            var("ZAKURO_TEST_HUB_URL"),
            var("ZAKURO_TEST_HUB_TOKEN"),
            var("ZAKURO_TEST_JOB_IMAGE"),
        );
        let home = test_dir("e2e-home");
        let inputs = test_dir("e2e-in");
        let outbox = Outbox::new(&home);
        let id = outbox
            .submit({
                let mut s = sample_spec(&inputs);
                s.name = "zc-e2e".into();
                s.image = image;
                s.max_price_per_batch = 1.0;
                s
            })
            .unwrap()
            .0
            .id;
        let d = Dispatcher::new(
            Store::new(&home),
            Arc::new(move || Some((url.clone(), token.clone()))),
            Arc::new(|_, _| {}),
            Config {
                poll: Duration::from_secs(5),
                ..Config::default()
            },
            Arc::new(Notify::new()),
        );
        let store = Store::new(&home);
        let deadline = Instant::now() + Duration::from_secs(20 * 60);
        let job = loop {
            d.advance(&id).await;
            let j = store.load(&id).unwrap();
            if j.state.terminal() {
                break j;
            }
            assert!(Instant::now() < deadline, "not done in 20 minutes: {j:?}");
            tokio::time::sleep(Duration::from_secs(5)).await;
        };
        assert_eq!(job.state, State::Done, "{:?}", job.error);
        assert_eq!(job.results.len(), 2);
        for r in &job.results {
            assert!(!r.files.is_empty(), "batch {} has outputs", r.seq);
            for f in &r.files {
                let p = std::path::Path::new(&r.dir).join(&f.name);
                assert_eq!(spec::sha256_file(&p).unwrap().0, f.sha256);
            }
            // Verified when the hub names the receipt; otherwise the job says
            // why it is unavailable. Either way it is on the record.
            match r.receipt.status.as_str() {
                "verified" => assert!(std::path::Path::new(&r.dir).join("receipt.json").exists()),
                other => {
                    assert_eq!(other, "unavailable", "{:?}", r.receipt);
                    eprintln!(
                        "batch {}: receipt unavailable: {:?}",
                        r.seq, r.receipt.detail
                    );
                }
            }
        }
    }

    #[test]
    fn backoff_doubles_and_is_capped() {
        // The schedule itself: base * 2^(attempts-1), never over the cap.
        let cfg = Config::default();
        let at = |n: u32| {
            cfg.backoff_base
                .checked_mul(1u32 << (n - 1).min(16))
                .unwrap_or(cfg.backoff_cap)
                .min(cfg.backoff_cap)
        };
        assert_eq!(at(1), Duration::from_secs(2));
        assert_eq!(at(2), Duration::from_secs(4));
        assert_eq!(at(3), Duration::from_secs(8));
        assert_eq!(at(30), Duration::from_secs(300));
    }
}