bunsen 0.38.0

bunsen is a batteries included common library for burn
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
//! Shard-set descriptors: what a shard set is.

use std::{
    collections::BTreeSet,
    fmt,
};

use burn::tensor::Slice;
use serde::{
    Deserialize,
    Serialize,
};

use crate::{
    data::pretrained::{
        Resource,
        ResourceMap,
        Source,
    },
    errors::{
        BunsenError,
        BunsenResult,
        ConstraintError,
        LookupError,
        ResultContext,
        Rule,
    },
};

/// The placeholder a shard template carries for the zero-padded index.
pub const INDEX_PLACEHOLDER: &str = "{index}";

/// A shard's number within its set: `0..count`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ShardId(pub usize);

impl From<usize> for ShardId {
    fn from(index: usize) -> Self {
        Self(index)
    }
}

impl fmt::Display for ShardId {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// How a set's shards are pinned, as a compiled-in table spells it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StaticShardDigests<'a> {
    /// No digests: a shard is trusted on its length.
    #[default]
    Unpinned,

    /// One lowercase hex SHA-256 per shard, index-ordered.
    Table(&'a [&'a str]),
}

impl StaticShardDigests<'_> {
    /// The owned twin.
    pub fn to_digests(&self) -> ShardDigests {
        match self {
            Self::Unpinned => ShardDigests::Unpinned,
            Self::Table(table) => {
                ShardDigests::Table(table.iter().map(|s| s.to_string()).collect())
            }
        }
    }
}

/// How a set's shards are pinned.
///
/// [`Unpinned`](Self::Unpinned): a fetched shard is checked against its
/// `Content-Length` alone. [`Table`](Self::Table): one SHA-256 per shard,
/// which the fetch verifies as the bytes land. A listing fetched from the
/// source is the planned addition, which is why this is `#[non_exhaustive]`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ShardDigests {
    /// No digests: a shard is trusted on its length.
    #[default]
    Unpinned,

    /// One lowercase hex SHA-256 per shard, index-ordered.
    Table(Vec<String>),
}

/// A shard set, as a compiled-in table spells it.
///
/// [`to_descriptor`](Self::to_descriptor) gives the owned twin,
/// [`ShardSetDescriptor`], which is where the behavior lives.
#[derive(Debug)]
pub struct StaticShardSetDescriptor<'a> {
    /// The set's name, unique within its map.
    pub name: &'a str,

    /// What the set is.
    pub description: &'a str,

    /// The data's license.
    pub license: Option<&'a str>,

    /// Where the set is published.
    pub origin: Option<&'a str>,

    /// Base URLs the shard file name is appended to: mirrors, tried in order.
    pub base_urls: &'a [&'a str],

    /// The shard file name, with [`INDEX_PLACEHOLDER`] where the index goes.
    pub template: &'a str,

    /// The zero-padded width of the index in a file name.
    pub index_width: usize,

    /// How many shards there are: ids are `0..count`.
    pub count: usize,

    /// The shards' format, as a label (`"parquet"`).
    pub format: &'a str,

    /// How the shards are pinned.
    pub digests: StaticShardDigests<'a>,
}

impl StaticShardSetDescriptor<'_> {
    /// The owned twin.
    pub fn to_descriptor(&self) -> ShardSetDescriptor {
        ShardSetDescriptor {
            name: self.name.to_string(),
            description: self.description.to_string(),
            license: self.license.map(str::to_string),
            origin: self.origin.map(str::to_string),
            base_urls: self.base_urls.iter().map(|s| s.to_string()).collect(),
            template: self.template.to_string(),
            index_width: self.index_width,
            count: self.count,
            format: self.format.to_string(),
            digests: self.digests.to_digests(),
        }
    }
}

impl From<&StaticShardSetDescriptor<'_>> for ShardSetDescriptor {
    fn from(descriptor: &StaticShardSetDescriptor<'_>) -> Self {
        descriptor.to_descriptor()
    }
}

