triblespace-core 0.47.1

The triblespace core implementation.
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
//! Immutable collection observations and logical views over their realized
//! covers.
//!
//! A [`CollectionSnapshot`] owns the store observation against which its
//! realized target cover is valid. Its support comes with it, read from the
//! coverage index by the same selection: a cover of the collection's own
//! foundations. Whether a derived collection has caught up with its source
//! is [`CollectionSnapshot::missing_from`]. Logical values remain
//! caller-chosen projections reconstructed through [`TryFromCover`].

use std::collections::{BTreeSet, HashMap};
use std::convert::Infallible;
use std::error::Error;
use std::fmt;

use crate::blob::encodings::simplearchive::SimpleArchive;
use crate::blob::{Blob, BlobEncoding, Bytes, TryFromBlob};
use crate::inline::encodings::hash::Handle;
use crate::inline::{Inline, InlineEncoding};
use crate::repo::{BlobStoreGet, BlobStoreMeta, StoreChanges, StoreRead, StoreSnapshot};
use crate::trible::Fragment;

use super::observed_store::{DependencyTracker, ObservedStore};
use super::{
    CollectionData, CollectionDescriptorError, CollectionEncoding, CollectionHandle,
    CollectionRealizationError, Cover, CoverageRead, MapMapping, RecordDecodeError, SourceLocator,
    Support,
};

/// One immutable collection observation and what it stands on.
///
/// The cover is the target's resident frontier, selected from the coverage
/// index; the support is the union of what those nodes stand for, taken from
/// the same index in the same selection: the target's own foundations.
/// Reading the value does not require the historical inputs to be present.
/// Logical views are reconstructed on demand with [`Self::view`].
pub struct CollectionSnapshot<R, E>
where
    R: StoreSnapshot,
    E: CollectionEncoding,
{
    snapshot: R,
    support: Support<E>,
    cover: Cover<E>,
    dependencies: DependencyTracker,
}

impl<R, E> Clone for CollectionSnapshot<R, E>
where
    R: StoreSnapshot,
    E: CollectionEncoding,
{
    fn clone(&self) -> Self {
        Self {
            snapshot: self.snapshot.clone(),
            support: self.support.clone(),
            cover: self.cover.clone(),
            dependencies: self.dependencies.clone(),
        }
    }
}

