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