holos-tda 0.7.0

Vietoris-Rips persistent homology with an implicit ripser-class engine
Documentation
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
//! Durable content-addressed execution for relative interfaces.
//!
//! A store writes verified shard artifacts under their SHA-256 identifiers.
//! The coordinator folds one shard at a time while protecting the common
//! separator. Each fold is durable before the next one starts. An atomic
//! manifest publishes the final result. [`DurableInterfaceStore`] is local
//! and does not provide networking, authentication, or multi-writer
//! coordination.

use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

use crate::{CertificateLimits, RelativeInterfaceCertificate};

const MANIFEST_MAGIC: &[u8; 8] = b"HOLOSDM\0";
const PROGRESS_MAGIC: &[u8; 8] = b"HOLOSDW\0";
const VERSION: u16 = 1;

/// Failure during durable interface execution or recovery.
#[derive(Debug)]
pub struct DistributedInterfaceError {
    message: String,
}

impl DistributedInterfaceError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    /// Description of the failed store or algebra rule.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for DistributedInterfaceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "distributed interface: {}", self.message)
    }
}

impl std::error::Error for DistributedInterfaceError {}

/// SHA-256 identifier of one stored artifact.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArtifactId([u8; 32]);

impl ArtifactId {
    /// Compute the identifier of exact artifact bytes.
    pub fn for_bytes(bytes: &[u8]) -> Self {
        Self(Sha256::digest(bytes).into())
    }

    /// Construct an identifier from its 32-byte representation.
    pub fn from_bytes(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Raw identifier bytes.
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Lowercase hexadecimal identifier.
    pub fn to_hex(self) -> String {
        let mut output = String::with_capacity(64);
        for byte in self.0 {
            use std::fmt::Write as _;
            write!(output, "{byte:02x}").expect("writing to a string cannot fail");
        }
        output
    }
}

impl fmt::Display for ArtifactId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.to_hex())
    }
}

/// Exact I/O and fold work for one distributed composition.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DistributedInterfaceWork {
    /// Shard artifacts in the job.
    pub shards: usize,
    /// Shard artifacts decoded during this invocation.
    pub shards_loaded: usize,
    /// Completed folds reused from durable progress.
    pub folds_reused: usize,
    /// New folds computed during this invocation.
    pub folds_computed: usize,
    /// Artifact bytes read from the store.
    pub bytes_read: usize,
    /// New artifact bytes written to the store.
    pub bytes_written: usize,
    /// Peak byte count of one accumulator and one shard.
    pub peak_artifact_bytes: usize,
}

/// Commit record for one distributed interface result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DistributedInterfaceManifest {
    job: ArtifactId,
    max_dim: usize,
    modulus: u32,
    separator_vertices: Vec<usize>,
    output_protected_vertices: Vec<usize>,
    shards: Vec<ArtifactId>,
    folds: Vec<ArtifactId>,
    result: ArtifactId,
}

impl DistributedInterfaceManifest {
    /// Deterministic job identifier.
    pub fn job(&self) -> ArtifactId {
        self.job
    }

    /// Highest composed homology dimension.
    pub fn max_dim(&self) -> usize {
        self.max_dim
    }

    /// Prime coefficient modulus.
    pub fn modulus(&self) -> u32 {
        self.modulus
    }

    /// Separator protected during every intermediate fold.
    pub fn separator_vertices(&self) -> &[usize] {
        &self.separator_vertices
    }

    /// Protected vertices retained in the final result.
    pub fn output_protected_vertices(&self) -> &[usize] {
        &self.output_protected_vertices
    }

    /// Ordered shard artifact identifiers.
    pub fn shards(&self) -> &[ArtifactId] {
        &self.shards
    }

    /// Accumulator identifier after each shard.
    pub fn folds(&self) -> &[ArtifactId] {
        &self.folds
    }

    /// Final relative-interface artifact identifier.
    pub fn result(&self) -> ArtifactId {
        self.result
    }

    /// Encode the canonical `HOLOSDM` version 1 manifest.
    pub fn encode(&self) -> Result<Vec<u8>, DistributedInterfaceError> {
        let mut output = Vec::new();
        output.extend_from_slice(MANIFEST_MAGIC);
        output.extend_from_slice(&VERSION.to_be_bytes());
        output.extend_from_slice(self.job.as_bytes());
        put_usize(&mut output, self.max_dim)?;
        output.extend_from_slice(&self.modulus.to_be_bytes());
        encode_usizes(&mut output, &self.separator_vertices)?;
        encode_usizes(&mut output, &self.output_protected_vertices)?;
        encode_ids(&mut output, &self.shards)?;
        encode_ids(&mut output, &self.folds)?;
        output.extend_from_slice(self.result.as_bytes());
        Ok(output)
    }

    /// Decode one canonical bounded `HOLOSDM` version 1 manifest.
    pub fn decode(bytes: &[u8], maximum_bytes: usize) -> Result<Self, DistributedInterfaceError> {
        check_manifest_size(bytes.len(), maximum_bytes)?;
        let mut reader = Reader::new(bytes);
        check_manifest_identity(&mut reader)?;
        let manifest = decode_manifest_body(&mut reader)?;
        check_manifest_shape(&manifest, reader.remaining())?;
        check_manifest_binding(&manifest)?;
        Ok(manifest)
    }
}

fn check_manifest_size(actual: usize, limit: usize) -> Result<(), DistributedInterfaceError> {
    if actual > limit {
        return Err(DistributedInterfaceError::new(
            "manifest exceeds the byte limit",
        ));
    }
    Ok(())
}

fn check_manifest_identity(reader: &mut Reader<'_>) -> Result<(), DistributedInterfaceError> {
    if reader.take(8)? != MANIFEST_MAGIC || reader.u16()? != VERSION {
        return Err(DistributedInterfaceError::new(
            "unsupported distributed manifest",
        ));
    }
    Ok(())
}