impl<R, E> CollectionSnapshot<R, E>
where
    R: StoreSnapshot,
    E: CollectionEncoding,
{
    /// Pair one store observation with a cover and support taken from the
    /// coverage index's frontier. Both are read from the target's own rows,
    /// whose read-set is already in `dependencies`.
    pub(crate) fn from_frontier(
        snapshot: R,
        support: Support<E>,
        cover: Cover<E>,
        dependencies: DependencyTracker,
    ) -> Self {
        Self {
            snapshot,
            support,
            cover,
            dependencies,
        }
    }

    /// Immutable store observation against which the cover and provenance are valid.
    pub fn snapshot(&self) -> &R {
        &self.snapshot
    }

    /// Whether all consulted store dependencies are unchanged in `snapshot`.
    ///
    /// Missing records and blobs are dependencies too. Unrelated appends do
    /// not invalidate an observation on backends with scoped indexes. A false
    /// result is conservative: a reattachment may still select the same cover.
    /// Application clocks and deadlines are independent of this comparison.
    /// Reading a view or requesting support extends the tracked read-set.
    pub fn is_current(&self, snapshot: &R) -> bool {
        let dependencies = self
            .dependencies
            .lock()
            .expect("dependency tracker poisoned");
        snapshot.changes_for(&self.snapshot, &dependencies) == StoreChanges::NONE
    }

    /// What this observation stands on: a cover of the collection's own
    /// foundations -- commit payloads for a root, leaf images for a derived
    /// collection.
    ///
    /// It is read from the target's own rows, the same ones the cover came
    /// from, so it adds nothing to the read-set. Two collections' supports
    /// are never comparable; ask [`Self::missing_from`] whether a derived
    /// collection has caught up with its source.
    pub fn support(&self) -> Result<&Support<E>, CollectionRealizationError>
    where
        R: StoreRead,
    {
        Ok(&self.support)
    }

    /// The foundations of `source` this observation does not answer for:
    /// the freshness of a view against a source observation.
    ///
    /// Each source foundation `F` is looked up by its locator `L(F)` in this
    /// collection's leaves, the DERIVE relation read by its own key, and
    /// counts as answered only when one of its outputs is in this
    /// observation's support, which is what [`Self::view`] reads. A leaf whose
    /// image is not here yet, and is under no resident merge, is still
    /// missing: a caller that treated the leaf record as delivery would skip
    /// facts it never saw. Nothing is compared between the two collections'
    /// supports. `source` must be the collection this one's descriptor names
    /// as its source; the two observations may be of different store
    /// snapshots, and the answer is then this view against that source's
    /// foundations.
    pub fn missing_from<RS, S>(
        &self,
        source: &CollectionSnapshot<RS, S>,
    ) -> Result<Cover<S>, CollectionRealizationError>
    where
        R: StoreRead,
        RS: StoreRead,
        S: CollectionEncoding,
    {
        let target = self.cover.collection().handle();
        let observed =
            ObservedStore::with_tracker(self.snapshot.clone(), self.dependencies.clone());
        let descriptor = super::api::load_collection_descriptor(&observed, target)
            .map_err(|error| CollectionRealizationError::storage("read view descriptor", error))?;
        let named = super::descriptor::source(descriptor.fragment.facts()).map_err(|error| {
            CollectionRealizationError::Resolution(format!("read view source: {error}"))
        })?;
        let source_collection = source.cover().collection();
        if named != Some(source_collection.handle()) {
            return Err(CollectionRealizationError::InvalidCover(format!(
                "collection {} does not derive from {}",
                hex::encode_upper(target.raw),
                hex::encode_upper(source_collection.handle().raw),
            )));
        }
        let coverage = observed
            .coverage(&BTreeSet::from([target]))
            .map_err(|error| CollectionRealizationError::storage("read view leaves", error))?;
        let missing = source.support()?.data_members().filter(|foundation| {
            !coverage
                .leaf_outputs(target, SourceLocator::of(foundation.raw))
                .into_iter()
                .any(|output| {
                    self.support
                        .contains(crate::inline::Inline::new(output.raw))
                })
        });
        Ok(Cover::from_data(source_collection, missing))
    }

    /// Resident target cover selected from the coverage index.
    pub fn cover(&self) -> &Cover<E> {
        &self.cover
    }

    /// Reconstruct one caller-chosen logical value from the realized cover.
    pub fn view<V>(&self) -> Result<V, TryFromCoverError<R::GetError<Infallible>, V::Error>>
    where
        R: BlobStoreGet,
        V: TryFromCover<E>,
    {
        let observed =
            ObservedStore::with_tracker(self.snapshot.clone(), self.dependencies.clone());
        let descriptor =
            super::api::load_collection_descriptor(&observed, self.cover.collection().handle())
                .map_err(TryFromCoverError::from)?;
        V::try_from_cover(&self.cover, &descriptor.fragment, &observed)
    }

    /// Consume this snapshot into its store observation, its support and its
    /// cover.
    pub fn into_parts(self) -> Result<(R, Support<E>, Cover<E>), CollectionRealizationError>
    where
        R: StoreRead,
    {
        Ok((self.snapshot, self.support, self.cover))
    }
}

/// One immutable observation of an attached collection: the attached cover
/// over its parent's lattice.
///
/// The cover is a set of attachments, one per parent node taken; the
/// support is the parent foundations those nodes stand for, read from the
/// parent's own rows in the same observation; the residual is the parent
/// foundations no attachment reaches. An attached collection has no support
/// of its own: it stands for its parent's.
pub struct AttachedSnapshot<R, E>
where
    R: StoreSnapshot,
    E: CollectionEncoding,
{
    snapshot: R,
    cover: Cover<E>,
    support: Support<SimpleArchive>,
    residual: Support<SimpleArchive>,
    dependencies: DependencyTracker,
}

