heddle-thread-api 0.25.4

Native Thread clients and durable peer replication over Iroh
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
//! Source bytes remain temporary until the terminal receipt and exact closure
//! have been checked. Staging never changes a repository or a checkout.
use std::{
    collections::{BTreeMap, BTreeSet},
    path::Path,
};

use api::v2::client::MessageReader;
use crypto::thread_operation::SignedOperation;
use heddle_object_model::object::{ContentHash, State, thread_replication::ThreadOperation};
use heddle_pack::store::pack::PackReader;
use prost::Message;
use tokio::io::AsyncWriteExt;

use super::{Download, Error, Item};
use crate::{contract::*, transport};

const METADATA_BYTES: usize = 16 * 1024 * 1024;
const SOURCE_BYTES: u64 = 256 * 1024 * 1024;
const SOURCE_OBJECTS: usize = 100_000;

/// Verified source artifacts and their original proofs. Dropping this value
/// removes its temporary files. Native callers can install it on a disk worker.
pub struct StagedSource {
    pub(super) directory: tempfile::TempDir,
    pub(super) ready: TransferReady,
    pub(super) operations: Vec<SignedOperation>,
    pub(super) dependencies: Vec<ThreadGenesisRecord>,
    pub(super) state: State,
    pub(super) partial_trees: Vec<heddle_object_model::object::PartialTree>,
    pub(super) authority_admissions:
        BTreeMap<ContentHash, crypto::thread_authority_admission::SignedAuthorityAdmission>,
}
impl StagedSource {
    pub fn artifact_paths(&self) -> [std::path::PathBuf; 2] {
        [
            self.directory.path().join("source.pack"),
            self.directory.path().join("source.idx"),
        ]
    }
    pub fn operations(&self) -> &[SignedOperation] {
        &self.operations
    }
    pub fn dependency_geneses(&self) -> &[ThreadGenesisRecord] {
        &self.dependencies
    }
    pub fn ready(&self) -> &TransferReady {
        &self.ready
    }
    pub fn state(&self) -> &State {
        &self.state
    }
    /// Partial source remains read-only until a verified full closure arrives.
    pub fn is_complete(&self) -> bool {
        self.ready.full_closure_available
    }
}
impl<R: MessageReader<Error = transport::Error>> Download<R> {
    /// Consume one complete source download into bounded temporary files and
    /// validate its original causal ancestry and exact selected source closure.
    pub async fn stage(mut self, scratch: &Path) -> Result<StagedSource, Error> {
        if self.state.facets != [SharedFacet::Source as i32] {
            return Err(Error::Invalid("staging requires the source facet alone"));
        }
        let total = self
            .state
            .ready
            .packs
            .iter()
            .try_fold(0u64, |sum, extent| sum.checked_add(extent.length))
            .ok_or(Error::Invalid("source artifact length overflow"))?;
        if total > SOURCE_BYTES {
            return Err(Error::Invalid("staged source exceeds 256 MiB"));
        }
        self.state.limits.max_operations = self.state.limits.max_operations.min(10_000);
        let directory = tempfile::Builder::new()
            .prefix("thread-download-")
            .tempdir_in(scratch)?;
        let mut files = [
            tokio::fs::File::create(directory.path().join("source.pack")).await?,
            tokio::fs::File::create(directory.path().join("source.idx")).await?,
        ];
        let mut operations = Vec::new();
        let mut receipt_records = Vec::new();
        let mut dependencies = Vec::new();
        let mut metadata_bytes = 0usize;
        let mut complete = false;
        while let Some(item) = self.next().await? {
            match item {
                Item::Pack(chunk) => {
                    let kind = chunk
                        .extent
                        .as_ref()
                        .ok_or(Error::Invalid("chunk extent absent"))?
                        .kind;
                    let index = match pack_extent::Kind::try_from(kind) {
                        Ok(pack_extent::Kind::NativePack) => 0,
                        Ok(pack_extent::Kind::NativeIndex) => 1,
                        _ => return Err(Error::Invalid("native source artifacts required")),
                    };
                    files[index].write_all(&chunk.data).await?;
                }
                Item::Operations(batch) => {
                    metadata_bytes = metadata_bytes
                        .checked_add(batch.encoded_len())
                        .ok_or(Error::Invalid("source metadata length overflow"))?;
                    if metadata_bytes > METADATA_BYTES {
                        return Err(Error::Invalid("staged source metadata exceeds 16 MiB"));
                    }
                    for received in crate::authority_admission::match_batch(&batch)? {
                        operations.push(received.original);
                        receipt_records.extend(received.authority_admission);
                    }
                }
                Item::ThreadGenesis(record) => {
                    metadata_bytes = metadata_bytes
                        .checked_add(record.encoded_len())
                        .ok_or(Error::Invalid("source metadata length overflow"))?;
                    if metadata_bytes > METADATA_BYTES || dependencies.len() >= 127 {
                        return Err(Error::Invalid("dependency metadata exceeds bounds"));
                    }
                    dependencies.push(record);
                }
                Item::Complete(_) => complete = true,
                Item::Sidecar(_) => return Err(Error::Invalid("source staging excludes sidecars")),
            }
        }
        if !complete {
            return Err(Error::Invalid("source staging requires Complete"));
        }
        for file in &mut files {
            file.flush().await?;
            file.sync_all().await?;
        }
        drop(files);
        let ready = self.state.ready;
        tokio::task::spawn_blocking(move || {
            validate_with_receipts(directory, ready, operations, dependencies, receipt_records)
        })
        .await
        .map_err(|error| Error::Preparation(error.to_string()))?
    }
}
#[cfg(test)]
fn validate(
    directory: tempfile::TempDir,
    ready: TransferReady,
    operations: Vec<SignedOperation>,
    dependencies: Vec<ThreadGenesisRecord>,
) -> Result<StagedSource, Error> {
    validate_with_receipts(directory, ready, operations, dependencies, Vec::new())
}

