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
//! Canonical encodings and mappings for typed collections.
//!
//! Durable collection records carry representation-neutral content hashes.
//! This module restores their physical meaning at the API boundary without
//! inventing a second runtime planner:
//!
//! - a [`CollectionEncoding`] owns the canonical bytes, validation, and join
//!   within one collection;
//! - a [`CollectionDerivation`] lets one target encoding own its canonical,
//!   parameterized, join-preserving conversion from one source encoding;
//! - a [`DeriveMapping`] is an explicit mapping whose images are derived into
//!   a collection of their own, and a [`MapMapping`] (or the target-owned
//!   [`CollectionAttachment`]) indexes another collection's nodes instead,
//!   into an attached collection;
//! - [`Collection`] binds an encoding to one exact, content-addressed
//!   descriptor.
//!
//! Logical interpretation is deliberately separate in
//! [`TryFromCover`](crate::collection::TryFromCover). Maintained-index views
//! retain their mmap-backed shards and check only the framing, bounds and
//! alignment needed to access them safely. Attachment does not re-prove
//! canonical contents, serialize a logical union, or construct an accelerator.
//! Query preparation may derive scratch data the encoding does not persist;
//! that work belongs to the requested query, not to attaching the index.

use std::error::Error;
use std::fmt;
use std::marker::PhantomData;

use crate::blob::encodings::simplearchive::SimpleArchive;
use crate::blob::{Blob, BlobEncoding};
use crate::metadata::{self, MetaDescribe};
use crate::prelude::{exists, pattern};
use crate::repo::{BlobStoreGet, BlobStoreMeta, StoreRead};
use crate::trible::Fragment;

use super::{
    collection_representation, CollectionData, CollectionHandle, KIND_COLLECTION_DESCRIPTOR,
};

/// Failure of one exact canonical collection operation.
///
/// `Capacity` is reserved for deterministic geometry limits of the chosen
/// encoding. It must not describe transient allocation, I/O, or accelerator
/// failures. Malformed or noncanonical bytes are always `Fatal`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CollectionOperationError {
    /// The operation or supplied bytes are invalid and another cover cannot
    /// repair it.
    Fatal(String),
    /// This exact encoding cannot hold the result, but a finer physical cover
    /// may still represent the same logical value.
    Capacity(String),
    /// The canonical result names an immutable dependency which is not present
    /// in the current snapshot. Storage may materialize or fetch it and retry
    /// the otherwise pure operation.
    MissingDependency(CollectionData),
}

impl fmt::Display for CollectionOperationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Fatal(reason) | Self::Capacity(reason) => formatter.write_str(reason),
            Self::MissingDependency(member) => write!(
                formatter,
                "collection operation requires resident blob {}",
                hex::encode_upper(member.raw),
            ),
        }
    }
}

impl Error for CollectionOperationError {}