#[cfg(feature = "object-store")]
impl<R, E> AttachedSnapshot<crate::repo::async_store::AcquiringReader<R>, E>
where
    R: StoreSnapshot,
    E: CollectionEncoding,
{
    /// Remove only the acquisition adapter, retaining this selected cover,
    /// support, residual and read-set. This extracts the exact original frozen
    /// reader; it cannot substitute another snapshot or reselect after a fetch.
    pub fn into_frozen(self) -> AttachedSnapshot<R, E> {
        AttachedSnapshot {
            snapshot: self.snapshot.into_frozen(),
            cover: self.cover,
            support: self.support,
            residual: self.residual,
            dependencies: self.dependencies,
        }
    }
}

impl<R, E> Clone for AttachedSnapshot<R, E>
where
    R: StoreSnapshot,
    E: CollectionEncoding,
{
    fn clone(&self) -> Self {
        Self {
            snapshot: self.snapshot.clone(),
            cover: self.cover.clone(),
            support: self.support.clone(),
            residual: self.residual.clone(),
            dependencies: self.dependencies.clone(),
        }
    }
}

impl<R, E> AttachedSnapshot<R, E>
where
    R: StoreSnapshot,
    E: CollectionEncoding,
{
    pub(crate) fn new(
        snapshot: R,
        cover: Cover<E>,
        support: Support<SimpleArchive>,
        residual: Support<SimpleArchive>,
        dependencies: DependencyTracker,
    ) -> Self {
        Self {
            snapshot,
            cover,
            support,
            residual,
            dependencies,
        }
    }

    /// Immutable store observation against which the cover is valid.
    pub fn snapshot(&self) -> &R {
        &self.snapshot
    }

    /// Whether everything consulted is unchanged in `snapshot`: the parent's
    /// and the attached collection's records, and the residency of every
    /// attachment and dependency looked at and of every residual foundation.
    /// A MAP, an attachment's bytes or a residual foundation's bytes arriving
    /// moves an observation off current, and so does a new parent node.
    pub fn is_current(&self, snapshot: &R) -> bool {
        let dependencies = self
            .dependencies
            .lock()
            .expect("dependency tracker poisoned");
        snapshot.changes_for(&self.snapshot, &dependencies) == StoreChanges::NONE
    }

    /// The attachments taken, in the attached collection.
    pub fn cover(&self) -> &Cover<E> {
        &self.cover
    }

    /// The parent foundations the taken attachments stand for.
    pub fn support(&self) -> &Support<SimpleArchive> {
        &self.support
    }

    /// The parent foundations no taken attachment reaches: a node whose
    /// attachment is not built yet, cannot be represented, or waits for a
    /// dependency. Read these raw, build them, or report them as a gap;
    /// membership never implies that their bytes are here.
    pub fn residual(&self) -> &Support<SimpleArchive> {
        &self.residual
    }

    /// Reconstruct one caller-chosen logical value from the attachments
    /// taken, and nothing else.
    ///
    /// The residual is not part of it, so beside a read that does include
    /// the residual -- the facts of the same parent, say -- it answers for
    /// less than they do. [`Self::read`] is the whole read; this is the
    /// cover alone, for a caller that reads the residual some other way or
    /// reports it.
    pub fn view<V>(&self) -> Result<V, TryFromCoverError<R::GetError<Infallible>, V::Error>>
    where
        R: BlobStoreGet,
        V: TryFromCover<E>,
    {
        let observed =
            ObservedStore::with_tracker(self.snapshot.clone(), self.dependencies.clone());
        let descriptor =
            super::api::load_collection_descriptor(&observed, self.cover.collection().handle())
                .map_err(TryFromCoverError::from)?;
        V::try_from_cover(&self.cover, &descriptor.fragment, &observed)
    }

    /// Reconstruct one caller-chosen logical value over everything the
    /// parent stands on in this observation, through the canonical mapping
    /// the attached descriptor names: [`Self::read_with`] for
    /// [`CollectionAttachment`](super::CollectionAttachment).
    pub fn read<V>(
        &self,
    ) -> Result<AttachedRead<V>, AttachedReadError<R::GetError<Infallible>, V::Error>>
    where
        R: StoreRead,
        E: super::CollectionAttachment,
        V: TryFromCover<E>,
    {
        self.read_with::<super::encoding::CanonicalAttachment<E>, V>()
    }

    /// Read this exact selected cover and residual through an acquiring reader.
    /// Missing residual bytes are requested by handle, not skipped on the
    /// snapshot's frozen residency. Unavailable inputs remain explicit unread
    /// members; other read and mapping failures are returned. No records,
    /// proofs, cover, or support are refreshed and no work is published.
    pub fn read_acquiring<V>(
        &self,
    ) -> Result<AttachedRead<V>, AttachedReadError<R::GetError<Infallible>, V::Error>>
    where
        R: StoreRead,
        E: super::CollectionAttachment,
        V: TryFromCover<E>,
    {
        self.read_with_acquiring::<super::encoding::CanonicalAttachment<E>, V>()
    }

    /// The explicit-mapping form of [`Self::read_acquiring`].
    pub fn read_with_acquiring<M, V>(
        &self,
    ) -> Result<AttachedRead<V>, AttachedReadError<R::GetError<Infallible>, V::Error>>
    where
        R: StoreRead,
        M: MapMapping<Target = E>,
        V: TryFromCover<E>,
    {
        self.read_mode::<M, V>(true)
    }

    /// Wrap only the byte reader of this already-selected observation.
    /// The caller must keep the runtime and network store owner alive and
    /// execute synchronous reads outside an async task (e.g. spawn_blocking).
    #[cfg(feature = "object-store")]
    pub fn acquiring(
        &self,
        runtime: tokio::runtime::Handle,
    ) -> AttachedSnapshot<crate::repo::async_store::AcquiringReader<R>, E> {
        AttachedSnapshot {
            snapshot: crate::repo::async_store::AcquiringReader::with_handle(
                self.snapshot.clone(),
                runtime,
            ),
            cover: self.cover.clone(),
            support: self.support.clone(),
            residual: self.residual.clone(),
            dependencies: self.dependencies.clone(),
        }
    }

    /// Reconstruct one caller-chosen logical value over everything the
    /// parent stands on in this observation: the attachments taken, and an
    /// image of every residual foundation built in memory through `M`.
    ///
    /// This is the reader's half of "read raw, build, or report a gap": a
    /// residual foundation whose bytes are here is mapped the way
    /// maintenance would map it, and the view is formed over the cover and
    /// those images together, so, by the mapping's cover-query law
    /// ([`MapMapping`]), it answers like the view of the parent's whole
    /// support and never less than a fact read of the same observation. A
    /// mapping whose law is a premise about its input answers so only where
    /// the premise holds; where it does not, nothing here is unread to show
    /// it. Nothing is stored or published. What cannot be built
    /// here -- bytes not here, a dependency the mapping names not here, a
    /// node the mapping cannot represent or interpret, or any node at all
    /// when the mapping reads sibling attachments -- is named in
    /// [`AttachedRead::unread`], never read as absent. The mapping's reads
    /// join this observation's read-set, so a dependency arriving moves it
    /// off current.
    ///
    /// `M` must be the mapping the attached descriptor names; one it does
    /// not bind is [`AttachedReadError::Mapping`].
    pub fn read_with<M, V>(
        &self,
    ) -> Result<AttachedRead<V>, AttachedReadError<R::GetError<Infallible>, V::Error>>
    where
        R: StoreRead,
        M: MapMapping<Target = E>,
        V: TryFromCover<E>,
    {
        self.read_mode::<M, V>(false)
    }

    fn read_mode<M, V>(
        &self,
        acquire: bool,
    ) -> Result<AttachedRead<V>, AttachedReadError<R::GetError<Infallible>, V::Error>>
    where
        R: StoreRead,
        M: MapMapping<Target = E>,
        V: TryFromCover<E>,
    {
        let observed =
            ObservedStore::with_tracker(self.snapshot.clone(), self.dependencies.clone());
        let attached = self.cover.collection();
        let parent = self.support.collection();
        let descriptor = super::api::load_collection_descriptor(&observed, attached.handle())
            .map_err(|error| AttachedReadError::View(error.into()))?;
        let parent_descriptor = super::api::load_collection_descriptor(&observed, parent.handle())
            .map_err(|error| AttachedReadError::View(error.into()))?;
        let mapping = M::bind(&parent_descriptor.fragment, &descriptor.fragment)
            .map_err(AttachedReadError::Mapping)?;
        // A sibling's attachment of a residual node is not built here: the
        // sibling's own mapping is not known to this read.
        let builds = mapping.siblings().is_empty();
        let mut images: HashMap<[u8; 32], Bytes> = HashMap::new();
        let mut unread = Vec::new();
        for foundation in self.residual.members() {
            let member = Handle::<SimpleArchive>::to_hash(foundation);
            if !builds {
                unread.push(member);
                continue;
            }
            let failed = |reason: String| AttachedReadError::Residual { member, reason };
            if !acquire
                && observed
                    .metadata(foundation)
                    .map_err(|error| failed(error.to_string()))?
                    .is_none()
            {
                unread.push(member);
                continue;
            }
            let node: Blob<SimpleArchive> = match observed.get(foundation) {
                Ok(node) => node,
                Err(error) if acquire && crate::repo::is_missing_blob(&error) => {
                    unread.push(member);
                    continue;
                }
                Err(error) => return Err(failed(error.to_string())),
            };
            match mapping.map(&node, &[], &observed) {
                Ok(image) => {
                    images.insert(image.get_handle().raw, image.bytes);
                }
                Err(super::CollectionOperationError::Fatal(reason)) if acquire => {
                    return Err(failed(reason));
                }
                Err(_) => unread.push(member),
            }
        }
        let cover = Cover::from_members(
            attached,
            self.cover
                .members()
                .chain(images.keys().map(|raw| Inline::new(*raw))),
        );
        let reader = WithImages {
            base: &observed,
            images: &images,
        };
        let value = V::try_from_cover(&cover, &descriptor.fragment, &reader)
            .map_err(|error| AttachedReadError::View(error.into_base()))?;
        Ok(AttachedRead::new(value, Support::from_data(parent, unread)))
    }
}