struct DisclosureInput {
    directory: tempfile::TempDir,
    operations: Vec<SignedOperation>,
    dependency_records: Vec<ThreadGenesisRecord>,
    receipt_records: Vec<crypto::thread_authority_admission::SignedAuthorityAdmission>,
    allow_partial: bool,
}

pub(super) fn validate_with_receipts(
    directory: tempfile::TempDir,
    ready: TransferReady,
    operations: Vec<SignedOperation>,
    dependencies: Vec<ThreadGenesisRecord>,
    receipt_records: Vec<crypto::thread_authority_admission::SignedAuthorityAdmission>,
) -> Result<StagedSource, Error> {
    let value = validate_disclosure_artifacts(
        ready
            .thread
            .as_ref()
            .ok_or(Error::Invalid("Thread absent"))?,
        ready
            .current
            .as_ref()
            .ok_or(Error::Invalid("revision absent"))?,
        ready
            .thread_genesis
            .as_ref()
            .ok_or(Error::Invalid("original genesis absent"))?,
        DisclosureInput {
            directory,
            operations,
            dependency_records: dependencies,
            receipt_records,
            allow_partial: !ready.full_closure_available,
        },
    )?;
    Ok(StagedSource {
        directory: value.directory,
        ready,
        operations: value.operations,
        dependencies: value.dependencies,
        state: value.state,
        partial_trees: value.partial_trees,
        authority_admissions: value.authority_admissions,
    })
}
/// Structurally verified original source and actual artifact closure. This is
/// not an author, audience, executor, or sharing-policy admission decision.
pub struct ValidatedSourceArtifacts {
    directory: tempfile::TempDir,
    operations: Vec<SignedOperation>,
    genesis: ThreadGenesisRecord,
    dependencies: Vec<ThreadGenesisRecord>,
    state: State,
    partial_trees: Vec<heddle_object_model::object::PartialTree>,
    authority_admissions:
        BTreeMap<ContentHash, crypto::thread_authority_admission::SignedAuthorityAdmission>,
}
impl ValidatedSourceArtifacts {
    pub fn artifact_paths(&self) -> [std::path::PathBuf; 2] {
        [
            self.directory.path().join("source.pack"),
            self.directory.path().join("source.idx"),
        ]
    }
    pub fn operations(&self) -> &[SignedOperation] {
        &self.operations
    }
    pub fn geneses(&self) -> impl Iterator<Item = &ThreadGenesisRecord> {
        std::iter::once(&self.genesis).chain(&self.dependencies)
    }
    pub fn state(&self) -> &State {
        &self.state
    }
    pub fn authority_admissions(
        &self,
    ) -> &BTreeMap<ContentHash, crypto::thread_authority_admission::SignedAuthorityAdmission> {
        &self.authority_admissions
    }
}
pub(crate) fn validate_artifacts(
    directory: tempfile::TempDir,
    thread: &ThreadRef,
    revision: &RevisionRef,
    original: &ThreadGenesisRecord,
    operations: Vec<SignedOperation>,
    dependency_records: Vec<ThreadGenesisRecord>,
    receipt_records: Vec<crypto::thread_authority_admission::SignedAuthorityAdmission>,
) -> Result<ValidatedSourceArtifacts, Error> {
    validate_disclosure_artifacts(
        thread,
        revision,
        original,
        DisclosureInput {
            directory,
            operations,
            dependency_records,
            receipt_records,
            allow_partial: false,
        },
    )
}

