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