/// One canonical physical shape carried by a blob encoding.
///
/// Collection members are always ordinary typed [`Blob`] values. An encoding
/// validates its own bytes and owns one canonical intra-shape join. Derived
/// collections are ordinary lattices connected to their source by a
/// join-preserving [`CollectionDerivation`], not a weaker kind of collection.
/// The logical join remains total at the [`Cover`](super::Cover) level: when
/// one physical member cannot represent the result, `Capacity` retains a finer
/// cover of members with the same value.
///
/// This is intentionally stronger than [`BlobEncoding`]: not every blob format
/// is a collection member, while every `CollectionEncoding` has an exact
/// validation boundary.
pub trait CollectionEncoding: BlobEncoding + MetaDescribe + Sized + 'static {
    /// Validate encoding-specific context carried by one descriptor.
    ///
    /// Most encodings need no context. An encoding whose canonical bytes are
    /// parameterized (for example a path summary over one automaton) validates
    /// only the shape information it needs here; the source-to-target mapping
    /// still owns the parameterized conversion itself.
    fn validate_descriptor(_descriptor: &Fragment) -> Result<(), CollectionOperationError> {
        Ok(())
    }

    /// Explicitly validate one member independently of its provenance.
    ///
    /// The root bytes have already passed the blob store's content-address
    /// boundary. A Merkle encoding may inspect children through `reader`; a
    /// monolithic encoding normally ignores it. Warm collection resolution
    /// does not invoke this hook; it is available to producers, untrusted
    /// ingress, and offline audits. It is not part of ordinary typed-view
    /// construction, nor a requirement to check locally produced output again.
    fn validate_member<R>(
        descriptor: &Fragment,
        member: &Blob<Self>,
        reader: &R,
    ) -> Result<(), CollectionOperationError>
    where
        R: BlobStoreGet + BlobStoreMeta;

    /// Return immutable representation dependencies missing from a resident
    /// member root in this snapshot.
    ///
    /// Self-contained encodings need no extra work. Merkle encodings override
    /// this narrow availability query so cover resolution can ignore an
    /// incomplete compacted root and fall back to a finer support-equivalent
    /// cover. Returned handles are only the blobs required to interpret this
    /// representation, not optional attachments or semantic provenance.
    ///
    /// This is not semantic validation: it neither recomputes the member nor
    /// proves its canonical bytes. It may read the named resident root, but
    /// must not request missing dependencies, persist, or otherwise change
    /// storage.
    fn missing_representation_dependencies<R>(
        _member: CollectionData,
        _reader: &R,
    ) -> Result<Vec<CollectionData>, CollectionOperationError>
    where
        R: BlobStoreGet + BlobStoreMeta,
    {
        Ok(Vec::new())
    }

    /// Compute the exact canonical join of two members.
    ///
    /// The implementation owns decoding and rejecting malformed inputs while
    /// it performs this new work; warm resolution never calls this method.
    ///
    /// `reader` resolves immutable content-addressed dependencies named by the
    /// inputs or by their canonical result. Availability may delay publication
    /// but cannot alter the result bytes. Other resident content is not an
    /// input to the join.
    ///
    fn join_members<R>(
        descriptor: &Fragment,
        low: &Blob<Self>,
        high: &Blob<Self>,
        reader: &R,
    ) -> Result<Blob<Self>, CollectionOperationError>
    where
        R: BlobStoreGet + BlobStoreMeta;

    /// Compute the exact canonical join of one or more members: the k-way
    /// join an n-ary MERGE states.
    ///
    /// The default folds [`Self::join_members`] left to right, which is the
    /// same canonical result by associativity; an encoding with a cheaper
    /// k-way join overrides it. The same availability rules apply.
    fn join_many<R>(
        descriptor: &Fragment,
        members: &[Blob<Self>],
        reader: &R,
    ) -> Result<Blob<Self>, CollectionOperationError>
    where
        R: BlobStoreGet + BlobStoreMeta,
    {
        let (first, rest) = members.split_first().ok_or_else(|| {
            CollectionOperationError::Fatal("a join needs at least one member".to_owned())
        })?;
        let mut joined = first.clone();
        for member in rest {
            joined = Self::join_members(descriptor, &joined, member, reader)?;
        }
        Ok(joined)
    }
}

/// The canonical incoming derivation owned by one target encoding.
///
/// The target names its one source encoding and the runtime argument carried
/// by the mapping fragment embedded in its descriptor. Canonical builders
/// normally derive the mapping entity id, but binding validates its algorithm
/// and argument rather than its minting history. Implementations must be a
/// join homomorphism:
///
/// `map(a join b) = map(a) join map(b)`.
pub trait CollectionDerivation: CollectionEncoding {
    /// Canonical source encoding.
    type Source: CollectionEncoding;

    /// Runtime argument which distinguishes concrete mappings of this
    /// canonical source-to-target relation.
    type Argument;

    /// Canonical concrete mapping fragment embedded in a target descriptor.
    ///
    /// Parameterized derivations carry their argument in this fragment;
    /// parameter-free derivations use `()`.
    fn fragment(argument: &Self::Argument) -> Fragment;

    /// Bind and validate the concrete mapping named by the target descriptor.
    fn bind(
        source: &Fragment,
        target: &Fragment,
    ) -> Result<Self::Argument, CollectionOperationError>;

    /// Compute the canonical target image of one source member.
    ///
    /// `reader` is the same frozen store observation from which the
    /// source was loaded. The mapping owns decoding and rejecting malformed
    /// input while it performs new work. It may use `reader` only to resolve
    /// dependencies named by `source` or its concrete argument. An explicit
    /// collection reference is resolved using this observation's records and
    /// capability evidence; unrelated store contents are not semantic input.
    fn map<R>(
        argument: &Self::Argument,
        source: &Blob<Self::Source>,
        reader: &R,
    ) -> Result<Blob<Self>, CollectionOperationError>
    where
        R: StoreRead;