fn decode_manifest_body(
    reader: &mut Reader<'_>,
) -> Result<DistributedInterfaceManifest, DistributedInterfaceError> {
    Ok(DistributedInterfaceManifest {
        job: ArtifactId(reader.array32()?),
        max_dim: reader.usize()?,
        modulus: reader.u32()?,
        separator_vertices: decode_usizes(reader)?,
        output_protected_vertices: decode_usizes(reader)?,
        shards: decode_ids(reader)?,
        folds: decode_ids(reader)?,
        result: ArtifactId(reader.array32()?),
    })
}

fn check_manifest_shape(
    manifest: &DistributedInterfaceManifest,
    remaining: usize,
) -> Result<(), DistributedInterfaceError> {
    if remaining != 0 || manifest.shards.is_empty() || manifest.folds.len() != manifest.shards.len()
    {
        return Err(DistributedInterfaceError::new(
            "distributed manifest shape is invalid",
        ));
    }
    require_canonical_vertices(&manifest.separator_vertices)?;
    require_canonical_vertices(&manifest.output_protected_vertices)?;
    Ok(())
}

fn check_manifest_binding(
    manifest: &DistributedInterfaceManifest,
) -> Result<(), DistributedInterfaceError> {
    let expected = job_id(
        manifest.max_dim,
        manifest.modulus,
        &manifest.separator_vertices,
        &manifest.output_protected_vertices,
        &manifest.shards,
    );
    if expected != manifest.job {
        return Err(DistributedInterfaceError::new(
            "distributed manifest binding is invalid",
        ));
    }
    Ok(())
}

/// Completed distributed composition and its durable manifest.
#[derive(Debug, Clone)]
pub struct DistributedInterfaceCommit {
    manifest: DistributedInterfaceManifest,
    certificate: RelativeInterfaceCertificate,
    work: DistributedInterfaceWork,
}

impl DistributedInterfaceCommit {
    /// Durable commit manifest.
    pub fn manifest(&self) -> &DistributedInterfaceManifest {
        &self.manifest
    }

    /// Composed relative-interface certificate.
    pub fn certificate(&self) -> &RelativeInterfaceCertificate {
        &self.certificate
    }

    /// I/O and fold work charged to this invocation.
    pub fn work(&self) -> DistributedInterfaceWork {
        self.work
    }
}

/// Filesystem-backed content-addressed store for interface artifacts.
#[derive(Debug, Clone)]
pub struct DurableInterfaceStore {
    root: PathBuf,
}

struct CommitPlan<'a> {
    job: ArtifactId,
    shard_ids: &'a [ArtifactId],
    separator_vertices: Vec<usize>,
    output_protected_vertices: Vec<usize>,
    intermediate_protected: Vec<usize>,
    limits: CertificateLimits,
}

struct FoldState {
    accumulator: RelativeInterfaceCertificate,
    folds: Vec<ArtifactId>,
    next: usize,
    accumulator_bytes: Vec<u8>,
}

struct PreparedCommit<'a> {
    plan: CommitPlan<'a>,
    first_id: ArtifactId,
    first: RelativeInterfaceCertificate,
}