/// A logical value an attached collection gives over its parent's whole
/// support in one observation ([`AttachedSnapshot::read`]), and the residual
/// foundations it could not include.
#[derive(Clone, Debug)]
pub struct AttachedRead<V> {
    value: V,
    unread: Support<SimpleArchive>,
}

impl<V> AttachedRead<V> {
    pub(crate) fn new(value: V, unread: Support<SimpleArchive>) -> Self {
        Self { value, unread }
    }

    /// The value, over the attachments taken and every residual foundation
    /// read here.
    pub fn value(&self) -> &V {
        &self.value
    }

    /// The value alone.
    pub fn into_value(self) -> V {
        self.value
    }

    /// The residual foundations the value leaves out, each a gap: its bytes
    /// are not here, a dependency its mapping names is not here, or the
    /// mapping cannot represent or interpret it here. The rest of the
    /// residual is in the value. Empty when every foundation the parent
    /// stands on in this observation went into the value; whether the value
    /// then answers like their union is the mapping's cover-query law, which
    /// for some mappings is a premise about the input that nothing here
    /// checks ([`MapMapping`]).
    pub fn unread(&self) -> &Support<SimpleArchive> {
        &self.unread
    }

    /// The value and what it leaves out.
    pub fn into_parts(self) -> (V, Support<SimpleArchive>) {
        (self.value, self.unread)
    }

