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