impl DurableInterfaceStore {
    /// Open or create a store rooted at `path`.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, DistributedInterfaceError> {
        let root = path.as_ref().to_path_buf();
        fs::create_dir_all(root.join("objects"))
            .and_then(|_| fs::create_dir_all(root.join("jobs")))
            .and_then(|_| fs::create_dir_all(root.join("manifests")))
            .map_err(|error| DistributedInterfaceError::new(format!("create store: {error}")))?;
        Ok(Self { root })
    }

    /// Store exact bytes and return their content identifier.
    pub fn put(&self, bytes: &[u8]) -> Result<(ArtifactId, bool), DistributedInterfaceError> {
        let id = ArtifactId::for_bytes(bytes);
        let path = self.object_path(id);
        if path.is_file() {
            let existing = read_bounded(&path, bytes.len())?;
            if existing != bytes {
                return Err(DistributedInterfaceError::new(
                    "stored object differs under the same content identifier",
                ));
            }
            return Ok((id, false));
        }
        let parent = path.parent().expect("object path has a parent");
        fs::create_dir_all(parent).map_err(|error| {
            DistributedInterfaceError::new(format!("create object path: {error}"))
        })?;
        sync_parent(parent)?;
        sync_directory(parent)?;
        atomic_write(&path, bytes)?;
        Ok((id, true))
    }

    /// Read an object and check its identifier.
    pub fn get(
        &self,
        id: ArtifactId,
        maximum_bytes: usize,
    ) -> Result<Vec<u8>, DistributedInterfaceError> {
        let bytes = read_bounded(&self.object_path(id), maximum_bytes)?;
        if ArtifactId::for_bytes(&bytes) != id {
            return Err(DistributedInterfaceError::new(
                "stored object fails its content identifier",
            ));
        }
        Ok(bytes)
    }

    /// Whether an object path exists. This does not read or verify the bytes.
    pub fn contains(&self, id: ArtifactId) -> bool {
        self.object_path(id).is_file()
    }

    /// Compose shard artifacts and publish one atomic manifest.
    ///
    /// Shards are ordered. Every intermediate fold protects the union of
    /// `separator_vertices` and `output_protected_vertices`. A retry resumes
    /// from the last durable fold for the same content-bound job.
    pub fn commit(
        &self,
        shard_artifacts: &[Vec<u8>],
        separator_vertices: &[usize],
        output_protected_vertices: &[usize],
        limits: CertificateLimits,
    ) -> Result<DistributedInterfaceCommit, DistributedInterfaceError> {
        let mut shard_ids = Vec::with_capacity(shard_artifacts.len());
        let mut work = DistributedInterfaceWork {
            shards: shard_artifacts.len(),
            ..DistributedInterfaceWork::default()
        };
        for bytes in shard_artifacts {
            let (id, written) = self.put(bytes)?;
            shard_ids.push(id);
            if written {
                work.bytes_written += bytes.len();
            }
        }
        self.commit_stored_inner(
            &shard_ids,
            separator_vertices,
            output_protected_vertices,
            limits,
            work,
        )
    }

    /// Compose shards already present in this store.
    ///
    /// The coordinator loads at most one shard and one accumulator artifact
    /// for each fold. The identifiers are ordered and bind the job.
    pub fn commit_stored(
        &self,
        shard_ids: &[ArtifactId],
        separator_vertices: &[usize],
        output_protected_vertices: &[usize],
        limits: CertificateLimits,
    ) -> Result<DistributedInterfaceCommit, DistributedInterfaceError> {
        self.commit_stored_inner(
            shard_ids,
            separator_vertices,
            output_protected_vertices,
            limits,
            DistributedInterfaceWork {
                shards: shard_ids.len(),
                ..DistributedInterfaceWork::default()
            },
        )
    }

    fn commit_stored_inner(
        &self,
        shard_ids: &[ArtifactId],
        separator_vertices: &[usize],
        output_protected_vertices: &[usize],
        limits: CertificateLimits,
        mut work: DistributedInterfaceWork,
    ) -> Result<DistributedInterfaceCommit, DistributedInterfaceError> {
        let prepared = self.prepare_commit(
            shard_ids,
            separator_vertices,
            output_protected_vertices,
            limits,
            &mut work,
        )?;
        if let Some(manifest) = self.read_manifest(prepared.plan.job, limits.max_bytes)? {
            return self.load_commit(manifest, work, limits);
        }
        let mut state =
            self.resume_or_start(&prepared.plan, prepared.first_id, prepared.first, &mut work)?;
        self.compute_folds(&prepared.plan, &mut state, &mut work)?;
        self.finish_protection(&prepared.plan, &mut state, &mut work)?;
        self.publish_commit(&prepared.plan, state, work)
    }

    fn prepare_commit<'a>(
        &self,
        shard_ids: &'a [ArtifactId],
        separator_vertices: &[usize],
        output_protected_vertices: &[usize],
        limits: CertificateLimits,
        work: &mut DistributedInterfaceWork,
    ) -> Result<PreparedCommit<'a>, DistributedInterfaceError> {
        let first_id = require_first_shard(shard_ids)?;
        let separator_vertices = canonical_vertices(separator_vertices)?;
        let output_protected_vertices = canonical_vertices(output_protected_vertices)?;
        let first_bytes = self.get(first_id, limits.max_bytes)?;
        work.bytes_read += first_bytes.len();
        work.peak_artifact_bytes = first_bytes.len();
        work.shards_loaded += 1;
        let first = decode_certificate(&first_bytes, limits)?;
        require_separator(&first, &separator_vertices)?;
        let plan = CommitPlan {
            job: job_id(
                first.max_dim(),
                first.modulus(),
                &separator_vertices,
                &output_protected_vertices,
                shard_ids,
            ),
            shard_ids,
            intermediate_protected: combined_vertices(
                &separator_vertices,
                &output_protected_vertices,
            ),
            separator_vertices,
            output_protected_vertices,
            limits,
        };
        Ok(PreparedCommit {
            plan,
            first_id,
            first,
        })
    }

    fn resume_or_start(
        &self,
        plan: &CommitPlan<'_>,
        first_id: ArtifactId,
        first: RelativeInterfaceCertificate,
        work: &mut DistributedInterfaceWork,
    ) -> Result<FoldState, DistributedInterfaceError> {
        let Some(progress) = self.read_progress(plan.job, plan.limits.max_bytes)? else {
            return self.start_folds(plan, first_id, first);
        };
        check_progress_prefix(progress.prefix, plan.shard_ids.len())?;
        let bytes = self.get(progress.accumulator, plan.limits.max_bytes)?;
        work.bytes_read += bytes.len();
        work.folds_reused = progress.prefix;
        Ok(FoldState {
            accumulator: decode_certificate(&bytes, plan.limits)?,
            folds: progress.folds,
            next: progress.prefix,
            accumulator_bytes: bytes,
        })
    }

    fn start_folds(
        &self,
        plan: &CommitPlan<'_>,
        first_id: ArtifactId,
        first: RelativeInterfaceCertificate,
    ) -> Result<FoldState, DistributedInterfaceError> {
        let folds = vec![first_id];
        self.write_progress(
            plan.job,
            &Progress {
                prefix: 1,
                accumulator: first_id,
                folds: folds.clone(),
            },
        )?;
        Ok(FoldState {
            accumulator_bytes: encode_certificate(&first, plan.limits)?,
            accumulator: first,
            folds,
            next: 1,
        })
    }

    fn compute_folds(
        &self,
        plan: &CommitPlan<'_>,
        state: &mut FoldState,
        work: &mut DistributedInterfaceWork,
    ) -> Result<(), DistributedInterfaceError> {
        for (position, shard_id) in plan.shard_ids.iter().enumerate().skip(state.next) {
            self.compute_one_fold(plan, state, work, position, *shard_id)?;
        }
        Ok(())
    }

    fn compute_one_fold(
        &self,
        plan: &CommitPlan<'_>,
        state: &mut FoldState,
        work: &mut DistributedInterfaceWork,
        position: usize,
        shard_id: ArtifactId,
    ) -> Result<(), DistributedInterfaceError> {
        let (child, child_bytes) = self.load_child(plan, shard_id, work)?;
        compose_accumulator(plan, state, child, child_bytes, work)?;
        let fold = self.store_fold(&state.accumulator_bytes, work)?;
        state.folds.push(fold);
        state.next = position + 1;
        work.folds_computed += 1;
        self.write_progress(
            plan.job,
            &Progress {
                prefix: state.next,
                accumulator: fold,
                folds: state.folds.clone(),
            },
        )
    }

    fn load_child(
        &self,
        plan: &CommitPlan<'_>,
        shard_id: ArtifactId,
        work: &mut DistributedInterfaceWork,
    ) -> Result<(RelativeInterfaceCertificate, usize), DistributedInterfaceError> {
        let bytes = self.get(shard_id, plan.limits.max_bytes)?;
        work.bytes_read += bytes.len();
        work.shards_loaded += 1;
        let child = decode_certificate(&bytes, plan.limits)?;
        require_separator(&child, &plan.separator_vertices)?;
        Ok((child, bytes.len()))
    }

    fn store_fold(
        &self,
        bytes: &[u8],
        work: &mut DistributedInterfaceWork,
    ) -> Result<ArtifactId, DistributedInterfaceError> {
        let (fold, written) = self.put(bytes)?;
        if written {
            work.bytes_written += bytes.len();
        }
        Ok(fold)
    }

    fn finish_protection(
        &self,
        plan: &CommitPlan<'_>,
        state: &mut FoldState,
        work: &mut DistributedInterfaceWork,
    ) -> Result<(), DistributedInterfaceError> {
        if state.accumulator.protected_vertices() == plan.output_protected_vertices {
            return Ok(());
        }
        state.accumulator = compose_certificates(
            &[&state.accumulator],
            &plan.output_protected_vertices,
            plan.limits,
        )?;
        state.accumulator_bytes = encode_certificate(&state.accumulator, plan.limits)?;
        self.store_fold(&state.accumulator_bytes, work)?;
        Ok(())
    }

    fn publish_commit(
        &self,
        plan: &CommitPlan<'_>,
        state: FoldState,
        work: DistributedInterfaceWork,
    ) -> Result<DistributedInterfaceCommit, DistributedInterfaceError> {
        let manifest = DistributedInterfaceManifest {
            job: plan.job,
            max_dim: state.accumulator.max_dim(),
            modulus: state.accumulator.modulus(),
            separator_vertices: plan.separator_vertices.clone(),
            output_protected_vertices: plan.output_protected_vertices.clone(),
            shards: plan.shard_ids.to_vec(),
            folds: state.folds,
            result: ArtifactId::for_bytes(&state.accumulator_bytes),
        };
        atomic_write(&self.manifest_path(plan.job), &manifest.encode()?)?;
        Ok(DistributedInterfaceCommit {
            manifest,
            certificate: state.accumulator,
            work,
        })
    }

    /// Recompute every fold and verify a committed manifest from stored shards.
    ///
    /// Ignores durable progress. Checks that every recorded fold and the
    /// final result follow from the ordered shard artifacts.
    pub fn verify_manifest(
        &self,
        manifest: &DistributedInterfaceManifest,
        limits: CertificateLimits,
    ) -> Result<RelativeInterfaceCertificate, DistributedInterfaceError> {
        let mut accumulator = self.load_manifest_start(manifest, limits)?;
        self.replay_manifest_folds(manifest, limits, &mut accumulator)?;
        if accumulator.protected_vertices() != manifest.output_protected_vertices {
            accumulator =
                compose_certificates(&[&accumulator], &manifest.output_protected_vertices, limits)?;
        }
        self.check_manifest_result(manifest, &accumulator, limits)?;
        Ok(accumulator)
    }

    fn load_manifest_start(
        &self,
        manifest: &DistributedInterfaceManifest,
        limits: CertificateLimits,
    ) -> Result<RelativeInterfaceCertificate, DistributedInterfaceError> {
        let bytes = self.get(manifest.shards[0], limits.max_bytes)?;
        let accumulator = decode_certificate(&bytes, limits)?;
        require_separator(&accumulator, &manifest.separator_vertices)?;
        check_fold_id(&bytes, manifest.folds[0])?;
        Ok(accumulator)
    }

    fn replay_manifest_folds(
        &self,
        manifest: &DistributedInterfaceManifest,
        limits: CertificateLimits,
        accumulator: &mut RelativeInterfaceCertificate,
    ) -> Result<(), DistributedInterfaceError> {
        let intermediate = combined_vertices(
            &manifest.separator_vertices,
            &manifest.output_protected_vertices,
        );
        for (position, shard) in manifest.shards.iter().enumerate().skip(1) {
            self.replay_manifest_fold(
                manifest,
                limits,
                &intermediate,
                accumulator,
                position,
                *shard,
            )?;
        }
        Ok(())
    }

    fn replay_manifest_fold(
        &self,
        manifest: &DistributedInterfaceManifest,
        limits: CertificateLimits,
        intermediate: &[usize],
        accumulator: &mut RelativeInterfaceCertificate,
        position: usize,
        shard: ArtifactId,
    ) -> Result<(), DistributedInterfaceError> {
        let bytes = self.get(shard, limits.max_bytes)?;
        let child = decode_certificate(&bytes, limits)?;
        require_compatible(accumulator, &child)?;
        require_separator(&child, &manifest.separator_vertices)?;
        *accumulator = compose_certificates(&[accumulator, &child], intermediate, limits)?;
        check_fold_id(
            &encode_certificate(accumulator, limits)?,
            manifest.folds[position],
        )
    }

    fn check_manifest_result(
        &self,
        manifest: &DistributedInterfaceManifest,
        accumulator: &RelativeInterfaceCertificate,
        limits: CertificateLimits,
    ) -> Result<(), DistributedInterfaceError> {
        let encoded = encode_certificate(accumulator, limits)?;
        if ArtifactId::for_bytes(&encoded) != manifest.result {
            return Err(DistributedInterfaceError::new(
                "manifest result differs from recomputation",
            ));
        }
        let stored = self.get(manifest.result, limits.max_bytes)?;
        if stored != encoded {
            return Err(DistributedInterfaceError::new(
                "stored result differs from recomputed result",
            ));
        }
        Ok(())
    }

    /// Read a committed manifest by job identifier.
    pub fn manifest(
        &self,
        job: ArtifactId,
        maximum_bytes: usize,
    ) -> Result<DistributedInterfaceManifest, DistributedInterfaceError> {
        self.read_manifest(job, maximum_bytes)?
            .ok_or_else(|| DistributedInterfaceError::new("distributed manifest is absent"))
    }

    fn load_commit(
        &self,
        manifest: DistributedInterfaceManifest,
        mut work: DistributedInterfaceWork,
        limits: CertificateLimits,
    ) -> Result<DistributedInterfaceCommit, DistributedInterfaceError> {
        let bytes = self.get(manifest.result, limits.max_bytes)?;
        work.bytes_read += bytes.len();
        work.folds_reused = manifest.folds.len();
        let certificate = RelativeInterfaceCertificate::decode(&bytes, limits)
            .map_err(|error| DistributedInterfaceError::new(error.to_string()))?;
        Ok(DistributedInterfaceCommit {
            manifest,
            certificate,
            work,
        })
    }

    fn object_path(&self, id: ArtifactId) -> PathBuf {
        let hex = id.to_hex();
        self.root.join("objects").join(&hex[..2]).join(&hex[2..])
    }

    fn manifest_path(&self, id: ArtifactId) -> PathBuf {
        self.root.join("manifests").join(format!("{id}.hdm"))
    }

    fn progress_path(&self, id: ArtifactId) -> PathBuf {
        self.root.join("jobs").join(format!("{id}.work"))
    }

    fn read_manifest(
        &self,
        id: ArtifactId,
        maximum_bytes: usize,
    ) -> Result<Option<DistributedInterfaceManifest>, DistributedInterfaceError> {
        let path = self.manifest_path(id);
        if !path.is_file() {
            return Ok(None);
        }
        let bytes = read_bounded(&path, maximum_bytes)?;
        DistributedInterfaceManifest::decode(&bytes, maximum_bytes).map(Some)
    }

    fn write_progress(
        &self,
        job: ArtifactId,
        progress: &Progress,
    ) -> Result<(), DistributedInterfaceError> {
        let mut output = Vec::new();
        output.extend_from_slice(PROGRESS_MAGIC);
        output.extend_from_slice(&VERSION.to_be_bytes());
        output.extend_from_slice(job.as_bytes());
        put_usize(&mut output, progress.prefix)?;
        output.extend_from_slice(progress.accumulator.as_bytes());
        encode_ids(&mut output, &progress.folds)?;
        atomic_replace(&self.progress_path(job), &output)
    }

    fn read_progress(
        &self,
        job: ArtifactId,
        maximum_bytes: usize,
    ) -> Result<Option<Progress>, DistributedInterfaceError> {
        let path = self.progress_path(job);
        if !path.is_file() {
            return Ok(None);
        }
        let bytes = read_bounded(&path, maximum_bytes)?;
        let mut reader = Reader::new(&bytes);
        check_progress_identity(&mut reader, job)?;
        let prefix = reader.usize()?;
        let accumulator = ArtifactId(reader.array32()?);
        let folds = decode_ids(&mut reader)?;
        check_progress_shape(reader.remaining(), prefix, accumulator, &folds)?;
        Ok(Some(Progress {
            prefix,
            accumulator,
            folds,
        }))
    }
}