    /// The same read with its value transformed.
    pub fn map<W>(self, transform: impl FnOnce(V) -> W) -> AttachedRead<W> {
        AttachedRead {
            value: transform(self.value),
            unread: self.unread,
        }
    }
}

/// Failure to read an attached collection with its residual
/// ([`AttachedSnapshot::read_with`]).
#[derive(Debug)]
pub enum AttachedReadError<GetError, ViewError> {
    /// A descriptor or an attachment could not be read, or the view could
    /// not be formed from the attachments and the images built.
    View(TryFromCoverError<GetError, ViewError>),
    /// The attached descriptor does not name the mapping read through.
    Mapping(super::CollectionOperationError),
    /// The store could not read a residual foundation whose bytes are here.
    Residual {
        /// The parent foundation.
        member: CollectionData,
        /// What went wrong.
        reason: String,
    },
}

impl<GetError, ViewError> fmt::Display for AttachedReadError<GetError, ViewError>
where
    GetError: fmt::Display,
    ViewError: fmt::Display,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::View(source) => source.fmt(formatter),
            Self::Mapping(source) => write!(
                formatter,
                "attached descriptor does not bind the mapping read through: {source}"
            ),
            Self::Residual { member, reason } => write!(
                formatter,
                "read residual foundation {}: {reason}",
                hex::encode_upper(member.raw),
            ),
        }
    }
}