    /// Join target images: the k-way join a MERGE of the derived collection
    /// states. See [`DeriveMapping::join_images`].
    fn join_images<R>(
        _argument: &Self::Argument,
        target_descriptor: &Fragment,
        images: &[Blob<Self>],
        reader: &R,
    ) -> Result<Blob<Self>, CollectionOperationError>
    where
        R: BlobStoreGet + BlobStoreMeta,
    {
        Self::join_many(target_descriptor, images, reader)
    }
}

/// One explicit parameterized mapping between collection encodings, whose
/// images are derived into a collection of their own.
///
/// Its images are published as `DERIVE` leaves of the derived collection and
/// replicate with it. Only a mapping not every reader of a node can compute
/// is derived; an index that every reader of a node can compute for itself
/// is a [`MapMapping`] instead. The contract an implementor takes on:
///
/// - It maps foundations only: a commit payload of a root source, or a leaf
///   image of a derived one. It never maps a merge result: the derived
///   collection carries its own leaf images into a lattice of its own, joined
///   with [`Self::join_images`], and never reads its source's merges.
/// - The target encoding's join is total: any two members that are each
///   valid join, so every set of leaves has a join, whoever derived them.
///   Several leaves may name one source foundation -- two derivations that
///   disagree, or a re-derivation -- and the join keeps what each says. A
///   join that cannot be represented in one member is `Capacity`, which
///   leaves the finer cover standing; it is never `Fatal` for valid members.
/// - A deterministic mapping is a join homomorphism into that join,
///   `map(a join b) = map(a) join map(b)`, so the join of a collection's
///   leaves is the image of everything the source's foundations hold. A
///   mapping may also be non-deterministic -- an embedding that does not
///   reproduce bit for bit -- and then the join of its leaves holds what
///   each derivation observed.
/// - It may be pinned to a class of host ([`Self::computable_here`]): a model
///   whose output is canonical on one accelerator class only. Another host
///   derives nothing through it and still carries the collection; its leaves
///   arrive by replication.
///
/// Derivation is scheduled per source foundation by one rule, which every
/// mapping in this crate follows: any admitted leaf suffices. Maintenance
/// derives a foundation only when no believed leaf for its locator has an
/// output that is here or can be fetched, whoever signed that leaf, and any
/// key the derived collection admits may derive it on a host that can
/// compute the mapping, not only the foundation's owner. A leaf whose output
/// cannot be obtained does not count; whether it can is asked only of a
/// store that reaches other holders, and a store that cannot waits for the
/// output instead. A fetch that fails says the output is
/// not available now, not that it is lost: an original output that arrives
/// after its foundation was derived again stands beside the newer leaf,
/// both are joined, and nothing further is derived. A leaf known to be bad
/// is supplemented only on request
/// ([`CollectionStoreExt::rederive_with`](super::CollectionStoreExt::rederive_with)),
/// which adds a second leaf and never replaces one.
///
/// This is the coherence-safe extension point for mappings whose source and
/// target encodings are both owned elsewhere. Prefer [`CollectionDerivation`]
/// when a target encoding owns one canonical incoming derivation; explicit
/// mappings are selected through the `*_with` collection-store methods.
pub trait DeriveMapping: Sized {
    /// Canonical source encoding.
    type Source: CollectionEncoding;
    /// Canonical target encoding.
    type Target: CollectionEncoding;

    /// Canonical concrete mapping fragment embedded in a target descriptor.
    fn fragment(&self) -> Fragment;

    /// Bind and validate the concrete mapping named by the target descriptor.
    fn bind(source: &Fragment, target: &Fragment) -> Result<Self, CollectionOperationError>;

    /// Compute the canonical target image of one source member.
    ///
    /// The reader freezes the source and any explicitly named dependencies
    /// together, including collection records and authorization. A mapping may
    /// resolve references carried by its descriptor or input, but must not
    /// discover ambient inputs or advance the control-plane observation.
    fn map<R>(
        &self,
        source: &Blob<Self::Source>,
        reader: &R,
    ) -> Result<Blob<Self::Target>, CollectionOperationError>
    where
        R: StoreRead;

