Skip to main content

ic_db/store/
mod.rs

1//! Shared commit and traversal over one supplier-owned collection.
2//! Typed codecs stay at the boundary; no executor is generated per entity.
3
4mod maintenance;
5mod query;
6
7use crate::{
8    __private::RowInfo, Entity, EntitySchema, Error, FieldType, IndexValue, PrimaryKey, Schema,
9    UniqueKey, key, primary::RowKey, store_key::StoreKey,
10};
11use ic_storage::{
12    Memory, RuntimeMemory,
13    adapter::{MapIter, StableBTreeMap},
14};
15pub use maintenance::{
16    CopyStatus, CopyStep, Maintenance, RetiredSource, SchemaCopy, SchemaTransition,
17};
18pub use query::{
19    Aggregate, AggregateJobs, Column, Comparison, GetMany, GroupCount, GroupCursor, GroupOrder,
20    GroupPage, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue, JobHandle, JobOutcome,
21    JobStep, OrderTerm, Query, QueryCursor, QueryOperand, QueryPage, SelectColumns,
22    SelectedGetMany, SelectedQuery, Selection, SortDirection, SummaryMeasure,
23};
24use std::collections::{BTreeMap, BTreeSet};
25
26const MANIFEST: &[u8] = b"ICDBMF02";
27const MAX_BATCH: usize = 32;
28const MAX_BATCH_BYTES: usize = 128 * 1024;
29type Map<M> = StableBTreeMap<StoreKey, Vec<u8>, M>;
30type BulkRowVisitor<'a> = dyn FnMut(usize, &[u8]) -> Result<(), Error> + 'a;
31
32// Share supplier advancement and physical-key decoding without buffering a page
33// or moving the typed row/key consistency check out of the public terminal.
34#[inline(never)]
35fn next_primary<M: Memory>(
36    entries: &mut MapIter<'_, StoreKey, Vec<u8>, M>,
37    prefix: &[u8],
38    key_type: FieldType,
39) -> Result<Option<(RowKey, Vec<u8>)>, Error> {
40    let Some(entry) = entries.next() else {
41        return Ok(None);
42    };
43    if !entry.key().starts_with(prefix) {
44        return Ok(None);
45    }
46    let id = RowKey::decode(&entry.key()[ENTITY_PREFIX_BYTES..], key_type)?;
47
48    Ok(Some((id, entry.into_value())))
49}
50
51fn decode_primary<E: Entity>(bytes: &[u8], key: E::Key) -> Result<E, Error> {
52    let row = E::decode(bytes)?;
53    if row.key() != key {
54        return Err(Error::Corrupt);
55    }
56
57    Ok(row)
58}
59
60// The index value is already the encoded primary key. Validate its exact type
61// and framing before using those same bytes to address the owner.
62fn read_index_owner<M: Memory>(
63    map: &Map<M>,
64    entity: u32,
65    key_type: FieldType,
66    encoded: &[u8],
67) -> Result<(RowKey, Vec<u8>), Error> {
68    let owner = RowKey::decode(encoded, key_type)?;
69    let key = prefix(2, entity, encoded);
70    let row = map.get(&StoreKey::new(key)?).ok_or(Error::Corrupt)?;
71
72    Ok((owner, row))
73}
74
75// Validate a physical index entry against its stored owner when the caller needs
76// only the integrity result. Query scans already have the inspected fields.
77fn validate_index_owner<M: Memory>(
78    map: &Map<M>,
79    entity: &EntitySchema,
80    key: &[u8],
81    encoded_owner: &[u8],
82) -> Result<(), Error> {
83    let (owner, row) = read_index_owner(map, entity.id, entity.key_type()?, encoded_owner)?;
84    validate_index_entry(entity, &entity.inspect_row(&row)?, owner, key)
85}
86
87// The typed caller checks the decoded row's index components against this key.
88#[inline(never)]
89fn next_index<M: Memory>(
90    map: &Map<M>,
91    entries: &mut MapIter<'_, StoreKey, Vec<u8>, M>,
92    prefix: &[u8],
93    entity: u32,
94    key_type: FieldType,
95) -> Result<Option<(StoreKey, RowKey, Vec<u8>)>, Error> {
96    let Some(entry) = entries.next() else {
97        return Ok(None);
98    };
99    if !entry.key().starts_with(prefix) {
100        return Ok(None);
101    }
102    let (key, owner) = entry.into_pair();
103    let (id, bytes) = read_index_owner(map, entity, key_type, &owner)?;
104
105    Ok(Some((key, id, bytes)))
106}
107
108#[inline(never)]
109fn index_prefix_key(
110    entity: &EntitySchema,
111    index: &str,
112    values: &[IndexValue<'_>],
113    limit: usize,
114) -> Result<StoreKey, Error> {
115    let index = entity.index_by_name(index).ok_or(Error::InvalidSchema)?;
116    if values.is_empty() || !(1..=32).contains(&limit) {
117        return Err(Error::Limit);
118    }
119
120    StoreKey::new(admit_index_prefix(entity, index, values)?)
121}
122
123// Both ordinary batches and complete-target migration validation derive present
124// references from the same admitted reverse-index components.
125fn collect_references(
126    entity: &EntitySchema,
127    info: &RowInfo,
128    required: &mut BTreeSet<(u32, RowKey)>,
129) -> Result<(), Error> {
130    for field in entity.fields {
131        if let Some(reference) = field.reference {
132            if matches!(field.value, FieldType::List { .. }) {
133                required.extend(
134                    info.list_links
135                        .iter()
136                        .filter(|(index, _)| *index == reference.index)
137                        .map(|(_, key)| (reference.entity, *key)),
138                );
139                continue;
140            }
141            let position = entity
142                .indexes
143                .iter()
144                .position(|index| index.id == reference.index)
145                .ok_or(Error::Corrupt)?;
146            let mut bytes = info
147                .indexes
148                .get(position)
149                .and_then(Option::as_ref)
150                .map(Vec::as_slice)
151                .ok_or(Error::Corrupt)?;
152            if field.optional {
153                // Absence has no target; zero remains an ordinary target key.
154                match bytes.split_first() {
155                    Some((0, _)) => continue,
156                    Some((1, rest)) => bytes = rest,
157                    _ => return Err(Error::Corrupt),
158                }
159            }
160            let mut remaining = bytes;
161            key::consume(&mut remaining, field.value)?;
162            let target = RowKey::decode(&bytes[..bytes.len() - remaining.len()], field.value)?;
163            required.insert((reference.entity, target));
164        }
165    }
166
167    Ok(())
168}
169
170fn validate_reference_target<M: Memory>(
171    map: &Map<M>,
172    schema: &Schema,
173    entity: u32,
174    id: RowKey,
175) -> Result<(), Error> {
176    let bytes = map
177        .get(&row_key(entity, id))
178        .ok_or(Error::ReferenceViolation)?;
179    let entity = schema.entity_by_id(entity).ok_or(Error::Corrupt)?;
180    if entity.inspect_row(&bytes)?.key != id {
181        return Err(Error::Corrupt);
182    }
183
184    Ok(())
185}
186
187fn manifest_key() -> StoreKey {
188    StoreKey::new(vec![0]).expect("manifest key fits")
189}
190
191fn live_manifest(schema: [u8; 32], incarnation: [u8; 16]) -> Vec<u8> {
192    let mut bytes = MANIFEST.to_vec();
193    bytes.extend(schema);
194    bytes.extend(incarnation);
195
196    bytes
197}
198
199/// A bounded synchronous batch; preparation is internal to `Database::commit`.
200#[derive(Default)]
201pub struct Batch {
202    operation_time: Option<crate::Timestamp>,
203    mutations: Vec<Mutation>,
204    bytes: usize,
205}
206struct Mutation {
207    entity: &'static EntitySchema,
208    key: RowKey,
209    kind: Kind,
210}
211struct PreparedBatch {
212    removes: BTreeSet<StoreKey>,
213    writes: BTreeMap<StoreKey, Vec<u8>>,
214}
215struct ReturningRow<'a> {
216    entity: u32,
217    key: RowKey,
218    decode: &'a mut dyn FnMut(&[u8]) -> Result<(), Error>,
219}
220
221#[derive(Clone, Copy, PartialEq, Eq)]
222enum WriteMode {
223    Insert,
224    Replace,
225    Upsert,
226}
227
228enum Kind {
229    Put(WriteMode, Vec<u8>, RowInfo),
230    // Only maintenance can construct this; ordinary insert policies stay intact.
231    CopyInsert(Vec<u8>, RowInfo, [Option<crate::Timestamp>; 2]),
232    Delete,
233}
234
235impl Batch {
236    /// Begin an empty batch without persistent effects.
237    #[must_use]
238    pub fn new() -> Self {
239        Self::default()
240    }
241
242    /// Supply a deterministic clock value in qualification fixtures.
243    #[cfg(feature = "test-support")]
244    #[must_use]
245    pub fn at_for_test(time: crate::Timestamp) -> Self {
246        Self {
247            operation_time: Some(time),
248            ..Self::default()
249        }
250    }
251
252    /// Insert a typed record. Primary-key/uniqueness admission happens at commit.
253    /// # Errors
254    /// Refuses managed-field entities (use `insert_input`), encoding or batch capacity.
255    pub fn insert<E: Entity>(&mut self, row: &E) -> Result<(), Error> {
256        if E::SCHEMA.has_managed() {
257            return Err(Error::ManagedField);
258        }
259
260        self.save(row, WriteMode::Insert)
261    }
262
263    /// Resolve a typed insert input, append it to this batch and return its full row.
264    /// This is preparation, not a commit; the returned row is not yet persistent.
265    /// Explicit `None` remains absence, while omitted fields select their declared
266    /// literal default or optional absence. An omitted ULID primary key is issued
267    /// from the local stream at the operation time. No defaults run during replacement.
268    /// # Errors
269    /// Refuses missing required values, field/row bounds or batch capacity.
270    /// A refused input appends no mutation to the batch.
271    pub fn insert_input<I: crate::InsertInput>(&mut self, input: I) -> Result<I::Entity, Error> {
272        let time = *self
273            .operation_time
274            .get_or_insert_with(crate::Timestamp::now);
275        let row = input.__into_entity(Some(time))?;
276        self.save(&row, WriteMode::Insert)?;
277
278        Ok(row)
279    }
280
281    /// Replace an existing typed record, retaining its primary key.
282    /// Managed fields must echo the current stored values; commit sets update time
283    /// only on a real change. Queuing a replacement does not produce a committed row.
284    /// # Errors
285    /// Refuses encoding or batch capacity before mutation.
286    pub fn replace<E: Entity>(&mut self, row: &E) -> Result<(), Error> {
287        self.save(row, WriteMode::Replace)
288    }
289
290    /// Queue a full row for insertion or replacement by primary key. Managed
291    /// times are assigned by the database. Defaults and key generation do not run.
292    /// # Errors
293    /// Refuses encoding or batch capacity. Commit enforces ordinary constraints.
294    pub fn upsert<E: Entity>(&mut self, row: &E) -> Result<(), Error> {
295        self.save(row, WriteMode::Upsert)
296    }
297
298    fn save<E: Entity>(&mut self, row: &E, mode: WriteMode) -> Result<(), Error> {
299        if E::SCHEMA.has_managed() {
300            self.operation_time
301                .get_or_insert_with(crate::Timestamp::now);
302        }
303        self.put(row, |bytes, info| Kind::Put(mode, bytes, info))
304    }
305
306    /// Delete the matching row if present. An absent key has no effect.
307    /// # Errors
308    /// Refuses batch capacity before persistent mutation.
309    pub fn delete<E: Entity>(&mut self, key: impl Into<crate::Id<E>>) -> Result<(), Error> {
310        self.push(
311            Mutation {
312                entity: E::SCHEMA,
313                key: key.into().key().into_row_key(),
314                kind: Kind::Delete,
315            },
316            0,
317        )
318    }
319
320    fn put<E: Entity>(
321        &mut self,
322        row: &E,
323        kind: impl FnOnce(Vec<u8>, RowInfo) -> Kind,
324    ) -> Result<(), Error> {
325        let bytes = row.encode()?;
326        if bytes.len() > E::SCHEMA.max_row_bytes {
327            return Err(Error::Limit);
328        }
329        // encode() admitted field/row bounds. Keys come from that same typed
330        // value; decoding freshly encoded bytes would duplicate codec work.
331        let info = row.__row_info();
332        let key = info.key;
333        let len = bytes.len();
334        let kind = kind(bytes, info);
335        self.push(
336            Mutation {
337                entity: E::SCHEMA,
338                key,
339                kind,
340            },
341            len,
342        )
343    }
344
345    fn push(&mut self, mutation: Mutation, bytes: usize) -> Result<(), Error> {
346        if self.mutations.len() == MAX_BATCH || bytes > MAX_BATCH_BYTES - self.bytes {
347            return Err(Error::Limit);
348        }
349        self.bytes += bytes;
350        self.mutations.push(mutation);
351
352        Ok(())
353    }
354}
355
356/// A bounded page of rows in live primary-key order.
357pub struct Page<E: Entity> {
358    /// Typed records from this bounded primary-key traversal.
359    pub rows: Vec<E>,
360    /// Last returned key, present when another key in this entity follows at read time.
361    pub next_after: Option<E::Key>,
362}
363
364/// Admitted database owning the supplier's exclusive collection lease.
365pub struct Database<M: Memory> {
366    map: Map<M>,
367    schema: Schema,
368    incarnation: [u8; 16],
369}
370
371fn initialize_map<M: Memory>(
372    memory: RuntimeMemory<M>,
373    schema: &Schema,
374    manifest: Vec<u8>,
375) -> Result<Map<M>, Error> {
376    if memory.size() != 0 {
377        return Err(Error::Exists);
378    }
379    let mut map = Map::create(memory);
380    map.insert(manifest_key(), manifest);
381    for entity in schema.entities() {
382        map.insert(entity_state_key(entity.id), EntityState::default().encode());
383    }
384
385    Ok(map)
386}
387
388fn load_manifest<M: Memory>(memory: RuntimeMemory<M>) -> Result<(Map<M>, Vec<u8>), Error> {
389    if memory.size() == 0 {
390        return Err(Error::Corrupt);
391    }
392    let map = Map::load(memory);
393    let manifest = map.get(&manifest_key()).ok_or(Error::Corrupt)?;
394    Ok((map, manifest))
395}
396
397impl<M: Memory> Database<M> {
398    /// Create in a proven empty governed allocation. Never resets existing data.
399    /// # Errors
400    /// Refuses an all-zero incarnation or nonempty/unsupported supplier allocation.
401    /// # Panics
402    /// Supplier failures after initialization starts trap the enclosing IC message.
403    pub fn create(
404        memory: RuntimeMemory<M>,
405        schema: Schema,
406        incarnation: [u8; 16],
407    ) -> Result<Self, Error> {
408        if incarnation == [0; 16] {
409            return Err(Error::InvalidSchema);
410        }
411        let manifest = live_manifest(schema.fingerprint, incarnation);
412        let map = initialize_map(memory, &schema, manifest)?;
413
414        Ok(Self {
415            map,
416            schema,
417            incarnation,
418        })
419    }
420
421    /// Open only an exact manifest/compiled-contract match, without mutation.
422    /// This is not a whole-database integrity scan. Entity metadata is checked
423    /// when read explicitly or when preparing a write to that entity.
424    /// # Errors
425    /// Refuses active maintenance, missing/corrupt manifests, foreign contracts or supplier formats.
426    /// # Panics
427    /// Supplier corruption, including overlong stored keys, traps without repair.
428    pub fn open(memory: RuntimeMemory<M>, schema: Schema) -> Result<Self, Error> {
429        let (map, manifest) = load_manifest(memory)?;
430        if maintenance::admits_gate(&manifest)? {
431            return Err(Error::Maintenance);
432        }
433        if manifest.len() != 56 {
434            return Err(Error::Corrupt);
435        }
436        if &manifest[..8] != MANIFEST || manifest[8..40] != schema.fingerprint {
437            return Err(Error::IncompatibleSchema);
438        }
439        let incarnation = manifest[40..].try_into().map_err(|_| Error::Corrupt)?;
440        if incarnation == [0; 16] {
441            return Err(Error::Corrupt);
442        }
443
444        Ok(Self {
445            map,
446            schema,
447            incarnation,
448        })
449    }
450
451    /// Borrow the admitted executable description for inspection.
452    #[must_use]
453    pub const fn schema(&self) -> &Schema {
454        &self.schema
455    }
456
457    /// Durable database identity, distinct from schema identity.
458    #[must_use]
459    pub const fn incarnation(&self) -> [u8; 16] {
460        self.incarnation
461    }
462
463    /// Read the atomic revision of one admitted entity.
464    /// # Errors
465    /// Refuses unknown entities and malformed revision metadata.
466    pub fn revision<E: Entity>(&self) -> Result<u64, Error> {
467        let entity = self.schema.admits(E::SCHEMA)?;
468
469        read_revision(&self.map, entity.id)
470    }
471
472    /// Read the exact maintained whole-entity row count without scanning rows.
473    /// This trusts atomic entity metadata; it does not validate row/index integrity.
474    /// Filtered counts and row-validating enumeration use the fluent query API.
475    /// # Errors
476    /// Refuses unadmitted entities and missing or malformed entity metadata.
477    /// # Panics
478    /// Supplier corruption may trap; this operation never repairs storage.
479    pub fn cardinality<E: Entity>(&self) -> Result<u64, Error> {
480        let entity = self.schema.admits(E::SCHEMA)?;
481
482        Ok(read_entity_state(&self.map, entity.id)?.count)
483    }
484
485    /// Inspect the maintained whole-entity count by exact admitted schema name.
486    /// Like [`Self::cardinality`], this reads metadata without validating rows or indexes.
487    /// # Errors
488    /// Refuses unknown names and missing or malformed entity metadata.
489    /// # Panics
490    /// Supplier corruption may trap; this operation never repairs storage.
491    pub fn cardinality_by_name(&self, name: &str) -> Result<u64, Error> {
492        let entity = self
493            .schema
494            .entity_by_name(name)
495            .ok_or(Error::UnknownEntity)?;
496
497        Ok(read_entity_state(&self.map, entity.id)?.count)
498    }
499
500    /// Read a typed primary key without planning a scan.
501    /// # Errors
502    /// Refuses unadmitted types or malformed rows.
503    #[inline]
504    pub fn get<E: Entity>(&self, key: impl Into<crate::Id<E>>) -> Result<Option<E>, Error> {
505        let entity = self.schema.admits(E::SCHEMA)?;
506
507        self.get_typed::<E>(entity, key.into().key())
508    }
509
510    /// Read the owner of a complete generated unique key, or `None` on a miss.
511    /// # Errors
512    /// Propagates schema, key admission and row integrity errors.
513    pub fn get_unique<K: UniqueKey>(&self, key: &K) -> Result<Option<K::Entity>, Error> {
514        let components = key.components();
515        let values = components.as_ref();
516        if !K::Entity::SCHEMA
517            .index_by_name(K::INDEX)
518            .is_some_and(|index| index.is_unique_lookup(values.len()))
519        {
520            return Err(Error::InvalidQuery);
521        }
522
523        self.query::<K::Entity>()
524            .using_index(K::INDEX, values)
525            .work_limit(1)
526            .try_one()
527    }
528
529    // Share grouping and storage reads across raw/branded keys and result shapes.
530    #[inline(never)]
531    fn get_many_typed<K: PrimaryKey, R>(
532        &self,
533        entity: &EntitySchema,
534        keys: &[K],
535        decode: impl Fn(&EntitySchema, K, &[u8]) -> Result<R, Error>,
536    ) -> Result<Vec<Option<R>>, Error> {
537        let mut rows: Vec<_> = (0..keys.len()).map(|_| None).collect();
538        let Some((&first, rest)) = keys.split_first() else {
539            return Ok(rows);
540        };
541        if rest.iter().all(|&key| key == first) {
542            if let Some(bytes) = self.map.get(&row_key(entity.id, first.into_row_key())) {
543                for slot in &mut rows {
544                    *slot = Some(decode(entity, first, &bytes)?);
545                }
546            }
547            return Ok(rows);
548        }
549
550        let mut probes = keys
551            .iter()
552            .map(|key| row_key(entity.id, key.into_row_key()));
553        self.visit_bulk_rows(&mut probes, &mut |slot, bytes| {
554            rows[slot] = Some(decode(entity, keys[slot], bytes)?);
555            Ok(())
556        })?;
557        Ok(rows)
558    }
559
560    // Share routing and positional bookkeeping across entity and projection types.
561    fn visit_bulk_rows(
562        &self,
563        keys: &mut dyn ExactSizeIterator<Item = StoreKey>,
564        visit: &mut BulkRowVisitor<'_>,
565    ) -> Result<(), Error> {
566        let mut probes = Vec::with_capacity(keys.len());
567        let mut masks = Vec::with_capacity(keys.len());
568        for (slot, key) in keys.enumerate() {
569            let bit = 1_u32 << slot;
570            match probes.binary_search(&key) {
571                Ok(i) => masks[i] |= bit,
572                Err(i) => {
573                    probes.insert(i, key);
574                    masks.insert(i, bit);
575                }
576            }
577        }
578        let mut masks = masks.into_iter();
579        self.map.try_visit_sorted_keys(&probes, |_, bytes| {
580            let slots = masks.next().expect("one visit per distinct key");
581            if let Some(bytes) = bytes {
582                for slot in query::set_bit_positions(slots) {
583                    visit(slot, &bytes)?;
584                }
585            }
586            Ok(())
587        })
588    }
589
590    // Keep traversal separate from the static type's admission call. Passing
591    // its admitted descriptor lets compatible typed readers share machine code.
592    #[inline(never)]
593    fn get_typed<E: Entity>(&self, entity: &EntitySchema, key: E::Key) -> Result<Option<E>, Error> {
594        self.map
595            .get(&row_key(entity.id, key.into_row_key()))
596            .map(|bytes| decode_primary::<E>(&bytes, key))
597            .transpose()
598    }
599
600    /// Read at most 32 rows in primary-key order; continuation is live, not a snapshot.
601    /// # Errors
602    /// Refuses zero/oversized limits, unadmitted types or corrupt rows.
603    /// # Panics
604    /// Supplier corruption, including overlong stored keys, traps without repair.
605    #[inline]
606    pub fn page<E: Entity>(&self, after: Option<E::Key>, limit: usize) -> Result<Page<E>, Error> {
607        let entity = self.schema.admits(E::SCHEMA)?;
608
609        self.page_typed::<E>(entity, after, limit)
610    }
611
612    #[inline(never)]
613    fn page_typed<E: Entity>(
614        &self,
615        entity: &EntitySchema,
616        after: Option<E::Key>,
617        limit: usize,
618    ) -> Result<Page<E>, Error> {
619        if !(1..=32).contains(&limit) {
620            return Err(Error::Limit);
621        }
622        let prefix = prefix(2, entity.id, &[]);
623        let lower = match after {
624            Some(key) => std::ops::Bound::Excluded(row_key(entity.id, key.into_row_key())),
625            None => std::ops::Bound::Included(
626                StoreKey::new(prefix.clone()).expect("row namespace fits"),
627            ),
628        };
629        let mut entries = self.map.range((lower, std::ops::Bound::Unbounded));
630        let key_type = entity.key_type()?;
631        let mut rows = Vec::new();
632        let mut last = None;
633        for _ in 0..limit {
634            let Some((id, bytes)) = next_primary(&mut entries, &prefix, key_type)? else {
635                break;
636            };
637            let id = E::Key::from_row_key(id)?;
638            rows.push(decode_primary::<E>(&bytes, id)?);
639            last = Some(id);
640        }
641
642        // Look ahead only on a full page. The next row is decoded on its own page.
643        let more = rows.len() == limit
644            && entries
645                .next_key()
646                .is_some_and(|key| key.starts_with(&prefix));
647        Ok(Page {
648            next_after: if more { last } else { None },
649            rows,
650        })
651    }
652
653    /// Read the first bounded collection under an exact, nonempty leading index prefix.
654    /// Exact operands obey field bounds and the 512-byte complete-key budget.
655    /// Use `IndexValue::Absent` for an absent optional component. A present-only
656    /// unique index refuses absent operands because it does not enumerate those rows.
657    /// # Errors
658    /// Refuses unknown indexes, mismatched operand types, invalid prefix/limit or
659    /// inconsistent index entries. This method does not yet return continuation.
660    #[inline]
661    pub fn index_prefix<E: Entity>(
662        &self,
663        index: &str,
664        values: &[IndexValue<'_>],
665        limit: usize,
666    ) -> Result<Vec<E>, Error> {
667        let entity = self.schema.admits(E::SCHEMA)?;
668
669        self.index_prefix_typed::<E>(entity, index, values, limit)
670    }
671
672    #[inline(never)]
673    fn index_prefix_typed<E: Entity>(
674        &self,
675        entity: &EntitySchema,
676        index: &str,
677        values: &[IndexValue<'_>],
678        limit: usize,
679    ) -> Result<Vec<E>, Error> {
680        let prefix = index_prefix_key(entity, index, values, limit)?;
681        let mut rows = Vec::new();
682        let mut entries = self.map.range(prefix.clone()..);
683        let key_type = entity.key_type()?;
684        for _ in 0..limit {
685            let Some((key, id, bytes)) =
686                next_index(&self.map, &mut entries, &prefix, entity.id, key_type)?
687            else {
688                break;
689            };
690            let row = E::decode(&bytes)?;
691            let info = row.__row_info();
692            visit_index_components(entity, &info, |idx, components| {
693                check_component_framing(entity, idx, components)
694            })?;
695            validate_index_entry(entity, &info, id, &key)?;
696            rows.push(row);
697        }
698
699        Ok(rows)
700    }
701
702    /// Prepare final state, then synchronously apply rows, indexes, revisions and counts.
703    /// A normal refusal occurs before persistent writes. Success is not a separate
704    /// durability point from the surrounding IC message. Empty/no-op batches preserve revisions.
705    /// # Errors
706    /// Refuses missing/existing rows, duplicate targets, uniqueness/reference violations,
707    /// corruption or limits. References use the intended final batch state.
708    /// # Panics
709    /// Supplier failures after the first mutation trap; never catch and continue an IC commit.
710    pub fn commit(&mut self, batch: Batch) -> Result<(), Error> {
711        observe!(commit, { self.commit_batch(batch, None, None).map(|_| ()) })
712    }
713
714    /// Insert or replace one row by primary key and return its stored value.
715    /// # Errors
716    /// Propagates batch preparation and commit errors, including unique conflicts.
717    /// # Panics
718    /// Supplier failures during publication trap as in [`Self::commit`].
719    pub fn upsert<E: Entity>(&mut self, row: &E) -> Result<E, Error> {
720        let mut batch = Batch::new();
721        batch.upsert(row)?;
722        self.commit_returning(batch, row.id())
723    }
724
725    /// Commit the whole batch and return the selected insert or replacement,
726    /// including its final managed timestamps. The row is decoded during preparation.
727    /// # Errors
728    /// Returns [`Error::Missing`] if the batch has no insert or replacement for
729    /// this entity and key. All ordinary [`Self::commit`] refusals apply.
730    /// # Panics
731    /// Supplier failures during publication trap as in [`Self::commit`].
732    pub fn commit_returning<E: Entity>(
733        &mut self,
734        batch: Batch,
735        key: impl Into<crate::Id<E>>,
736    ) -> Result<E, Error> {
737        observe!(commit, {
738            self.schema.admits(E::SCHEMA)?;
739            let mut row = None;
740            let selected = ReturningRow {
741                entity: E::SCHEMA.id,
742                key: key.into().key().into_row_key(),
743                decode: &mut |bytes| {
744                    row = Some(E::decode(bytes)?);
745                    Ok(())
746                },
747            };
748            self.commit_batch(batch, Some(selected), None)?;
749            Ok(row.expect("commit validated the selected row before publication"))
750        })
751    }
752
753    pub(crate) fn insert_if_absent<K: UniqueKey>(
754        &mut self,
755        input: impl crate::InsertInput<Entity = K::Entity>,
756    ) -> Result<crate::InsertOutcome<K::Entity>, Error> {
757        let entity = K::Entity::SCHEMA;
758        let index = entity
759            .index_by_name(K::INDEX)
760            .filter(|i| i.unique)
761            .ok_or(Error::InvalidQuery)?;
762        let mut batch = Batch::new();
763        let row = batch.insert_input(input)?;
764        let prefix = index_prefix(entity.id, index.id);
765        let applied = observe!(commit, {
766            self.commit_batch(batch, None, Some((entity, &prefix)))
767        })?;
768        Ok(if applied {
769            crate::InsertOutcome::Inserted(row)
770        } else {
771            crate::InsertOutcome::AlreadyPresent
772        })
773    }
774
775    // False means the single conditional insert was validated and skipped.
776    fn commit_batch(
777        &mut self,
778        batch: Batch,
779        returning: Option<ReturningRow<'_>>,
780        conflict_target: Option<(&EntitySchema, &[u8])>,
781    ) -> Result<bool, Error> {
782        let Some(prepared) = self.prepare_batch(batch, returning, conflict_target)? else {
783            return Ok(false);
784        };
785        self.apply_batch(prepared);
786        Ok(true)
787    }
788
789    // Supplier failures during stable writes trap and roll back the IC message.
790    fn apply_batch(&mut self, prepared: PreparedBatch) {
791        let PreparedBatch { removes, writes } = prepared;
792        let expected = removes.len() as u64;
793        assert_eq!(
794            self.map.remove_many(removes),
795            expected,
796            "prepared removal set changed"
797        );
798        for (key, value) in writes {
799            self.map.insert(key, value);
800        }
801    }
802
803    fn prepare_batch(
804        &self,
805        batch: Batch,
806        mut returning: Option<ReturningRow<'_>>,
807        conflict_target: Option<(&EntitySchema, &[u8])>,
808    ) -> Result<Option<PreparedBatch>, Error> {
809        let mut targets = BTreeSet::new();
810        let mut removes = BTreeSet::new();
811        let mut writes = BTreeMap::new();
812        let mut unique = BTreeSet::new();
813        // Observe each entity once, then apply its final net row delta. A balanced
814        // delete/insert batch must not depend on mutation order. No state survives calls.
815        let mut entities = BTreeMap::new();
816        let mut required = BTreeSet::new();
817        let mut deleted = Vec::new();
818        let mut index_runs = Vec::new();
819        for mut mutation in batch.mutations {
820            let direction = deleted.last().and_then(|&(entity, key)| {
821                (entity == mutation.entity.id && matches!(mutation.kind, Kind::Delete))
822                    .then(|| mutation.key < key)
823            });
824            if direction.is_none() {
825                index_runs.clear();
826            }
827            self.schema.admits(mutation.entity)?;
828            let key = row_key(mutation.entity.id, mutation.key);
829            if !targets.insert(key.clone()) {
830                return Err(Error::DuplicateTarget);
831            }
832            let old = self.map.get(&key);
833            match (&mutation.kind, &old) {
834                (Kind::Put(WriteMode::Insert, ..) | Kind::CopyInsert(..), Some(_)) => {
835                    return Err(Error::Exists);
836                }
837                (Kind::Put(WriteMode::Replace, ..), None) => return Err(Error::Missing),
838                (Kind::Delete, None) => continue,
839                _ => {}
840            }
841            if mutation.entity.has_managed() {
842                match &mut mutation.kind {
843                    Kind::Put(mode, bytes, info) => {
844                        if crate::managed::save(
845                            mutation.entity,
846                            bytes,
847                            old.as_deref(),
848                            *mode == WriteMode::Upsert,
849                            batch.operation_time.ok_or(Error::MissingOperationTime)?,
850                        )? {
851                            *info = mutation.entity.inspect_row(bytes)?;
852                        }
853                    }
854                    Kind::CopyInsert(bytes, _, expected) => {
855                        if crate::managed::values(mutation.entity, bytes)? != *expected {
856                            return Err(Error::ManagedField);
857                        }
858                    }
859                    Kind::Delete => {}
860                }
861            }
862            if let Kind::Put(_, bytes, _) = &mutation.kind
863                && let Some(selected) = returning
864                    .take_if(|row| row.entity == mutation.entity.id && row.key == mutation.key)
865            {
866                (selected.decode)(bytes)?;
867            }
868            // Admit complete after-image keys even when the row is a no-op.
869            // Retain these buffers for publication instead of encoding twice.
870            let mut after_indexes = match &mutation.kind {
871                Kind::Put(_, _, info) | Kind::CopyInsert(_, info, _) => {
872                    index_entries(mutation.entity, info)?
873                }
874                Kind::Delete => Vec::new(),
875            };
876            let (_, changed, delta) = match entities.entry(mutation.entity.id) {
877                std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
878                std::collections::btree_map::Entry::Vacant(entry) => entry.insert((
879                    read_entity_state(&self.map, mutation.entity.id)?,
880                    false,
881                    0_i64,
882                )),
883            };
884            if let (Kind::Put(_, bytes, _), Some(old)) = (&mutation.kind, &old)
885                && bytes == old
886            {
887                continue;
888            }
889            if let Some(old) = &old {
890                let info = mutation.entity.inspect_row(old)?;
891                if info.key != mutation.key {
892                    return Err(Error::Corrupt);
893                }
894                let owner = info.key.encode();
895                for (slot, (key, _)) in index_entries(mutation.entity, &info)?
896                    .into_iter()
897                    .enumerate()
898                {
899                    let value = if let Some(descending) = direction
900                        && key.first() == Some(&3)
901                    {
902                        read_adjacent_index(&self.map, &mut index_runs, slot, &key, descending)
903                    } else {
904                        self.map.get(&key)
905                    };
906                    if value.as_deref() != Some(owner.as_slice()) {
907                        return Err(Error::Corrupt);
908                    }
909
910                    // Same physical key and owner: leave the verified entry in place.
911                    // Its unique value remains occupied during final-state admission.
912                    if let Some(position) =
913                        after_indexes.iter().position(|(after, _)| *after == key)
914                    {
915                        after_indexes.remove(position);
916                    } else {
917                        removes.insert(key);
918                    }
919                }
920            }
921            *changed = true;
922            *delta += match &mutation.kind {
923                Kind::Put(..) | Kind::CopyInsert(..) => i64::from(old.is_none()),
924                Kind::Delete => -1,
925            };
926            // Private migration inserts may precede their targets. The frozen
927            // complete target validates references before it can be published.
928            let copy_insert = matches!(&mutation.kind, Kind::CopyInsert(..));
929
930            match mutation.kind {
931                Kind::Delete => {
932                    deleted.push((mutation.entity.id, mutation.key));
933                    removes.insert(key);
934                }
935                Kind::Put(_, bytes, info) | Kind::CopyInsert(bytes, info, _) => {
936                    writes.insert(key, bytes);
937                    for (key, is_unique) in after_indexes {
938                        if is_unique && !unique.insert(key.clone()) {
939                            return Err(Error::UniqueViolation);
940                        }
941                        writes.insert(key, info.key.encode());
942                    }
943                    if !copy_insert {
944                        collect_references(mutation.entity, &info, &mut required)?;
945                    }
946                }
947            }
948        }
949        drop(index_runs);
950        if returning.is_some() {
951            return Err(Error::Missing);
952        }
953        // Check existing owners only after all releases in this batch are known.
954        let mut skip_insert = false;
955        for key in unique {
956            if let Some((entity, _)) = conflict_target.filter(|(_, prefix)| key.starts_with(prefix))
957            {
958                if let Some(encoded) = self.map.get(&key) {
959                    validate_index_owner(&self.map, entity, &key, &encoded)?;
960                    skip_insert = true;
961                }
962                continue;
963            }
964            if self.map.contains_key(&key) && !removes.contains(&key) {
965                return Err(Error::UniqueViolation);
966            }
967        }
968        if skip_insert {
969            // No candidate row will be published to satisfy its own references.
970            self.validate_references(&required, &deleted, &removes, &BTreeMap::new())?;
971            return Ok(None);
972        }
973        self.validate_references(&required, &deleted, &removes, &writes)?;
974        for (entity, (mut state, changed, delta)) in entities {
975            if changed {
976                state.revision = state.revision.checked_add(1).ok_or(Error::Limit)?;
977                state.count = if delta >= 0 {
978                    state.count.checked_add(delta as u64).ok_or(Error::Limit)?
979                } else {
980                    state
981                        .count
982                        .checked_sub((-delta) as u64)
983                        .ok_or(Error::Corrupt)?
984                };
985                writes.insert(entity_state_key(entity), state.encode());
986            }
987        }
988        Ok(Some(PreparedBatch { removes, writes }))
989    }
990
991    // Reuse the prepared final rows and ordinary index changes. No durable
992    // relationship catalog or second mutation executor is involved.
993    fn validate_references(
994        &self,
995        required: &BTreeSet<(u32, RowKey)>,
996        deleted: &[(u32, RowKey)],
997        removes: &BTreeSet<StoreKey>,
998        writes: &BTreeMap<StoreKey, Vec<u8>>,
999    ) -> Result<(), Error> {
1000        for &(entity, id) in required {
1001            let key = row_key(entity, id);
1002            if writes.contains_key(&key) {
1003                continue;
1004            } // prepared, validated final target
1005            if removes.contains(&key) {
1006                return Err(Error::ReferenceViolation);
1007            }
1008            validate_reference_target(&self.map, &self.schema, entity, id)?;
1009        }
1010        // A lower-bound seek proves the gap before its first physical key is empty.
1011        // Keep one such gap only for this immutable preparation pass.
1012        let mut gap: Option<(StoreKey, Option<StoreKey>)> = None;
1013        for &(target, id) in deleted {
1014            for entity in self.schema.entities() {
1015                for field in entity.fields {
1016                    let Some(reference) = field.reference.filter(|value| value.entity == target)
1017                    else {
1018                        continue;
1019                    };
1020                    let prefix = if matches!(field.value, FieldType::List { .. }) {
1021                        list_target_prefix(entity.id, reference.index, id)
1022                    } else {
1023                        let mut prefix = index_prefix(entity.id, reference.index);
1024                        id.index_value()
1025                            .append_component(field.optional, &mut prefix);
1026                        prefix
1027                    };
1028                    let prefix = StoreKey::new(prefix)?;
1029                    if let Some((start, next)) = &gap
1030                        && start <= &prefix
1031                        && next
1032                            .as_ref()
1033                            .is_none_or(|key| key > &prefix && !key.starts_with(&prefix))
1034                    {
1035                        continue;
1036                    }
1037                    // Each skipped entry belongs to a distinct changed row in
1038                    // this range. At most MAX_BATCH skips plus one survivor.
1039                    let mut entries = self.map.range(prefix.clone()..);
1040                    for position in 0..=MAX_BATCH {
1041                        let entry = match entries.next() {
1042                            Some(entry) if entry.key().starts_with(&prefix) => entry,
1043                            boundary => {
1044                                if position == 0 && deleted.len() > 1 {
1045                                    gap = Some((prefix, boundary.map(|entry| entry.key().clone())));
1046                                }
1047                                break;
1048                            }
1049                        };
1050                        if removes.contains(entry.key()) {
1051                            if position == MAX_BATCH {
1052                                return Err(Error::Corrupt);
1053                            }
1054                            continue;
1055                        }
1056                        validate_index_owner(&self.map, entity, entry.key(), &entry.value())?;
1057
1058                        return Err(Error::ReferenceViolation);
1059                    }
1060                }
1061            }
1062        }
1063
1064        Ok(())
1065    }
1066}
1067
1068// Probe at most one neighboring entry per expected secondary key. A gap or different order
1069// switches that slot to point reads for the rest of the same-entity delete run.
1070// Every successful probe checks the full key; the caller checks its stored owner.
1071fn read_adjacent_index<'a, M: Memory>(
1072    map: &'a Map<M>,
1073    runs: &mut Vec<Option<MapIter<'a, StoreKey, Vec<u8>, M>>>,
1074    slot: usize,
1075    key: &StoreKey,
1076    descending: bool,
1077) -> Option<Vec<u8>> {
1078    if slot == runs.len() {
1079        let entries = if descending {
1080            map.range(..=key.clone())
1081        } else {
1082            map.range(key.clone()..)
1083        };
1084        runs.push(Some(entries));
1085    }
1086    let run = &mut runs[slot];
1087    if let Some(entry) = run.as_mut().and_then(|entries| {
1088        if descending {
1089            entries.next_back()
1090        } else {
1091            entries.next()
1092        }
1093    }) && entry.key() == key
1094    {
1095        return Some(entry.value());
1096    }
1097    *run = None;
1098    map.get(key)
1099}
1100
1101// Physical key headers contain a namespace tag and fixed-width schema handles.
1102const ENTITY_PREFIX_BYTES: usize = 1 + size_of::<u32>();
1103const INDEX_PREFIX_BYTES: usize = ENTITY_PREFIX_BYTES + size_of::<u32>();
1104
1105fn prefix(tag: u8, entity: u32, suffix: &[u8]) -> Vec<u8> {
1106    let mut key = Vec::with_capacity(ENTITY_PREFIX_BYTES + suffix.len());
1107    key.push(tag);
1108    key.extend_from_slice(&entity.to_be_bytes());
1109    key.extend_from_slice(suffix);
1110
1111    key
1112}
1113
1114fn entity_state_key(entity: u32) -> StoreKey {
1115    StoreKey::new(prefix(1, entity, &[])).expect("entity state key fits")
1116}
1117
1118fn read_revision<M: Memory>(map: &Map<M>, entity: u32) -> Result<u64, Error> {
1119    Ok(read_entity_state(map, entity)?.revision)
1120}
1121
1122/// One atomic metadata record; neither value is reconstructed during ordinary open.
1123#[derive(Default)]
1124struct EntityState {
1125    revision: u64,
1126    count: u64,
1127}
1128impl EntityState {
1129    fn encode(&self) -> Vec<u8> {
1130        let mut bytes = self.revision.to_le_bytes().to_vec();
1131        bytes.extend(self.count.to_le_bytes());
1132
1133        bytes
1134    }
1135}
1136fn read_entity_state<M: Memory>(map: &Map<M>, entity: u32) -> Result<EntityState, Error> {
1137    let bytes = map.get(&entity_state_key(entity)).ok_or(Error::Corrupt)?;
1138    let (revision, count) = bytes.split_first_chunk::<8>().ok_or(Error::Corrupt)?;
1139    let revision = u64::from_le_bytes(*revision);
1140    let count = u64::from_le_bytes(count.try_into().map_err(|_| Error::Corrupt)?);
1141    // The first insertion advances the revision in the same batch.
1142    if revision == 0 && count != 0 {
1143        return Err(Error::Corrupt);
1144    }
1145
1146    Ok(EntityState { revision, count })
1147}
1148
1149fn row_key(entity: u32, id: RowKey) -> StoreKey {
1150    let mut key = prefix(2, entity, &[]);
1151    id.append_to(&mut key);
1152
1153    StoreKey::new(key).expect("bounded primary key fits")
1154}
1155
1156fn index_prefix(entity: u32, index: u32) -> Vec<u8> {
1157    prefix(3, entity, &index.to_be_bytes())
1158}
1159// One entry per distinct target of a list field, suffixed by its owner key.
1160fn list_target_prefix(entity: u32, field: u32, target: RowKey) -> Vec<u8> {
1161    let mut key = prefix(4, entity, &field.to_be_bytes());
1162    target.append_to(&mut key);
1163    key
1164}
1165
1166// Direct lookups and fluent reads share exact prefix admission and completion bounds.
1167fn admit_index_prefix(
1168    entity: &EntitySchema,
1169    index: &crate::IndexSchema,
1170    values: &[IndexValue<'_>],
1171) -> Result<Vec<u8>, Error> {
1172    if values.len() > index.fields.len() {
1173        return Err(Error::Limit);
1174    }
1175    let mut prefix = index_prefix(entity.id, index.id);
1176    for (value, name) in values.iter().zip(index.fields) {
1177        let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1178        value.admit(field.value, field.optional)?;
1179        if index.present_only && *value == IndexValue::Absent {
1180            return Err(Error::InvalidOperand);
1181        }
1182        value.append_component(field.optional, &mut prefix);
1183        if prefix.len() > crate::MAX_INDEX_KEY_BYTES {
1184            return Err(Error::Limit);
1185        }
1186    }
1187    let mut completion = if index.unique {
1188        0
1189    } else {
1190        key::minimum_bytes(entity.key_type()?)?
1191    };
1192    for name in &index.fields[values.len()..] {
1193        let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1194        completion += if field.optional && !index.present_only {
1195            1
1196        } else {
1197            key::minimum_bytes(field.value)? + usize::from(field.optional)
1198        };
1199    }
1200    if prefix.len() + completion > crate::MAX_INDEX_KEY_BYTES {
1201        return Err(Error::Limit);
1202    }
1203
1204    Ok(prefix)
1205}
1206// RowInfo may come from a generated entity or the shared stored-row decoder.
1207fn visit_index_components(
1208    entity: &EntitySchema,
1209    info: &RowInfo,
1210    mut visit: impl FnMut(&crate::IndexSchema, &[u8]) -> Result<(), Error>,
1211) -> Result<(), Error> {
1212    if info.indexes.len() != entity.indexes.len() {
1213        return Err(Error::Corrupt);
1214    }
1215    for (index, values) in entity.indexes.iter().zip(&info.indexes) {
1216        let Some(values) = values else {
1217            if index.present_only {
1218                continue;
1219            }
1220
1221            return Err(Error::Corrupt);
1222        };
1223        visit(index, values)?;
1224    }
1225
1226    Ok(())
1227}
1228
1229// Generated RowInfo can be supplied by an Entity implementation. Check its
1230// component bytes before admitting them as physical index keys.
1231fn check_component_framing(
1232    entity: &EntitySchema,
1233    index: &crate::IndexSchema,
1234    mut remaining: &[u8],
1235) -> Result<(), Error> {
1236    for name in index.fields {
1237        let field = entity.index_field(name).ok_or(Error::Corrupt)?;
1238        key::consume_component(&mut remaining, field, index.present_only, Error::Corrupt)?;
1239    }
1240    if !remaining.is_empty() {
1241        return Err(Error::Corrupt);
1242    }
1243
1244    Ok(())
1245}
1246
1247fn index_entries(entity: &EntitySchema, info: &RowInfo) -> Result<Vec<(StoreKey, bool)>, Error> {
1248    let mut entries = Vec::new();
1249    visit_index_components(entity, info, |index, values| {
1250        check_component_framing(entity, index, values)?;
1251        let mut key = index_prefix(entity.id, index.id);
1252        key.extend_from_slice(values);
1253        if !index.unique {
1254            info.key.append_to(&mut key);
1255        }
1256        entries.push((StoreKey::new(key)?, index.unique));
1257
1258        Ok(())
1259    })?;
1260
1261    let mut links = BTreeSet::new();
1262    for &(field, target) in &info.list_links {
1263        if links.insert((field, target)) {
1264            let mut key = list_target_prefix(entity.id, field, target);
1265            info.key.append_to(&mut key);
1266            entries.push((StoreKey::new(key)?, false));
1267        }
1268    }
1269    Ok(entries)
1270}
1271
1272// A visited entry must agree with its owner in namespace, components and suffix.
1273// Stored-row inspection has decoded the typed components and encoded them with
1274// the canonical key writer. Generated RowInfo callers must check framing first.
1275// All indexes still obey the physical size limit, including unrelated entries.
1276fn validate_index_entry(
1277    entity: &EntitySchema,
1278    info: &RowInfo,
1279    owner: RowKey,
1280    key: &[u8],
1281) -> Result<(), Error> {
1282    if info.key != owner {
1283        return Err(Error::Corrupt);
1284    }
1285    let (header, payload) = key
1286        .split_at_checked(INDEX_PREFIX_BYTES)
1287        .ok_or(Error::Corrupt)?;
1288    let list_link = header[0] == 4;
1289    if (!list_link && header[0] != 3) || header[1..ENTITY_PREFIX_BYTES] != entity.id.to_be_bytes() {
1290        return Err(Error::Corrupt);
1291    }
1292    let mut matches = false;
1293    let owner = owner.encode();
1294    visit_index_components(entity, info, |index, values| {
1295        if list_link {
1296            check_component_framing(entity, index, values)?;
1297        }
1298        let suffix = if index.unique {
1299            &[][..]
1300        } else {
1301            owner.as_slice()
1302        };
1303        if INDEX_PREFIX_BYTES + values.len() + suffix.len() > crate::MAX_INDEX_KEY_BYTES {
1304            return Err(Error::Limit);
1305        }
1306        if !list_link && header[ENTITY_PREFIX_BYTES..] == index.id.to_be_bytes() {
1307            matches = payload.strip_prefix(values) == Some(suffix);
1308        }
1309
1310        Ok(())
1311    })?;
1312    if list_link {
1313        let index = u32::from_be_bytes(
1314            header[ENTITY_PREFIX_BYTES..]
1315                .try_into()
1316                .map_err(|_| Error::Corrupt)?,
1317        );
1318        let item = entity
1319            .fields
1320            .iter()
1321            .find_map(|field| match (field.reference, field.value) {
1322                (Some(reference), FieldType::List { item, .. }) if reference.index == index => {
1323                    Some(*item)
1324                }
1325                _ => None,
1326            })
1327            .ok_or(Error::Corrupt)?;
1328        // Both components are bounded primary keys. Decode the target once even
1329        // if the owner repeats a reference in its list.
1330        let target = RowKey::decode(
1331            payload
1332                .strip_suffix(owner.as_slice())
1333                .ok_or(Error::Corrupt)?,
1334            item,
1335        )?;
1336        matches = info.list_links.contains(&(index, target));
1337    }
1338    if !matches {
1339        return Err(Error::Corrupt);
1340    }
1341
1342    Ok(())
1343}