/// A shard set: what it is, and how its shards are named and reached.
///
/// Its name, where its shards come from, how they are named and numbered,
/// and whether they are pinned. Built from a [`StaticShardSetDescriptor`]
/// (usually a [`StaticShardSetMap`](super::StaticShardSetMap) lookup),
/// deserialized, or assembled at runtime; [`validate`](Self::validate)
/// checks a hand-built one. [`select`](Self::select) turns slices into
/// shard ids. A [`ShardSet`](super::ShardSet) binds the descriptor to a
/// directory and brings its shards in, and
/// [`to_resource_map`](Self::to_resource_map) makes a selection of shards a
/// [`ResourceMap`], for a pretrained row that fuses a shard set in.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShardSetDescriptor {
    /// The set's name, unique within its map.
    pub name: String,

    /// What the set is.
    pub description: String,

    /// The data's license.
    pub license: Option<String>,

    /// Where the set is published.
    pub origin: Option<String>,

    /// Base URLs the shard file name is appended to: mirrors, tried in order.
    pub base_urls: Vec<String>,

    /// The shard file name, with [`INDEX_PLACEHOLDER`] where the index goes.
    pub template: String,

    /// The zero-padded width of the index in a file name.
    pub index_width: usize,

    /// How many shards there are: ids are `0..count`.
    pub count: usize,

    /// The shards' format, as a label (`"parquet"`).
    pub format: String,

    /// How the shards are pinned.
    pub digests: ShardDigests,
}

impl ShardSetDescriptor {
    /// Checks the descriptor hangs together: a template with exactly one
    /// [`INDEX_PLACEHOLDER`], at least one base URL, at least one shard.
    ///
    /// # Errors
    /// [`Illegal`](crate::errors::BunsenErrorKind::Illegal) naming the first
    /// problem, under a frame naming the set; a
    /// [`ConstraintError`] cause for an empty `base_urls`, a zero `count`, or
    /// a digest table whose length is not `count`. A descriptor read from
    /// outside the program is the reader's to re-mark
    /// [`as_policy`](crate::errors::ResultContext::as_policy).
    pub fn validate(&self) -> BunsenResult<()> {
        self.validate_fields().context(&self.name)
    }

    /// [`validate`](Self::validate), without the frame.
    fn validate_fields(&self) -> BunsenResult<()> {
        const OWNER: &str = "ShardSetDescriptor";
        let placeholders = self.template.matches(INDEX_PLACEHOLDER).count();
        if placeholders != 1 {
            return Err(BunsenError::illegal(format!(
                "template {:?} must contain {INDEX_PLACEHOLDER} exactly once, not {placeholders} times",
                self.template
            )));
        }
        if self.base_urls.is_empty() {
            return Err(ConstraintError::zero_or_empty(OWNER, "base_urls").into());
        }
        if self.count == 0 {
            return Err(ConstraintError::zero_or_empty(OWNER, "count").into());
        }
        if let ShardDigests::Table(table) = &self.digests {
            if table.len() != self.count {
                return Err(ConstraintError::new(
                    OWNER,
                    "digests",
                    Rule::Relation {
                        lhs: ("digests.len()".to_string(), table.len().to_string()),
                        op: "==",
                        rhs: ("count".to_string(), self.count.to_string()),
                    },
                )
                .into());
            }
            let is_hex = |d: &str| {
                d.len() == 64 && d.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
            };
            if let Some((i, bad)) = table.iter().enumerate().find(|(_, d)| !is_hex(d)) {
                return Err(BunsenError::illegal(format!(
                    "shard {i}'s digest {bad:?} is not 64 lowercase hex digits"
                )));
            }
        }
        Ok(())
    }

    /// `true` when fetched shards are checked against a digest.
    pub fn is_pinned(&self) -> bool {
        !matches!(self.digests, ShardDigests::Unpinned)
    }

    /// Every id, in order.
    pub fn ids(&self) -> impl Iterator<Item = ShardId> {
        (0..self.count).map(ShardId)
    }

    /// `true` when `id` is within the set.
    pub fn contains(
        &self,
        id: ShardId,
    ) -> bool {
        id.0 < self.count
    }

    /// The file name of shard `id`: the template with the zero-padded index.
    pub fn file_name(
        &self,
        id: ShardId,
    ) -> String {
        let index = format!("{:0width$}", id.0, width = self.index_width);
        self.template.replace(INDEX_PLACEHOLDER, &index)
    }