    /// Whether this host can compute the mapping: the class-pin hook.
    ///
    /// A mapping pinned to a class of host -- a model whose output is
    /// canonical on one accelerator class, say -- answers `false` on every
    /// other host. There maintenance derives nothing through it, raises no
    /// error for it, and still carries the derived collection: its leaves
    /// arrive by replication and are joined like any others. The default,
    /// `true`, is every host.
    fn computable_here(&self) -> bool {
        true
    }

    /// Join target images: the k-way join one MERGE of the derived
    /// collection states, which is how a derived collection carries its own
    /// lattice.
    ///
    /// The result must be the encoding's canonical join
    /// ([`CollectionEncoding::join_many`], the default), without constructing
    /// upstream members or changing storage; a mapping may compute it through
    /// its own backend. `Capacity` and `MissingDependency` leave the finer
    /// cover standing.
    fn join_images<R>(
        &self,
        target_descriptor: &Fragment,
        images: &[Blob<Self::Target>],
        reader: &R,
    ) -> Result<Blob<Self::Target>, CollectionOperationError>
    where
        R: BlobStoreGet + BlobStoreMeta,
    {
        Self::Target::join_many(target_descriptor, images, reader)
    }
}

/// Internal adapter from a target-owned derivation to the explicit mapping
/// engine. Keeping this wrapper private leaves downstream coherence open.
pub(crate) struct CanonicalDerivation<T: CollectionDerivation> {
    argument: T::Argument,
}

impl<T: CollectionDerivation> CanonicalDerivation<T> {
    pub(crate) fn new(argument: T::Argument) -> Self {
        Self { argument }
    }
}

impl<T: CollectionDerivation> DeriveMapping for CanonicalDerivation<T> {
    type Source = T::Source;
    type Target = T;

    fn fragment(&self) -> Fragment {
        T::fragment(&self.argument)
    }

    fn bind(source: &Fragment, target: &Fragment) -> Result<Self, CollectionOperationError> {
        T::bind(source, target).map(Self::new)
    }

    fn map<R>(
        &self,
        source: &Blob<Self::Source>,
        reader: &R,
    ) -> Result<Blob<Self::Target>, CollectionOperationError>
    where
        R: StoreRead,
    {
        T::map(&self.argument, source, reader)
    }

    fn join_images<R>(
        &self,
        target_descriptor: &Fragment,
        images: &[Blob<Self::Target>],
        reader: &R,
    ) -> Result<Blob<Self::Target>, CollectionOperationError>
    where
        R: BlobStoreGet + BlobStoreMeta,
    {
        T::join_images(&self.argument, target_descriptor, images, reader)
    }
}

/// A mapping attached to another collection's nodes: an index of each node,
/// not a collection of its own.
///
/// An attached collection's descriptor names its parent collection and one
/// concrete mapping, and no policy: its records are `MAP(node ->
/// attachment)` signed by the host, which no other host believes: one that
/// reaches another store stays inert there. The contract an implementor
/// takes on:
///
/// - It maps any node of its parent's lattice, a merge result as well as a
///   foundation. The parent is a root collection: its nodes are
///   `SimpleArchive`s.
/// - It is deterministic. Its inputs are the node, immutable dependencies the
///   node or the mapping names, and optionally the attachments of the same
///   node in other attached collections of the same parent, named by
///   [`Self::siblings`]. A dependency that is not resident is reported as
///   [`CollectionOperationError::MissingDependency`], never read as absent.
/// - Every host that can read the node can compute it: it is not pinned to a
///   model, an accelerator class or any other property of a host. A mapping
///   that is pinned cannot implement this trait, so it cannot be attached by
///   mistake; it stays a [`DeriveMapping`].
/// - Its images need no join. `Capacity` means this node's attachment cannot
///   be represented; a reader then descends to finer nodes.
///
/// Its law is cover-query equivalence. A reader answers a query over a cover
/// of attachments at mixed granularity -- one node's image beside the images
/// of finer nodes, possibly overlapping -- and the answer must equal the
/// query over the image of the union the cover stands for:
///
/// `view(cover { map(a_1), ..., map(a_n) }) = view(map(a_1 join ... join a_n))`.
///
/// Because the `a_i` may overlap, a view combines its per-node answers
/// idempotently: a last-writer-wins register pairs partial rows across the
/// cover, a text index takes each entity's maximum score, and a count or any
/// other non-idempotent aggregate is never summed over overlapping supports.
/// Every implementor is tested against this law over random covers.
///
/// The law holds for every cover when an image is built from single facts,
/// as every implementor in this crate's is. A mapping whose image aggregates
/// facts of several entities cannot tell from one node that an entity has
/// more facts elsewhere, and then no combination of per-node images is
/// exact once a cover splits that entity; nothing refuses such a node, so
/// the answer can be wrong with an empty residual and nothing unread. For
/// such a mapping the law is a premise about its input, which the
/// implementor states. The one known is the Archive block BM25 mapping in
/// faculties (`ArchiveBlockTextBm25Mapping`), whose document is a block and
/// whose term frequency sums over the block's parts: it answers like the
/// union for every cover whose nodes hold whole source units (a block with
/// all its parts and their facts); a node holding part of a block scores
/// that block from the part it holds, with no refusal and no residual to
/// show it, so a cover that splits a block undercounts it. Faculties' own
/// Archive importer commits whole source units, and a test there pins it:
/// that is the premise for data it writes, not for another writer's commits
/// or historical input, and the writer keeps the fragments it is given
/// whole without checking that they hold whole blocks. The ignored
/// faculties tests `a_block_whose_parts_sit_in_two_nodes_scores_like_their_union`,
/// `a_block_extended_by_a_node_without_its_tag_scores_like_their_union` and
/// `archive_block_covers_answer_like_the_union_when_parts_spread_over_nodes`
/// are the acceptance tests of the structural fix: a per-fact text index
/// over the content fact's payload, with blocks ranked at query time.
pub trait MapMapping: Sized {
    /// Encoding of the attachments.
    type Target: CollectionEncoding;

