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