struct Progress {
    prefix: usize,
    accumulator: ArtifactId,
    folds: Vec<ArtifactId>,
}

fn require_first_shard(shards: &[ArtifactId]) -> Result<ArtifactId, DistributedInterfaceError> {
    shards
        .first()
        .copied()
        .ok_or_else(|| DistributedInterfaceError::new("distributed composition requires a shard"))
}

fn check_progress_identity(
    reader: &mut Reader<'_>,
    job: ArtifactId,
) -> Result<(), DistributedInterfaceError> {
    let valid = reader.take(8)? == PROGRESS_MAGIC
        && reader.u16()? == VERSION
        && ArtifactId(reader.array32()?) == job;
    if !valid {
        return Err(DistributedInterfaceError::new(
            "durable fold progress has an invalid binding",
        ));
    }
    Ok(())
}

fn check_progress_shape(
    remaining: usize,
    prefix: usize,
    accumulator: ArtifactId,
    folds: &[ArtifactId],
) -> Result<(), DistributedInterfaceError> {
    if remaining != 0 || folds.len() != prefix || folds.last().copied() != Some(accumulator) {
        return Err(DistributedInterfaceError::new(
            "durable fold progress has an invalid shape",
        ));
    }
    Ok(())
}

fn combined_vertices(left: &[usize], right: &[usize]) -> Vec<usize> {
    let mut combined = left.to_vec();
    combined.extend_from_slice(right);
    combined.sort_unstable();
    combined.dedup();
    combined
}