    /// Canonical concrete mapping fragment embedded in an attached
    /// descriptor.
    fn fragment(&self) -> Fragment;

    /// Bind and validate the concrete mapping an attached descriptor names.
    fn bind(parent: &Fragment, attached: &Fragment) -> Result<Self, CollectionOperationError>;

    /// The attached collections of the same parent whose attachment of a
    /// node this mapping reads, in the order [`Self::map`] receives them.
    /// Their handles are named by the mapping's own descriptor, never
    /// recomputed.
    fn siblings(&self) -> Vec<CollectionHandle> {
        Vec::new()
    }

    /// Compute the attachment of one node.
    ///
    /// `siblings` holds one usable attachment of this node in each collection
    /// [`Self::siblings`] names. `reader` resolves immutable dependencies
    /// named by the node, the siblings or the mapping; nothing else in the
    /// store is an input.
    fn map<R>(
        &self,
        node: &Blob<SimpleArchive>,
        siblings: &[CollectionData],
        reader: &R,
    ) -> Result<Blob<Self::Target>, CollectionOperationError>
    where
        R: StoreRead;
}

/// The canonical attachment owned by one target encoding: the
/// [`MapMapping`] counterpart of [`CollectionDerivation`], with the same
/// contract and law.
///
/// The target names the runtime argument its mapping fragment carries;
/// attaching it is [`crate::collection::CollectionStoreExt::attach`].
pub trait CollectionAttachment: CollectionEncoding {
    /// Runtime argument which distinguishes concrete mappings of this
    /// canonical relation.
    type Argument;

    /// Canonical concrete mapping fragment embedded in an attached
    /// descriptor.
    fn fragment(argument: &Self::Argument) -> Fragment;

    /// Bind and validate the concrete mapping an attached descriptor names.
    fn bind(
        parent: &Fragment,
        attached: &Fragment,
    ) -> Result<Self::Argument, CollectionOperationError>;

    /// See [`MapMapping::siblings`].
    fn siblings(_argument: &Self::Argument) -> Vec<CollectionHandle> {
        Vec::new()
    }

    /// See [`MapMapping::map`].
    fn map<R>(
        argument: &Self::Argument,
        node: &Blob<SimpleArchive>,
        siblings: &[CollectionData],
        reader: &R,
    ) -> Result<Blob<Self>, CollectionOperationError>
    where
        R: StoreRead;
}

/// Internal adapter from a target-owned attachment to the explicit mapping
/// engine, the counterpart of [`CanonicalDerivation`].
pub(crate) struct CanonicalAttachment<T: CollectionAttachment> {
    argument: T::Argument,
}