    /// The id a file name spells, when it is one of this set's.
    pub fn parse_file_name(
        &self,
        file_name: &str,
    ) -> Option<ShardId> {
        let (prefix, suffix) = self.template.split_once(INDEX_PLACEHOLDER)?;
        let digits = file_name.strip_prefix(prefix)?.strip_suffix(suffix)?;
        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
            return None;
        }
        let index: usize = digits.parse().ok()?;
        (index < self.count).then_some(ShardId(index))
    }

    /// Where shard `id` can be fetched from: one URL per base URL, in order.
    pub fn urls(
        &self,
        id: ShardId,
    ) -> Vec<String> {
        let file_name = self.file_name(id);
        self.base_urls
            .iter()
            .map(|base| format!("{}/{file_name}", base.trim_end_matches('/')))
            .collect()
    }

    /// The lowercase hex SHA-256 shard `id` must have, when the set is pinned.
    pub fn digest(
        &self,
        id: ShardId,
    ) -> Option<&str> {
        match &self.digests {
            ShardDigests::Unpinned => None,
            ShardDigests::Table(table) => table.get(id.0).map(String::as_str),
        }
    }

    /// The shards `ids` name as a resource map: one resource per shard,
    /// keyed by its file name, pinned by the table when the set is, labeled
    /// by the set's format, under the set's name as its namespace, and
    /// reachable from every base URL in order. What a pretrained row fuses a
    /// shard set in as, and what the pretrained cache's `load` brings in
    /// together.
    ///
    /// # Errors
    /// [`Lookup`](crate::errors::BunsenErrorKind::Lookup), with a
    /// [`LookupError`] cause, for an id outside the set.
    pub fn to_resource_map(
        &self,
        ids: &[ShardId],
    ) -> BunsenResult<ResourceMap> {
        let mut map = ResourceMap::new(&self.name);
        map.description = self.description.clone();
        map.license = self.license.clone();
        map.origin = self.origin.clone();
        for &id in ids {
            if !self.contains(id) {
                return Err(BunsenError::lookup(LookupError::out_of_range(
                    "shard", id, self.count,
                ))
                .context(&self.name));
            }
            let file = self.file_name(id);
            map.insert(Resource {
                key: file.clone(),
                file,
                sha256: self.digest(id).map(str::to_string),
                kind: Some(self.format.clone()),
                namespace: self.name.clone(),
                sources: self.urls(id).into_iter().map(Source::Url).collect(),
            });
        }
        Ok(map)
    }

    /// The ids `slices` name, sorted and without repeats.
    ///
    /// Each slice is resolved against [`count`](Self::count): a negative
    /// bound counts from the end, an open end is the end. Steps must be
    /// positive.
    ///
    /// # Errors
    /// [`Illegal`](crate::errors::BunsenErrorKind::Illegal), under a frame
    /// naming the set: with a [`ConstraintError`] cause for a bound outside
    /// `-count..=count`, or for a reversed slice.
    pub fn select(
        &self,
        slices: &[Slice],
    ) -> BunsenResult<Vec<ShardId>> {
        let count = self.count;
        let resolve = |bound: isize| -> BunsenResult<usize> {
            let resolved = if bound < 0 {
                count as isize + bound
            } else {
                bound
            };
            if resolved < 0 || resolved > count as isize {
                return Err(BunsenError::from(ConstraintError::out_of_range(
                    "ShardSetDescriptor::select",
                    "slices",
                    format!("shard index {bound}"),
                    format!("-{count}..={count}"),
                ))
                .context(&self.name));
            }
            Ok(resolved as usize)
        };

        let mut ids = BTreeSet::new();
        for slice in slices {
            if slice.is_reversed() {
                return Err(BunsenError::illegal(format!(
                    "shard slice {slice} is reversed; shards are selected in order"
                ))
                .context(&self.name));
            }
            let start = resolve(slice.start)?;
            let end = match slice.end {
                Some(end) => resolve(end)?,
                None => count,
            };
            let step = slice.step().unsigned_abs().max(1);
            ids.extend((start..end).step_by(step).map(ShardId));
        }
        Ok(ids.into_iter().collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors::{
        BunsenErrorKind,
        LookupProblem,
        testing::{
            ErrorMatcher,
            predicate,
        },
    };

    pub(crate) fn tiny() -> StaticShardSetDescriptor<'static> {
        StaticShardSetDescriptor {
            name: "tiny",
            description: "a tiny set",
            license: Some("CC0"),
            origin: Some("https://example.invalid/tiny"),
            base_urls: &["https://a.example/tiny/", "https://b.example/mirror"],
            template: "shard_{index}.bin",
            index_width: 3,
            count: 12,
            format: "bin",
            digests: StaticShardDigests::Unpinned,
        }
    }

    /// Twelve digests for `tiny`, all the same and all well formed.
    static TINY_SHA256: [&str; 12] =
        ["ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; 12];

    fn tiny_pinned() -> StaticShardSetDescriptor<'static> {
        StaticShardSetDescriptor {
            digests: StaticShardDigests::Table(&TINY_SHA256),
            ..tiny()
        }
    }

    /// A table pins every shard: it converts, validates, serializes, and
    /// answers `digest` by index; a short or malformed table is refused.
    #[test]
    fn test_table_digests() {
        let d = tiny_pinned().to_descriptor();
        assert!(d.is_pinned());
        assert!(!tiny().to_descriptor().is_pinned());
        assert_eq!(
            d.digests,
            ShardDigests::Table(vec![TINY_SHA256[0].to_string(); 12])
        );
        assert_eq!(d.digest(ShardId(0)), Some(TINY_SHA256[0]));
        assert_eq!(d.digest(ShardId(11)), Some(TINY_SHA256[11]));
        assert_eq!(d.digest(ShardId(12)), None);
        d.validate().unwrap();
        let json = serde_json::to_string(&d).unwrap();
        assert_eq!(
            serde_json::from_str::<ShardSetDescriptor>(&json).unwrap(),
            d
        );

        let mut short = d.clone();
        short.digests = ShardDigests::Table(vec![TINY_SHA256[0].to_string(); 11]);
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .display_contains(
                "tiny: ShardSetDescriptor.digests: digests.len() (11) must be == count (12)",
            )
            .cause(predicate("the digests field", |c: &ConstraintError| {
                c.field == "digests"
            }))
            .assert_err(&short.validate());

        let mut bad = d.clone();
        let mut table = vec![TINY_SHA256[0].to_string(); 12];
        table[3] = TINY_SHA256[0].to_uppercase();
        bad.digests = ShardDigests::Table(table);
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("shard 3's digest")
            .frame_contains("tiny")
            .assert_err(&bad.validate());
    }

    #[test]
    fn test_static_to_owned_round_trip() {
        let s = tiny();
        let d = s.to_descriptor();
        assert_eq!(d.name, "tiny");
        assert_eq!(d.license.as_deref(), Some("CC0"));
        assert_eq!(d.base_urls.len(), 2);
        assert_eq!(d.template, "shard_{index}.bin");
        assert_eq!((d.index_width, d.count), (3, 12));
        assert_eq!(d.digests, ShardDigests::Unpinned);
        assert_eq!(ShardSetDescriptor::from(&s), d);
        d.validate().unwrap();

        let json = serde_json::to_string(&d).unwrap();
        assert_eq!(
            serde_json::from_str::<ShardSetDescriptor>(&json).unwrap(),
            d
        );
    }

    #[test]
    fn test_validate_names_the_problem() {
        let mut d = tiny().to_descriptor();
        d.template = "shard.bin".to_string();
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("exactly once")
            .assert_err(&d.validate());
        d.template = "{index}-{index}".to_string();
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("not 2 times")
            .assert_err(&d.validate());

        let zero_or_empty = |field: &'static str| {
            ErrorMatcher::kind(BunsenErrorKind::Illegal)
                .frame_contains("tiny")
                .cause(predicate(field, move |c: &ConstraintError| {
                    c.field == field && c.rule == Rule::ZeroOrEmpty
                }))
        };

        let mut d = tiny().to_descriptor();
        d.base_urls.clear();
        zero_or_empty("base_urls").assert_err(&d.validate());

        let mut d = tiny().to_descriptor();
        d.count = 0;
        zero_or_empty("count").assert_err(&d.validate());
    }

    #[test]
    fn test_names_and_urls() {
        let d = tiny().to_descriptor();
        assert_eq!(d.file_name(ShardId(0)), "shard_000.bin");
        assert_eq!(d.file_name(ShardId(11)), "shard_011.bin");
        assert_eq!(
            d.urls(ShardId(7)),
            vec![
                "https://a.example/tiny/shard_007.bin",
                "https://b.example/mirror/shard_007.bin",
            ]
        );
        assert_eq!(d.digest(ShardId(7)), None);
        assert_eq!(ShardId(7).to_string(), "7");
        assert_eq!(ShardId::from(3), ShardId(3));

        assert_eq!(d.parse_file_name("shard_007.bin"), Some(ShardId(7)));
        assert_eq!(d.parse_file_name("shard_7.bin"), Some(ShardId(7)));
        assert_eq!(d.parse_file_name("shard_012.bin"), None, "past count");
        assert_eq!(d.parse_file_name("shard_.bin"), None);
        assert_eq!(d.parse_file_name("shard_0x7.bin"), None);
        assert_eq!(d.parse_file_name("other_007.bin"), None);
        assert_eq!(d.parse_file_name("shard_007.bin.partial"), None);

        assert!(d.contains(ShardId(11)));
        assert!(!d.contains(ShardId(12)));
        assert_eq!(d.ids().count(), 12);
        assert_eq!(d.ids().last(), Some(ShardId(11)));
    }

    #[test]
    fn test_select_resolves_slices_in_order_without_repeats() {
        let d = tiny().to_descriptor();
        let ids = |v: &[usize]| v.iter().copied().map(ShardId).collect::<Vec<_>>();

        assert_eq!(d.select(&[]).unwrap(), ids(&[]));
        assert_eq!(d.select(&[Slice::index(3)]).unwrap(), ids(&[3]));
        assert_eq!(
            d.select(&[Slice::from(..3), Slice::index(1)]).unwrap(),
            ids(&[0, 1, 2])
        );
        assert_eq!(d.select(&[Slice::from(9..)]).unwrap(), ids(&[9, 10, 11]));
        assert_eq!(d.select(&[Slice::from(-2..)]).unwrap(), ids(&[10, 11]));
        assert_eq!(
            d.select(&[Slice::from_range_stepped(0..12, 5)]).unwrap(),
            ids(&[0, 5, 10])
        );
        assert_eq!(d.select(&[Slice::from(..)]).unwrap().len(), 12);
        assert_eq!(
            d.select(&[Slice::from(12..)]).unwrap(),
            ids(&[]),
            "empty at the end"
        );

        let out_of_range = ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .frame_contains("tiny")
            .has_cause::<ConstraintError>();
        out_of_range
            .message_contains("shard index 13 is outside -12..=12")
            .assert_err(&d.select(&[Slice::from(..13)]));
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("shard index -13 is outside -12..=12")
            .assert_err(&d.select(&[Slice::from(-13..)]));
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("is reversed")
            .assert_err(&d.select(&[Slice::with_step(5, Some(0), -1)]));
    }

    /// The shards a slice names, as a map: keyed by file name, pinned when
    /// the set is, labeled by the format, one URL per base in order.
    #[test]
    fn test_to_resource_map() {
        let d = tiny_pinned().to_descriptor();
        let ids = d.select(&[Slice::from(..2)]).unwrap();
        let map = d.to_resource_map(&ids).unwrap();
        assert_eq!(map.name, "tiny");
        assert_eq!(map.description, "a tiny set");
        assert_eq!(map.license.as_deref(), Some("CC0"));
        assert_eq!(map.keys(), ["shard_000.bin", "shard_001.bin"]);
        let r = map.get("shard_001.bin").unwrap();
        assert_eq!(r.file, "shard_001.bin");
        assert_eq!(r.sha256.as_deref(), Some(TINY_SHA256[1]));
        assert_eq!(r.kind.as_deref(), Some("bin"));
        assert_eq!(r.namespace, "tiny");
        assert_eq!(
            r.urls(),
            [
                "https://a.example/tiny/shard_001.bin",
                "https://b.example/mirror/shard_001.bin",
            ]
        );
        map.validate().unwrap();

        let unpinned = tiny()
            .to_descriptor()
            .to_resource_map(&[ShardId(3)])
            .unwrap();
        assert!(unpinned.get("shard_003.bin").unwrap().sha256.is_none());
        assert_eq!(unpinned.len(), 1);

        ErrorMatcher::kind(BunsenErrorKind::Lookup)
            .display_contains("tiny: shard 12 is out of range; there are 12")
            .cause(predicate("shard 12 of 12", |l: &LookupError| {
                l.problem == LookupProblem::OutOfRange { len: 12 }
            }))
            .assert_err(&d.to_resource_map(&[ShardId(12)]));
    }

    #[test]
    fn test_select_is_ordered_without_repeats_twice_over() {
        let d = tiny().to_descriptor();
        let ids = |v: &[usize]| v.iter().copied().map(ShardId).collect::<Vec<_>>();
        assert_eq!(
            d.select(&[Slice::index(1), Slice::index(1)]).unwrap(),
            ids(&[1])
        );
    }
}