fn check_progress_prefix(
    prefix: usize,
    shard_count: usize,
) -> Result<(), DistributedInterfaceError> {
    if prefix == 0 || prefix > shard_count {
        return Err(DistributedInterfaceError::new(
            "durable fold progress has an invalid prefix",
        ));
    }
    Ok(())
}

fn decode_certificate(
    bytes: &[u8],
    limits: CertificateLimits,
) -> Result<RelativeInterfaceCertificate, DistributedInterfaceError> {
    RelativeInterfaceCertificate::decode(bytes, limits)
        .map_err(|error| DistributedInterfaceError::new(error.to_string()))
}

fn encode_certificate(
    certificate: &RelativeInterfaceCertificate,
    limits: CertificateLimits,
) -> Result<Vec<u8>, DistributedInterfaceError> {
    certificate
        .encode(limits)
        .map_err(|error| DistributedInterfaceError::new(error.to_string()))
}

fn compose_certificates(
    children: &[&RelativeInterfaceCertificate],
    protected_vertices: &[usize],
    limits: CertificateLimits,
) -> Result<RelativeInterfaceCertificate, DistributedInterfaceError> {
    RelativeInterfaceCertificate::compose(children, protected_vertices, limits)
        .map_err(|error| DistributedInterfaceError::new(error.to_string()))
}