impl<T: CollectionAttachment> CanonicalAttachment<T> {
    pub(crate) fn new(argument: T::Argument) -> Self {
        Self { argument }
    }
}

impl<T: CollectionAttachment> MapMapping for CanonicalAttachment<T> {
    type Target = T;

    fn fragment(&self) -> Fragment {
        T::fragment(&self.argument)
    }

    fn bind(parent: &Fragment, attached: &Fragment) -> Result<Self, CollectionOperationError> {
        T::bind(parent, attached).map(Self::new)
    }

    fn siblings(&self) -> Vec<CollectionHandle> {
        T::siblings(&self.argument)
    }

    fn map<R>(
        &self,
        node: &Blob<SimpleArchive>,
        siblings: &[CollectionData],
        reader: &R,
    ) -> Result<Blob<Self::Target>, CollectionOperationError>
    where
        R: StoreRead,
    {
        T::map(&self.argument, node, siblings, reader)
    }
}

/// A descriptor does not denote the encoding requested by its Rust type.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CollectionTypeError {
    /// No tagged descriptor entity names the requested encoding.
    WrongEncoding {
        /// Encoding required by the Rust type.
        expected: crate::id::Id,
    },
    /// The descriptor names the right encoding but supplies invalid context.
    InvalidDescriptor(CollectionOperationError),
}

impl fmt::Display for CollectionTypeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::WrongEncoding { expected } => write!(
                formatter,
                "no collection descriptor names encoding {expected:X}",
            ),
            Self::InvalidDescriptor(source) => {
                write!(formatter, "invalid collection encoding context: {source}")
            }
        }
    }
}

impl Error for CollectionTypeError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::InvalidDescriptor(source) => Some(source),
            Self::WrongEncoding { .. } => None,
        }
    }
}

/// Recognize the descriptor facts needed to interpret members as `E`.
///
/// A matching encoding fact is sufficient; other representations, annotations,
/// and legacy fields do not invalidate it. Policy and lineage are separate
/// queries at their respective consumers, not encoding prerequisites.
pub(crate) fn validate_descriptor_type<E>(
    descriptor_fragment: &Fragment,
) -> Result<(), CollectionTypeError>
where
    E: CollectionEncoding,
{
    let expected = E::id();
    if !exists!(pattern!(descriptor_fragment.facts(), [{ _?descriptor @
        metadata::tag: KIND_COLLECTION_DESCRIPTOR,
        collection_representation: expected,
    }])) {
        return Err(CollectionTypeError::WrongEncoding { expected });
    }
    E::validate_descriptor(descriptor_fragment).map_err(CollectionTypeError::InvalidDescriptor)
}

/// One exact collection descriptor, typed by its canonical member encoding.
///
/// The store owns the descriptor bytes. This is only its cheap, cloneable
/// content address plus compile-time meaning; constructing it is restricted to
/// descriptor-validation boundaries.
pub struct Collection<E: CollectionEncoding> {
    handle: CollectionHandle,
    encoding: PhantomData<fn() -> E>,
}

impl<E: CollectionEncoding> Collection<E> {
    pub(crate) const fn from_handle(handle: CollectionHandle) -> Self {
        Self {
            handle,
            encoding: PhantomData,
        }
    }

    /// Representation-neutral descriptor handle stored in dense records.
    pub const fn handle(self) -> CollectionHandle {
        self.handle
    }
}

impl<E: CollectionEncoding> Clone for Collection<E> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<E: CollectionEncoding> Copy for Collection<E> {}

impl<E: CollectionEncoding> fmt::Debug for Collection<E> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("Collection")
            .field(&hex::encode_upper(self.handle.raw))
            .finish()
    }
}

impl<E: CollectionEncoding> PartialEq for Collection<E> {
    fn eq(&self, other: &Self) -> bool {
        self.handle == other.handle
    }
}

impl<E: CollectionEncoding> Eq for Collection<E> {}

impl<E: CollectionEncoding> PartialOrd for Collection<E> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<E: CollectionEncoding> Ord for Collection<E> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.handle.cmp(&other.handle)
    }
}

impl<E: CollectionEncoding> std::hash::Hash for Collection<E> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.handle.hash(state);
    }
}

impl<E: CollectionEncoding> From<Collection<E>> for CollectionHandle {
    fn from(collection: Collection<E>) -> Self {
        collection.handle
    }
}