impl<GetError, ViewError> Error for AttachedReadError<GetError, ViewError>
where
    GetError: Error + 'static,
    ViewError: Error + 'static,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::View(source) => Some(source),
            Self::Mapping(source) => Some(source),
            Self::Residual { .. } => None,
        }
    }
}

/// A store read with images built in memory beside it: a get of one of the
/// images answers from memory, every other get from the store.
struct WithImages<'a, R> {
    base: &'a R,
    images: &'a HashMap<[u8; 32], Bytes>,
}

/// A get through [`WithImages`]: an in-memory image that did not decode as
/// asked, or the store's own failure.
#[derive(Debug)]
enum WithImagesGetError<Decode, Base> {
    Decode(Decode),
    Base(Base),
}

impl<Decode: fmt::Display, Base: fmt::Display> fmt::Display for WithImagesGetError<Decode, Base> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Decode(source) => write!(formatter, "decode an image built in memory: {source}"),
            Self::Base(source) => source.fmt(formatter),
        }
    }
}

impl<Decode, Base> Error for WithImagesGetError<Decode, Base>
where
    Decode: Error + 'static,
    Base: Error + 'static,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Decode(source) => Some(source),
            Self::Base(source) => Some(source),
        }
    }
}

impl<R: BlobStoreGet> BlobStoreGet for WithImages<'_, R> {
    type GetError<E: Error + Send + Sync + 'static> = WithImagesGetError<E, R::GetError<E>>;

    fn get<T, S>(
        &self,
        handle: Inline<Handle<S>>,
    ) -> Result<T, Self::GetError<<T as TryFromBlob<S>>::Error>>
    where
        S: BlobEncoding + 'static,
        T: TryFromBlob<S>,
        Handle<S>: InlineEncoding,
    {
        match self.images.get(&handle.raw) {
            Some(bytes) => T::try_from_blob(Blob::with_handle(bytes.clone(), handle))
                .map_err(WithImagesGetError::Decode),
            None => self.base.get(handle).map_err(WithImagesGetError::Base),
        }
    }
}

impl<Base, ViewError> TryFromCoverError<WithImagesGetError<Infallible, Base>, ViewError> {
    /// The same failure, as the store's own: an in-memory image never fails
    /// to be read as the blob it is.
    fn into_base(self) -> TryFromCoverError<Base, ViewError> {
        let base = |source: WithImagesGetError<Infallible, Base>| match source {
            WithImagesGetError::Decode(never) => match never {},
            WithImagesGetError::Base(source) => source,
        };
        match self {
            Self::DescriptorGet { collection, source } => TryFromCoverError::DescriptorGet {
                collection,
                source: base(source),
            },
            Self::InvalidDescriptor { collection, source } => {
                TryFromCoverError::InvalidDescriptor { collection, source }
            }
            Self::MemberGet { member, source } => TryFromCoverError::MemberGet {
                member,
                source: base(source),
            },
            Self::View(source) => TryFromCoverError::View(source),
        }
    }
}

/// Failure at the generic boundary between a physical cover and its logical
/// interpretation.
#[derive(Debug)]
pub enum TryFromCoverError<GetError, ViewError> {
    /// The cover's canonical collection descriptor could not be fetched.
    DescriptorGet {
        /// Canonical collection identity.
        collection: CollectionHandle,
        /// Backend fetch failure.
        source: GetError,
    },
    /// The fetched descriptor was not a canonical collection descriptor.
    InvalidDescriptor {
        /// Canonical collection identity.
        collection: CollectionHandle,
        /// Structural descriptor decoding failure.
        source: RecordDecodeError,
    },
    /// One exact physical member could not be fetched from the snapshot.
    MemberGet {
        /// Selected physical member.
        member: CollectionData,
        /// Backend fetch failure.
        source: GetError,
    },
    /// Resident member bytes could not form the requested logical value.
    View(ViewError),
}