fn compose_accumulator(
    plan: &CommitPlan<'_>,
    state: &mut FoldState,
    child: RelativeInterfaceCertificate,
    child_bytes: usize,
    work: &mut DistributedInterfaceWork,
) -> Result<(), DistributedInterfaceError> {
    require_compatible(&state.accumulator, &child)?;
    work.peak_artifact_bytes = work
        .peak_artifact_bytes
        .max(state.accumulator_bytes.len().saturating_add(child_bytes));
    state.accumulator = compose_certificates(
        &[&state.accumulator, &child],
        &plan.intermediate_protected,
        plan.limits,
    )?;
    state.accumulator_bytes = encode_certificate(&state.accumulator, plan.limits)?;
    Ok(())
}

fn check_fold_id(bytes: &[u8], expected: ArtifactId) -> Result<(), DistributedInterfaceError> {
    if ArtifactId::for_bytes(bytes) != expected {
        return Err(DistributedInterfaceError::new(
            "manifest fold chain differs from recomputation",
        ));
    }
    Ok(())
}

fn require_separator(
    certificate: &RelativeInterfaceCertificate,
    separator: &[usize],
) -> Result<(), DistributedInterfaceError> {
    if separator.iter().any(|vertex| {
        certificate
            .protected_vertices()
            .binary_search(vertex)
            .is_err()
    }) {
        return Err(DistributedInterfaceError::new(
            "shard does not protect every common separator vertex",
        ));
    }
    Ok(())
}

fn require_compatible(
    left: &RelativeInterfaceCertificate,
    right: &RelativeInterfaceCertificate,
) -> Result<(), DistributedInterfaceError> {
    if left.max_dim() != right.max_dim() || left.modulus() != right.modulus() {
        return Err(DistributedInterfaceError::new(
            "shards use different dimensions or coefficient fields",
        ));
    }
    Ok(())
}

fn job_id(
    max_dim: usize,
    modulus: u32,
    separator: &[usize],
    output_protected: &[usize],
    shards: &[ArtifactId],
) -> ArtifactId {
    let mut hash = Sha256::new();
    hash.update(b"holos-distributed-interface-job-v1");
    hash.update((max_dim as u64).to_be_bytes());
    hash.update(modulus.to_be_bytes());
    digest_usizes(&mut hash, separator);
    digest_usizes(&mut hash, output_protected);
    hash.update((shards.len() as u64).to_be_bytes());
    for shard in shards {
        hash.update(shard.as_bytes());
    }
    ArtifactId(hash.finalize().into())
}

fn canonical_vertices(vertices: &[usize]) -> Result<Vec<usize>, DistributedInterfaceError> {
    let mut result = vertices.to_vec();
    result.sort_unstable();
    result.dedup();
    if result.len() != vertices.len() {
        return Err(DistributedInterfaceError::new(
            "vertex list contains a duplicate",
        ));
    }
    Ok(result)
}

fn require_canonical_vertices(vertices: &[usize]) -> Result<(), DistributedInterfaceError> {
    if vertices.windows(2).any(|pair| pair[0] >= pair[1]) {
        return Err(DistributedInterfaceError::new(
            "manifest vertex list is not canonical",
        ));
    }
    Ok(())
}

fn read_bounded(path: &Path, maximum: usize) -> Result<Vec<u8>, DistributedInterfaceError> {
    let file = File::open(path).map_err(|error| {
        DistributedInterfaceError::new(format!("read {}: {error}", path.display()))
    })?;
    let mut bytes = Vec::new();
    file.take(u64::try_from(maximum).unwrap_or(u64::MAX).saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(|error| DistributedInterfaceError::new(format!("read object: {error}")))?;
    if bytes.len() > maximum {
        return Err(DistributedInterfaceError::new(
            "stored artifact exceeds the byte limit",
        ));
    }
    Ok(bytes)
}

fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), DistributedInterfaceError> {
    for nonce in 0..100u32 {
        let Some((temporary, mut file)) = reserve_temporary(path, nonce)? else {
            continue;
        };
        write_temporary(&mut file, bytes)?;
        if publish_temporary(&temporary, path, bytes)? {
            return Ok(());
        }
    }
    Err(DistributedInterfaceError::new(
        "cannot reserve an atomic temporary path",
    ))
}

fn reserve_temporary(
    path: &Path,
    nonce: u32,
) -> Result<Option<(PathBuf, File)>, DistributedInterfaceError> {
    let temporary = temporary_path(path, nonce);
    match OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&temporary)
    {
        Ok(file) => Ok(Some((temporary, file))),
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(None),
        Err(error) => Err(DistributedInterfaceError::new(format!(
            "create {}: {error}",
            temporary.display()
        ))),
    }
}

fn write_temporary(file: &mut File, bytes: &[u8]) -> Result<(), DistributedInterfaceError> {
    file.write_all(bytes)
        .and_then(|_| file.sync_all())
        .map_err(|error| DistributedInterfaceError::new(format!("write object: {error}")))
}

fn publish_temporary(
    temporary: &Path,
    path: &Path,
    bytes: &[u8],
) -> Result<bool, DistributedInterfaceError> {
    match fs::rename(temporary, path) {
        Ok(()) => {
            sync_parent(path)?;
            Ok(true)
        }
        Err(_) if path.is_file() => check_existing_destination(temporary, path, bytes),
        Err(error) => {
            let _ = fs::remove_file(temporary);
            Err(DistributedInterfaceError::new(format!(
                "publish {}: {error}",
                path.display()
            )))
        }
    }
}

fn check_existing_destination(
    temporary: &Path,
    path: &Path,
    bytes: &[u8],
) -> Result<bool, DistributedInterfaceError> {
    let _ = fs::remove_file(temporary);
    if read_bounded(path, bytes.len())? == bytes {
        return Ok(true);
    }
    Err(DistributedInterfaceError::new(
        "atomic destination contains different bytes",
    ))
}