fn validate_disclosure_artifacts(
    thread: &ThreadRef,
    revision: &RevisionRef,
    original: &ThreadGenesisRecord,
    input: DisclosureInput,
) -> Result<ValidatedSourceArtifacts, Error> {
    let DisclosureInput {
        directory,
        operations,
        dependency_records,
        receipt_records,
        allow_partial,
    } = input;
    if operations.len() > 10_000
        || dependency_records.len() >= 128
        || receipt_records.len() > operations.len()
    {
        return Err(Error::Invalid("source original graph exceeds bounds"));
    }
    let mut metadata = original.encoded_len();
    for record in &dependency_records {
        metadata = metadata.saturating_add(record.encoded_len());
    }
    for operation in &operations {
        metadata = metadata.saturating_add(operation.canonical.len() + operation.signature.len());
    }
    for receipt in &receipt_records {
        metadata = metadata.saturating_add(receipt.canonical.len() + receipt.signature.len());
    }
    let mut evidence_ids = BTreeSet::new();
    for wrapper in std::iter::once(original).chain(&dependency_records) {
        for record in &wrapper.boundary_acceptances {
            evidence_ids.insert(heddle_object_model::object::ContentHash::compute_typed(
                heddle_object_model::object::original_boundary_acceptance::FORMAT,
                &record.canonical_record,
            ));
            if evidence_ids.len() > crate::boundary_acceptance::MAX_ACCEPTANCES {
                return Err(Error::Invalid("boundary evidence count exceeded"));
            }
        }
    }
    for receipt in &receipt_records {
        if let Some(evidence) = &receipt.boundary_acceptance {
            if evidence_ids.insert(
                evidence
                    .verify_signature()
                    .map_err(preparation)?
                    .id()
                    .map_err(preparation)?,
            ) {
                metadata =
                    metadata.saturating_add(evidence.canonical.len() + evidence.signature.len());
            }
            if evidence_ids.len() > crate::boundary_acceptance::MAX_ACCEPTANCES {
                return Err(Error::Invalid("boundary evidence count exceeded"));
            }
        }
    }
    if metadata > METADATA_BYTES {
        return Err(Error::Invalid("source metadata exceeds 16 MiB"));
    }
    if revision.spool != thread.spool {
        return Err(Error::Invalid("source revision crosses Spool"));
    }
    let genesis = super::verify_origin(original, thread)?;
    let Some(revision_ref::Revision::State(selected)) = revision.revision.as_ref() else {
        return Err(Error::Invalid("exact native State required"));
    };
    let selected_thread = genesis.id().map_err(preparation)?;
    if operations.is_empty() {
        if !dependency_records.is_empty() || !receipt_records.is_empty() {
            return Err(Error::Invalid(
                "initial source cannot carry dependency originals",
            ));
        }
        let state =
            heddle_object_model::object::thread_replication::hosted_import::synthetic_initial_base(
            )
            .map_err(preparation)?;
        let canonical = state.encode_current_msgpack().map_err(preparation)?;
        heddle_object_model::object::thread_replication::hosted_import::initial_base_state(
            &genesis, &canonical,
        )
        .map_err(preparation)?;
        if selected.value.as_slice() != state.id().as_bytes() {
            return Err(Error::Invalid(
                "selected initial source differs from canonical seed",
            ));
        }
        PackReader::open(
            &directory.path().join("source.pack"),
            &directory.path().join("source.idx"),
        )
        .map_err(preparation)?
        .validate_source_closure_with_metadata(&state, &[], None, SOURCE_OBJECTS, SOURCE_BYTES)
        .map_err(preparation)?;
        return Ok(ValidatedSourceArtifacts {
            directory,
            operations,
            genesis: original.clone(),
            dependencies: Vec::new(),
            state,
            partial_trees: Vec::new(),
            authority_admissions: BTreeMap::new(),
        });
    }
    let mut geneses = BTreeMap::from([(selected_thread, genesis)]);
    let mut dependencies = Vec::new();
    for wrapper in dependency_records {
        let record = wrapper
            .genesis
            .as_ref()
            .ok_or(Error::Invalid("dependency signed genesis absent"))?;
        let candidate = heddle_object_model::object::thread_replication::ThreadGenesis::decode(
            &record.canonical_record,
        )
        .map_err(preparation)?;
        let reference = ThreadRef {
            spool: thread.spool.clone(),
            id: Some(ThreadId {
                value: candidate.id().map_err(preparation)?.as_bytes().to_vec(),
            }),
        };
        let candidate = super::verify_origin(&wrapper, &reference)?;
        let id = candidate.id().map_err(preparation)?;
        if geneses.len() >= 128 || geneses.insert(id, candidate).is_some() {
            return Err(Error::Invalid(
                "duplicate or oversized dependency genesis set",
            ));
        }
        dependencies.push(wrapper);
    }
    let mut claim_frontiers = BTreeMap::new();
    for wrapper in std::iter::once(original).chain(&dependencies) {
        let signed = wrapper
            .genesis
            .as_ref()
            .ok_or(Error::Invalid("claim genesis absent"))?;
        let genesis = heddle_object_model::object::thread_replication::ThreadGenesis::decode(
            &signed.canonical_record,
        )
        .map_err(preparation)?;
        let mut frontier = BTreeSet::new();
        let claims = crate::replication::ownership::verify_claims(wrapper, &genesis)?;
        let resolutions = crate::replication::ownership::verify_resolutions(wrapper, &genesis)?;
        if claims.is_empty() && resolutions.is_empty() {
            continue;
        }
        for claim in claims {
            frontier.extend(
                claim
                    .original
                    .verify()
                    .map_err(preparation)?
                    .source_frontier,
            );
        }
        for resolution in resolutions {
            frontier.extend(
                heddle_object_model::object::thread_replication::ownership_resolution::ThreadOwnershipResolution::decode(&resolution.original.canonical)
                    .map_err(preparation)?.frontier,
            );
        }
        claim_frontiers.insert(genesis.id().map_err(preparation)?, frontier);
    }
    let mut originals = BTreeMap::new();
    let mut decoded = BTreeMap::<ContentHash, ThreadOperation>::new();
    let mut selected_operation = None;
    let mut source_thread = selected_thread;
    let mut inherited_bases = BTreeSet::new();
    for _ in 0..128 {
        let current = geneses
            .get(&source_thread)
            .ok_or(Error::Invalid("fork base source genesis absent"))?;
        if selected.value.as_slice() != current.base.as_bytes() {
            break;
        }
        let parent = current.parent.ok_or(Error::Invalid(
            "non-system base has no original parent source",
        ))?;
        if !inherited_bases.insert(source_thread) {
            return Err(Error::Invalid("fork base parent cycle"));
        }
        let ancestor = geneses
            .get(&parent)
            .ok_or(Error::Invalid("fork base parent original absent"))?;
        if ancestor.spool != current.spool {
            return Err(Error::Invalid("fork base crosses Spool"));
        }
        source_thread = parent;
    }
    if selected.value.as_slice()
        == geneses
            .get(&source_thread)
            .ok_or(Error::Invalid("fork base source genesis absent"))?
            .base
            .as_bytes()
    {
        return Err(Error::Invalid("fork base source chain exceeds bound"));
    }
    for signed in &operations {
        let operation = signed.verify().map_err(preparation)?;
        let id = operation.id().map_err(preparation)?;
        let state = operation
            .source_state()
            .map_err(preparation)?
            .ok_or(Error::Invalid("non-source operation in source ancestry"))?;
        if operation.thread == source_thread
            && state.id().as_bytes().as_slice() == selected.value
            && selected_operation.replace((id, state)).is_some()
        {
            return Err(Error::Invalid("ambiguous selected source proof"));
        }
        originals.insert(id, signed.clone());
        if decoded.insert(id, operation).is_some() {
            return Err(Error::Invalid("duplicate source proof"));
        }
    }
    let mut authority_admissions = BTreeMap::new();
    for receipt in receipt_records {
        let statement = receipt.verify_signature().map_err(preparation)?;
        let operation_id = statement.subject.operation_id().ok_or(Error::Invalid(
            "source batch cannot carry ownership claim admission",
        ))?;
        let original = originals
            .get(&operation_id)
            .ok_or(Error::Invalid("unmatched source authority receipt"))?;
        // Match immutable claims and signatures only. This self-described key
        // is not enrolled here; the receiver must independently pin the issuer.
        receipt.verify(original, &heddle_object_model::object::thread_replication::integration::TrustedHostedExecutor {
            spool: statement.spool, spool_genesis: statement.spool_genesis, executor: statement.executor,
        }).map_err(preparation)?;
        if authority_admissions.insert(operation_id, receipt).is_some() {
            return Err(Error::Invalid("duplicate source authority receipt"));
        }
    }
    let (selected_id, state) =
        selected_operation.ok_or(Error::Invalid("selected source proof absent"))?;
    let mut pending = BTreeSet::from([selected_id]);
    let mut seen = BTreeSet::new();
    let mut used_threads = BTreeSet::new();
    let mut edges = BTreeMap::new();
    while let Some(id) = pending.pop_first() {
        if !seen.insert(id) {
            continue;
        }
        let operation = decoded
            .get(&id)
            .ok_or(Error::Invalid("incomplete source ancestry"))?;
        let parents = operation
            .parents
            .iter()
            .map(|id| {
                decoded
                    .get(id)
                    .cloned()
                    .ok_or(Error::Invalid("incomplete source ancestry"))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let genesis = geneses
            .get(&operation.thread)
            .ok_or(Error::Invalid("source dependency genesis absent"))?;
        if used_threads.insert(operation.thread)
            && let Some(frontier) = claim_frontiers.get(&operation.thread)
        {
            for head in frontier {
                if decoded
                    .get(head)
                    .is_none_or(|source| source.thread != operation.thread)
                {
                    return Err(Error::Invalid(
                        "ownership claim cutoff source proof absent or foreign",
                    ));
                }
            }
            pending.extend(frontier);
        }
        operation
            .validate_parents(genesis, &parents)
            .map_err(preparation)?;
        let mut required = operation.parents.clone();
        if let Some(receipt) = operation.local_integration().map_err(preparation)? {
            let source = decoded
                .get(&receipt.source_operation)
                .ok_or(Error::Invalid(
                    "local integration original source proof absent",
                ))?;
            receipt.validate_source(source).map_err(preparation)?;
            required.insert(receipt.source_operation);
            pending.insert(receipt.source_operation);
        }
        if let Some(receipt) = operation.integration().map_err(preparation)? {
            let source = decoded
                .get(&receipt.source_operation)
                .ok_or(Error::Invalid(
                    "hosted integration original source proof absent",
                ))?;
            receipt.validate_source(source).map_err(preparation)?;
            required.insert(receipt.source_operation);
            pending.insert(receipt.source_operation);
        }
        edges.insert(id, required);
        pending.extend(
            operation
                .parents
                .iter()
                .filter(|id| !seen.contains(id))
                .copied(),
        );
    }
    if seen.len() != decoded.len()
        || used_threads
            .union(&inherited_bases)
            .copied()
            .collect::<BTreeSet<_>>()
            != geneses.keys().copied().collect()
    {
        return Err(Error::Invalid("unselected source proofs"));
    }
    // A claim cutoff is an additional signed causal barrier. Ancestors retain
    // their original local author; work outside it must follow the claim.
    for (thread, frontier) in &claim_frontiers {
        let mut history = BTreeSet::new();
        let mut pending = frontier.clone();
        while let Some(id) = pending.pop_first() {
            if !history.insert(id) {
                continue;
            }
            let operation = decoded
                .get(&id)
                .ok_or(Error::Invalid("claim cutoff ancestry absent"))?;
            if operation.thread != *thread {
                return Err(Error::Invalid("claim cutoff crosses Thread"));
            }
            pending.extend(&operation.parents);
        }
        {
            for (id, operation) in &decoded {
                if operation.thread == *thread && !history.contains(id) {
                    if matches!(
                        operation.source_author().map_err(preparation)?,
                        Some(
                            heddle_object_model::object::thread_replication::SourceAuthor::LocalKey
                        )
                    ) {
                        return Err(Error::Invalid(
                            "new local source lies outside signed ownership cutoff",
                        ));
                    }
                    edges
                        .get_mut(id)
                        .ok_or(Error::Invalid("source topology entry absent"))?
                        .extend(frontier);
                }
            }
        }
    }
    let references = decoded
        .values()
        .map(|operation| {
            operation
                .reference_proof(
                    geneses
                        .get(&operation.thread)
                        .ok_or(Error::Invalid("dependency genesis absent"))?,
                )
                .map_err(preparation)
        })
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .flatten()
        .collect::<Vec<_>>();
    let capture = decoded
        .get(&selected_id)
        .ok_or(Error::Invalid("selected source operation absent"))?
        .source_result()
        .map_err(preparation)?
        .ok_or(Error::Invalid("selected operation has no source result"))?;
    let pack = PackReader::open(
        &directory.path().join("source.pack"),
        &directory.path().join("source.idx"),
    )
    .map_err(preparation)?;
    let partial_trees = if allow_partial {
        pack.validate_visible_source_closure(&state, SOURCE_OBJECTS, SOURCE_BYTES)
            .map_err(preparation)?
            .partial_trees
    } else {
        pack.validate_source_closure_with_metadata(
            &state,
            &references,
            capture.visibility.as_ref(),
            SOURCE_OBJECTS,
            SOURCE_BYTES,
        )
        .map_err(preparation)?;
        Vec::new()
    };
    // Dependency-first installation makes foreign source authority available
    // before admitting a local integration. Cycles cannot settle this graph.
    let mut ready_ids: BTreeSet<_> = edges
        .iter()
        .filter(|(_, parents)| parents.is_empty())
        .map(|(id, _)| *id)
        .collect();
    let mut children: BTreeMap<ContentHash, Vec<ContentHash>> = BTreeMap::new();
    for (child, parents) in &edges {
        for parent in parents {
            children.entry(*parent).or_default().push(*child);
        }
    }
    let mut ordered = Vec::new();
    while let Some(id) = ready_ids.pop_first() {
        ordered.push(
            originals
                .remove(&id)
                .ok_or(Error::Invalid("duplicate source topology identity"))?,
        );
        if let Some(dependants) = children.get(&id) {
            for child in dependants {
                let parents = edges
                    .get_mut(child)
                    .ok_or(Error::Invalid("incomplete source topology"))?;
                parents.remove(&id);
                if parents.is_empty() {
                    ready_ids.insert(*child);
                }
            }
        }
    }
    if !originals.is_empty() {
        return Err(Error::Invalid("source dependency cycle"));
    }
    Ok(ValidatedSourceArtifacts {
        directory,
        genesis: original.clone(),
        operations: ordered,
        authority_admissions,
        dependencies,
        state,
        partial_trees,
    })
}
fn preparation(error: impl std::fmt::Display) -> Error {
    Error::Preparation(error.to_string())
}

#[cfg(test)]
#[path = "staging_tests.rs"]
mod tests;