impl<GetError, ViewError> fmt::Display for TryFromCoverError<GetError, ViewError>
where
    GetError: fmt::Display,
    ViewError: fmt::Display,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DescriptorGet { collection, source } => write!(
                formatter,
                "failed to fetch collection descriptor {}: {source}",
                hex::encode_upper(collection.raw),
            ),
            Self::InvalidDescriptor { collection, source } => write!(
                formatter,
                "collection descriptor {} is invalid: {source}",
                hex::encode_upper(collection.raw),
            ),
            Self::MemberGet { member, source } => write!(
                formatter,
                "failed to fetch cover member {}: {source}",
                hex::encode_upper(member.raw),
            ),
            Self::View(source) => source.fmt(formatter),
        }
    }
}

impl<GetError, ViewError> Error for TryFromCoverError<GetError, ViewError>
where
    GetError: Error + 'static,
    ViewError: Error + 'static,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::DescriptorGet { source, .. } => Some(source),
            Self::InvalidDescriptor { source, .. } => Some(source),
            Self::MemberGet { source, .. } => Some(source),
            Self::View(source) => Some(source),
        }
    }
}

impl<GetError, ViewError> From<CollectionDescriptorError<GetError>>
    for TryFromCoverError<GetError, ViewError>
{
    fn from(source: CollectionDescriptorError<GetError>) -> Self {
        match source {
            CollectionDescriptorError::Get { collection, source } => {
                Self::DescriptorGet { collection, source }
            }
            CollectionDescriptorError::Invalid { collection, source } => {
                Self::InvalidDescriptor { collection, source }
            }
        }
    }
}

/// Low-level reconstruction hook for one selected typed physical cover.
///
/// This is deliberately cover-aware rather than a blanket blob conversion:
/// some values eagerly join members, while others retain mmap-backed shards
/// and answer queries over the union without constructing one monolith.
pub trait TryFromCover<L: CollectionEncoding>: Sized {
    /// Failure to construct the logical view from the resolved cover.
    type Error: Error + Send + Sync + 'static;

    /// Reconstruct the logical value named by `cover` through `snapshot`.
    ///
    /// Normal callers use [`CollectionSnapshot::view`], which passes the exact
    /// realized cover, its canonical descriptor, and the immutable store
    /// observation that validated it. Encoding-specific parameters belong in
    /// the descriptor rather than in a lifecycle facade around the collection.
    fn try_from_cover<R>(
        cover: &Cover<L>,
        descriptor: &Fragment,
        snapshot: &R,
    ) -> Result<Self, TryFromCoverError<R::GetError<Infallible>, Self::Error>>
    where
        R: BlobStoreGet;
}

#[cfg(test)]
mod tests {
    use crate::blob::encodings::succinctarchive::SuccinctArchiveBlob;
    use crate::collection::observed_store::ObservedStore;
    use crate::collection::{Collection, CollectionData, CollectionHandle};
    use crate::repo::memoryrepo::MemoryRepo;
    use crate::repo::SnapshotSource;

    use super::{CollectionSnapshot, Cover, Support};

    #[test]
    fn snapshot_keeps_its_own_support_beside_its_cover() {
        let target = Collection::<SuccinctArchiveBlob>::from_handle(CollectionHandle::new([2; 32]));
        let support: Support<SuccinctArchiveBlob> =
            Support::from_data(target, [CollectionData::new([3; 32])]);
        let cover = Cover::from_data(target, [CollectionData::new([4; 32])]);
        let mut store = MemoryRepo::default();
        let store_snapshot = store.snapshot().unwrap();

        let snapshot = CollectionSnapshot::from_frontier(
            store_snapshot.clone(),
            support.clone(),
            cover.clone(),
            ObservedStore::new(store_snapshot.clone()).tracker(),
        );
        assert!(snapshot.snapshot() == &store_snapshot);
        assert_eq!(snapshot.support().unwrap(), &support);
        assert_eq!(snapshot.cover(), &cover);

        let (actual_store, actual_support, actual_cover) = snapshot.into_parts().unwrap();
        assert!(actual_store == store_snapshot);
        assert_eq!(actual_support, support);
        assert_eq!(actual_cover, cover);
    }
}