fn atomic_replace(path: &Path, bytes: &[u8]) -> Result<(), DistributedInterfaceError> {
    for nonce in 0..100u32 {
        let temporary = temporary_path(path, nonce);
        let file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temporary);
        let mut file = match file {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => {
                return Err(DistributedInterfaceError::new(format!(
                    "create progress: {error}"
                )));
            }
        };
        file.write_all(bytes)
            .and_then(|_| file.sync_all())
            .map_err(|error| DistributedInterfaceError::new(format!("write progress: {error}")))?;
        fs::rename(&temporary, path).map_err(|error| {
            let _ = fs::remove_file(&temporary);
            DistributedInterfaceError::new(format!("publish progress: {error}"))
        })?;
        sync_parent(path)?;
        return Ok(());
    }
    Err(DistributedInterfaceError::new(
        "cannot reserve a progress temporary path",
    ))
}

fn temporary_path(path: &Path, nonce: u32) -> PathBuf {
    let name = path.file_name().unwrap_or_default().to_string_lossy();
    path.with_file_name(format!(".{name}.{}.{nonce}.tmp", std::process::id()))
}

fn sync_parent(path: &Path) -> Result<(), DistributedInterfaceError> {
    let parent = path
        .parent()
        .ok_or_else(|| DistributedInterfaceError::new("durable path has no parent"))?;
    sync_directory(parent)
}

#[cfg(unix)]
fn sync_directory(path: &Path) -> Result<(), DistributedInterfaceError> {
    File::open(path)
        .and_then(|directory| directory.sync_all())
        .map_err(|error| {
            DistributedInterfaceError::new(format!(
                "synchronize directory {}: {error}",
                path.display()
            ))
        })
}

#[cfg(not(unix))]
fn sync_directory(_path: &Path) -> Result<(), DistributedInterfaceError> {
    Ok(())
}

fn encode_ids(
    output: &mut Vec<u8>,
    values: &[ArtifactId],
) -> Result<(), DistributedInterfaceError> {
    put_usize(output, values.len())?;
    for value in values {
        output.extend_from_slice(value.as_bytes());
    }
    Ok(())
}

fn decode_ids(reader: &mut Reader<'_>) -> Result<Vec<ArtifactId>, DistributedInterfaceError> {
    let count = reader.usize()?;
    let maximum = reader.remaining() / 32;
    if count > maximum {
        return Err(DistributedInterfaceError::new(
            "manifest identifier count exceeds the remaining bytes",
        ));
    }
    (0..count)
        .map(|_| reader.array32().map(ArtifactId))
        .collect()
}

fn encode_usizes(output: &mut Vec<u8>, values: &[usize]) -> Result<(), DistributedInterfaceError> {
    put_usize(output, values.len())?;
    for value in values {
        put_usize(output, *value)?;
    }
    Ok(())
}

fn decode_usizes(reader: &mut Reader<'_>) -> Result<Vec<usize>, DistributedInterfaceError> {
    let count = reader.usize()?;
    let maximum = reader.remaining() / 8;
    if count > maximum {
        return Err(DistributedInterfaceError::new(
            "manifest integer count exceeds the remaining bytes",
        ));
    }
    (0..count).map(|_| reader.usize()).collect()
}

fn put_usize(output: &mut Vec<u8>, value: usize) -> Result<(), DistributedInterfaceError> {
    let value = u64::try_from(value)
        .map_err(|_| DistributedInterfaceError::new("integer does not fit the wire format"))?;
    output.extend_from_slice(&value.to_be_bytes());
    Ok(())
}

fn digest_usizes(hash: &mut Sha256, values: &[usize]) {
    hash.update((values.len() as u64).to_be_bytes());
    for value in values {
        hash.update((*value as u64).to_be_bytes());
    }
}

struct Reader<'a> {
    bytes: &'a [u8],
    position: usize,
}

impl<'a> Reader<'a> {
    fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, position: 0 }
    }

    fn remaining(&self) -> usize {
        self.bytes.len() - self.position
    }

    fn take(&mut self, count: usize) -> Result<&'a [u8], DistributedInterfaceError> {
        let end = self
            .position
            .checked_add(count)
            .ok_or_else(|| DistributedInterfaceError::new("manifest position overflows"))?;
        if end > self.bytes.len() {
            return Err(DistributedInterfaceError::new("manifest is truncated"));
        }
        let value = &self.bytes[self.position..end];
        self.position = end;
        Ok(value)
    }

    fn u16(&mut self) -> Result<u16, DistributedInterfaceError> {
        Ok(u16::from_be_bytes(self.take(2)?.try_into().unwrap()))
    }

    fn u32(&mut self) -> Result<u32, DistributedInterfaceError> {
        Ok(u32::from_be_bytes(self.take(4)?.try_into().unwrap()))
    }

    fn u64(&mut self) -> Result<u64, DistributedInterfaceError> {
        Ok(u64::from_be_bytes(self.take(8)?.try_into().unwrap()))
    }

    fn usize(&mut self) -> Result<usize, DistributedInterfaceError> {
        usize::try_from(self.u64()?)
            .map_err(|_| DistributedInterfaceError::new("manifest integer does not fit usize"))
    }

    fn array32(&mut self) -> Result<[u8; 32], DistributedInterfaceError> {
        Ok(self.take(32)?.try_into().unwrap())
    }
}

#[cfg(all(test, holos_repository_tests))]
mod tests {
    use super::*;
    use crate::{RipsParams, SparseDistanceMatrix, rips_persistence_sparse};
    use holos_tda_check::{ProofLimits, verify_distributed_interface};
    use std::collections::BTreeSet;

    struct TestStore(PathBuf);

    impl TestStore {
        fn new(name: &str) -> Self {
            let path = std::env::temp_dir().join(format!(
                "holos_distributed_{}_{}",
                std::process::id(),
                name
            ));
            if path.exists() {
                fs::remove_dir_all(&path).unwrap();
            }
            Self(path)
        }
    }

    impl Drop for TestStore {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn shard(labels: &[usize], side: usize, modulus: u32) -> RelativeInterfaceCertificate {
        let graph = SparseDistanceMatrix::from_triplets(
            5,
            &[
                (0, 1, 1.0),
                (1, 2, 1.0),
                (2, 3, 1.0),
                (0, 3, 1.0),
                (side, 4, 2.0),
                ((side + 1) % 4, 4, 2.0),
            ],
        )
        .unwrap();
        RelativeInterfaceCertificate::build_labeled(
            &graph,
            labels,
            &RipsParams::new(2).with_modulus(modulus),
            &[0, 1, 2, 3],
            CertificateLimits::default(),
        )
        .unwrap()
    }

    #[test]
    fn commits_recovers_and_independently_replays_a_streaming_fold() {
        let temporary = TestStore::new("commit");
        let store = DurableInterfaceStore::open(&temporary.0).unwrap();
        let shards = [
            shard(&[0, 1, 2, 3, 4], 0, 5),
            shard(&[0, 1, 2, 3, 5], 1, 5),
            shard(&[0, 1, 2, 3, 6], 2, 5),
        ];
        let artifacts: Vec<_> = shards
            .iter()
            .map(|shard| shard.encode(CertificateLimits::default()).unwrap())
            .collect();
        let commit = store
            .commit(&artifacts, &[0, 1, 2, 3], &[], CertificateLimits::default())
            .unwrap();
        assert_eq!(commit.manifest().shards().len(), 3);
        assert_eq!(commit.manifest().folds().len(), 3);
        assert_eq!(commit.work().folds_computed, 2);
        let verified = store
            .verify_manifest(commit.manifest(), CertificateLimits::default())
            .unwrap();
        assert_eq!(verified.diagram().bars, commit.certificate().diagram().bars);
        let mut ids: BTreeSet<_> = commit.manifest().shards().iter().copied().collect();
        ids.extend(commit.manifest().folds().iter().copied());
        ids.insert(commit.manifest().result());
        let objects: Vec<_> = ids
            .into_iter()
            .map(|id| {
                store
                    .get(id, CertificateLimits::default().max_bytes)
                    .unwrap()
            })
            .collect();
        let independent = verify_distributed_interface(
            &commit.manifest().encode().unwrap(),
            &objects,
            ProofLimits::default(),
        )
        .unwrap();
        assert_eq!(independent.result, *commit.manifest().result().as_bytes());
        assert_eq!(independent.shards, 3);

        fs::remove_file(store.manifest_path(commit.manifest().job())).unwrap();
        let recovered = store
            .commit(&artifacts, &[0, 1, 2, 3], &[], CertificateLimits::default())
            .unwrap();
        assert_eq!(recovered.manifest(), commit.manifest());
        assert_eq!(recovered.work().folds_reused, 3);
        assert_eq!(recovered.work().folds_computed, 0);

        let mut full_edges = vec![(0, 1, 1.0), (1, 2, 1.0), (2, 3, 1.0), (0, 3, 1.0)];
        full_edges.extend([(0, 4, 2.0), (1, 4, 2.0)]);
        full_edges.extend([(1, 5, 2.0), (2, 5, 2.0)]);
        full_edges.extend([(2, 6, 2.0), (3, 6, 2.0)]);
        let full = SparseDistanceMatrix::from_triplets(7, &full_edges).unwrap();
        assert_eq!(
            recovered.certificate().diagram().bars,
            rips_persistence_sparse(&full, &RipsParams::new(2).with_modulus(5))
                .unwrap()
                .bars
        );
    }

    #[test]
    fn resumes_an_arbitrary_durable_prefix() {
        let temporary = TestStore::new("prefix");
        let store = DurableInterfaceStore::open(&temporary.0).unwrap();
        let certificates = [
            shard(&[0, 1, 2, 3, 4], 0, 5),
            shard(&[0, 1, 2, 3, 5], 1, 5),
            shard(&[0, 1, 2, 3, 6], 2, 5),
        ];
        let artifacts: Vec<_> = certificates
            .iter()
            .map(|item| item.encode(CertificateLimits::default()).unwrap())
            .collect();
        let ids: Vec<_> = artifacts
            .iter()
            .map(|bytes| store.put(bytes).unwrap().0)
            .collect();
        let prefix = RelativeInterfaceCertificate::compose(
            &[&certificates[0], &certificates[1]],
            &[0, 1, 2, 3],
            CertificateLimits::default(),
        )
        .unwrap();
        let prefix_bytes = prefix.encode(CertificateLimits::default()).unwrap();
        let prefix_id = store.put(&prefix_bytes).unwrap().0;
        let job = job_id(2, 5, &[0, 1, 2, 3], &[], &ids);
        store
            .write_progress(
                job,
                &Progress {
                    prefix: 2,
                    accumulator: prefix_id,
                    folds: vec![ids[0], prefix_id],
                },
            )
            .unwrap();

        let commit = store
            .commit_stored(&ids, &[0, 1, 2, 3], &[], CertificateLimits::default())
            .unwrap();
        assert_eq!(commit.work().folds_reused, 2);
        assert_eq!(commit.work().folds_computed, 1);
        assert_eq!(commit.manifest().folds()[1], prefix_id);
        store
            .verify_manifest(commit.manifest(), CertificateLimits::default())
            .unwrap();
    }

    #[test]
    fn rejects_corrupt_objects_and_incompatible_shards() {
        let temporary = TestStore::new("corrupt");
        let store = DurableInterfaceStore::open(&temporary.0).unwrap();
        let first = shard(&[0, 1, 2, 3, 4], 0, 2)
            .encode(CertificateLimits::default())
            .unwrap();
        let incompatible = shard(&[0, 1, 2, 3, 5], 1, 3)
            .encode(CertificateLimits::default())
            .unwrap();
        assert!(
            store
                .commit(
                    &[first.clone(), incompatible],
                    &[0, 1, 2, 3],
                    &[],
                    CertificateLimits::default(),
                )
                .is_err()
        );
        let (id, _) = store.put(&first).unwrap();
        fs::write(store.object_path(id), b"corrupt").unwrap();
        assert!(
            store
                .get(id, CertificateLimits::default().max_bytes)
                .is_err()
        );
    }
}