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        let mut targets = BTreeSet::new();
571        let mut removes = BTreeSet::new();
572        let mut writes = BTreeMap::new();
573        let mut unique = BTreeSet::new();
574        // Observe each entity once, then apply its final net row delta. A balanced
575        // delete/insert batch must not depend on mutation order. No state survives calls.
576        let mut entities = BTreeMap::new();
577        let mut required = BTreeSet::new();
578        let mut deleted = Vec::new();
579        for mut mutation in batch.mutations {
580            self.schema.admits(mutation.entity)?;
581            let key = row_key(mutation.entity.id, mutation.key);
582            if !targets.insert(key.clone()) {
583                return Err(Error::DuplicateTarget);
584            }
585            let old = self.map.get(&key);
586            match (&mutation.kind, &old) {
587                (Kind::Insert(..) | Kind::CopyInsert(..), Some(_)) => return Err(Error::Exists),
588                (Kind::Replace(..) | Kind::Delete, None) => return Err(Error::Missing),
589                _ => {}
590            }
591            if mutation.entity.has_managed() {
592                match &mut mutation.kind {
593                    Kind::Insert(bytes, _) => crate::managed::validate_insert(
594                        mutation.entity,
595                        bytes,
596                        batch.operation_time.ok_or(Error::MissingOperationTime)?,
597                    )?,
598                    Kind::Replace(bytes, info) => {
599                        if crate::managed::replace(
600                            mutation.entity,
601                            bytes,
602                            old.as_deref().ok_or(Error::Missing)?,
603                            batch.operation_time.ok_or(Error::MissingOperationTime)?,
604                        )? {
605                            *info = mutation.entity.inspect_row(bytes)?;
606                        }
607                    }
608                    Kind::CopyInsert(bytes, _, expected) => {
609                        if crate::managed::values(mutation.entity, bytes)? != *expected {
610                            return Err(Error::ManagedField);
611                        }
612                    }
613                    Kind::Delete => {}
614                }
615            }
616            // Admit complete after-image keys even when the row is a no-op.
617            // Retain these buffers for publication instead of encoding twice.
618            let mut after_indexes = match &mutation.kind {
619                Kind::Insert(_, info) | Kind::CopyInsert(_, info, _) | Kind::Replace(_, info) => {
620                    index_entries(mutation.entity, info)?
621                }
622                Kind::Delete => Vec::new(),
623            };
624            let (_, changed, delta) = match entities.entry(mutation.entity.id) {
625                std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
626                std::collections::btree_map::Entry::Vacant(entry) => entry.insert((
627                    read_entity_state(&self.map, mutation.entity.id)?,
628                    false,
629                    0_i64,
630                )),
631            };
632            if let (Kind::Replace(bytes, _), Some(old)) = (&mutation.kind, &old)
633                && bytes == old
634            {
635                continue;
636            }
637            if let Some(old) = old {
638                let info = mutation.entity.inspect_row(&old)?;
639                if info.key != mutation.key {
640                    return Err(Error::Corrupt);
641                }
642                let owner = info.key.encode();
643                for (key, _) in index_entries(mutation.entity, &info)? {
644                    if self.map.get(&key).as_deref() != Some(owner.as_slice()) {
645                        return Err(Error::Corrupt);
646                    }
647
648                    // Same physical key and owner: leave the verified entry in place.
649                    // Its unique value remains occupied during final-state admission.
650                    if let Some(position) =
651                        after_indexes.iter().position(|(after, _)| *after == key)
652                    {
653                        after_indexes.remove(position);
654                    } else {
655                        removes.insert(key);
656                    }
657                }
658            }
659            *changed = true;
660            *delta += match &mutation.kind {
661                Kind::Insert(..) | Kind::CopyInsert(..) => 1,
662                Kind::Delete => -1,
663                Kind::Replace(..) => 0,
664            };
665            // Private migration inserts may precede their targets. The frozen
666            // complete target validates references before it can be published.
667            let copy_insert = matches!(&mutation.kind, Kind::CopyInsert(..));
668
669            match mutation.kind {
670                Kind::Delete => {
671                    deleted.push((mutation.entity.id, mutation.key));
672                    removes.insert(key);
673                }
674                Kind::Insert(bytes, info)
675                | Kind::CopyInsert(bytes, info, _)
676                | Kind::Replace(bytes, info) => {
677                    writes.insert(key, bytes);
678                    for (key, is_unique) in after_indexes {
679                        if is_unique && !unique.insert(key.clone()) {
680                            return Err(Error::UniqueViolation);
681                        }
682                        writes.insert(key, info.key.encode());
683                    }
684                    if !copy_insert {
685                        collect_references(mutation.entity, &info, &mut required)?;
686                    }
687                }
688            }
689        }
690        // Check existing owners only after all releases in this batch are known.
691        for key in unique {
692            if self.map.contains_key(&key) && !removes.contains(&key) {
693                return Err(Error::UniqueViolation);
694            }
695        }
696        self.validate_references(&required, &deleted, &removes, &writes)?;
697        for (entity, (mut state, changed, delta)) in entities {
698            if changed {
699                state.revision = state.revision.checked_add(1).ok_or(Error::Limit)?;
700                state.count = if delta >= 0 {
701                    state.count.checked_add(delta as u64).ok_or(Error::Limit)?
702                } else {
703                    state
704                        .count
705                        .checked_sub((-delta) as u64)
706                        .ok_or(Error::Corrupt)?
707                };
708                writes.insert(entity_state_key(entity), state.encode());
709            }
710        }
711        // Proven IC rollback boundary: no recoverable Result branch below this line.
712        for key in removes {
713            self.map.remove(&key);
714        }
715        for (key, value) in writes {
716            self.map.insert(key, value);
717        }
718
719        Ok(())
720    }
721
722    // Reuse the prepared final rows and ordinary index changes. No durable
723    // relationship catalog or second mutation executor is involved.
724    fn validate_references(
725        &self,
726        required: &BTreeSet<(u32, RowKey)>,
727        deleted: &[(u32, RowKey)],
728        removes: &BTreeSet<StoreKey>,
729        writes: &BTreeMap<StoreKey, Vec<u8>>,
730    ) -> Result<(), Error> {
731        for &(entity, id) in required {
732            let key = row_key(entity, id);
733            if writes.contains_key(&key) {
734                continue;
735            } // prepared, validated final target
736            if removes.contains(&key) {
737                return Err(Error::ReferenceViolation);
738            }
739            validate_reference_target(&self.map, &self.schema, entity, id)?;
740        }
741        for &(target, id) in deleted {
742            for entity in self.schema.entities() {
743                for field in entity.fields {
744                    let Some(reference) = field.reference.filter(|value| value.entity == target)
745                    else {
746                        continue;
747                    };
748                    let mut prefix = index_prefix(entity.id, reference.index);
749                    id.index_value()
750                        .append_component(field.optional, &mut prefix);
751                    let prefix = StoreKey::new(prefix)?;
752                    // Each skipped entry belongs to a distinct changed row in
753                    // this range. At most MAX_BATCH skips plus one survivor.
754                    for (position, entry) in self
755                        .map
756                        .range(prefix.clone()..)
757                        .take_while(|entry| entry.key().starts_with(&prefix))
758                        .take(MAX_BATCH + 1)
759                        .enumerate()
760                    {
761                        if removes.contains(entry.key()) {
762                            if position == MAX_BATCH {
763                                return Err(Error::Corrupt);
764                            }
765                            continue;
766                        }
767                        let owner = RowKey::decode(&entry.value(), entity.key_type()?)?;
768                        let bytes = self
769                            .map
770                            .get(&row_key(entity.id, owner))
771                            .ok_or(Error::Corrupt)?;
772                        let info = entity.inspect_row(&bytes)?;
773                        validate_index_entry(entity, &info, owner, entry.key())?;
774
775                        return Err(Error::ReferenceViolation);
776                    }
777                }
778            }
779        }
780
781        Ok(())
782    }
783}
784
785// Physical key headers contain a namespace tag and fixed-width schema handles.
786const ENTITY_PREFIX_BYTES: usize = 1 + size_of::<u32>();
787const INDEX_PREFIX_BYTES: usize = ENTITY_PREFIX_BYTES + size_of::<u32>();
788
789fn prefix(tag: u8, entity: u32) -> Vec<u8> {
790    let mut key = vec![tag];
791    key.extend(entity.to_be_bytes());
792
793    key
794}
795
796fn entity_state_key(entity: u32) -> StoreKey {
797    StoreKey::new(prefix(1, entity)).expect("entity state key fits")
798}
799
800fn read_revision<M: Memory>(map: &Map<M>, entity: u32) -> Result<u64, Error> {
801    Ok(read_entity_state(map, entity)?.revision)
802}
803
804/// One atomic metadata record; neither value is reconstructed during ordinary open.
805#[derive(Default)]
806struct EntityState {
807    revision: u64,
808    count: u64,
809}
810impl EntityState {
811    fn encode(&self) -> Vec<u8> {
812        let mut bytes = self.revision.to_le_bytes().to_vec();
813        bytes.extend(self.count.to_le_bytes());
814
815        bytes
816    }
817}
818fn read_entity_state<M: Memory>(map: &Map<M>, entity: u32) -> Result<EntityState, Error> {
819    let bytes = map.get(&entity_state_key(entity)).ok_or(Error::Corrupt)?;
820    let (revision, count) = bytes.split_first_chunk::<8>().ok_or(Error::Corrupt)?;
821    let revision = u64::from_le_bytes(*revision);
822    let count = u64::from_le_bytes(count.try_into().map_err(|_| Error::Corrupt)?);
823    // The first insertion advances the revision in the same batch.
824    if revision == 0 && count != 0 {
825        return Err(Error::Corrupt);
826    }
827
828    Ok(EntityState { revision, count })
829}
830
831fn row_key(entity: u32, id: RowKey) -> StoreKey {
832    let mut key = prefix(2, entity);
833    id.append_to(&mut key);
834
835    StoreKey::new(key).expect("bounded primary key fits")
836}
837
838fn index_prefix(entity: u32, index: u32) -> Vec<u8> {
839    let mut key = prefix(3, entity);
840    key.extend(index.to_be_bytes());
841
842    key
843}
844// Direct lookups and fluent reads share exact prefix admission and completion bounds.
845fn admit_index_prefix(
846    entity: &EntitySchema,
847    index: &crate::IndexSchema,
848    values: &[IndexValue<'_>],
849) -> Result<Vec<u8>, Error> {
850    if values.len() > index.fields.len() {
851        return Err(Error::Limit);
852    }
853    let mut prefix = index_prefix(entity.id, index.id);
854    for (value, name) in values.iter().zip(index.fields) {
855        let field = entity.field_by_name(name).ok_or(Error::InvalidSchema)?;
856        value.admit(field.value, field.optional)?;
857        if index.present_only && *value == IndexValue::Absent {
858            return Err(Error::InvalidOperand);
859        }
860        value.append_component(field.optional, &mut prefix);
861        if prefix.len() > crate::MAX_INDEX_KEY_BYTES {
862            return Err(Error::Limit);
863        }
864    }
865    let mut completion = if index.unique {
866        0
867    } else {
868        key::minimum_bytes(entity.key_type()?)?
869    };
870    for name in &index.fields[values.len()..] {
871        let field = entity.field_by_name(name).ok_or(Error::InvalidSchema)?;
872        completion += if field.optional && !index.present_only {
873            1
874        } else {
875            key::minimum_bytes(field.value)? + usize::from(field.optional)
876        };
877    }
878    if prefix.len() + completion > crate::MAX_INDEX_KEY_BYTES {
879        return Err(Error::Limit);
880    }
881
882    Ok(prefix)
883}
884// RowInfo may come from a generated entity or the shared stored-row decoder.
885fn visit_index_components(
886    entity: &EntitySchema,
887    info: &RowInfo,
888    mut visit: impl FnMut(&crate::IndexSchema, &[u8]) -> Result<(), Error>,
889) -> Result<(), Error> {
890    if info.indexes.len() != entity.indexes.len() {
891        return Err(Error::Corrupt);
892    }
893    for (index, values) in entity.indexes.iter().zip(&info.indexes) {
894        let Some(values) = values else {
895            if index.present_only {
896                continue;
897            }
898
899            return Err(Error::Corrupt);
900        };
901        let mut remaining = values.as_slice();
902        for name in index.fields {
903            let field = entity.field_by_name(name).ok_or(Error::Corrupt)?;
904            key::consume_component(&mut remaining, field, index.present_only, Error::Corrupt)?;
905        }
906        if !remaining.is_empty() {
907            return Err(Error::Corrupt);
908        }
909        visit(index, values)?;
910    }
911
912    Ok(())
913}
914
915fn index_entries(entity: &EntitySchema, info: &RowInfo) -> Result<Vec<(StoreKey, bool)>, Error> {
916    let mut entries = Vec::new();
917    visit_index_components(entity, info, |index, values| {
918        let mut key = index_prefix(entity.id, index.id);
919        key.extend_from_slice(values);
920        if !index.unique {
921            info.key.append_to(&mut key);
922        }
923        entries.push((StoreKey::new(key)?, index.unique));
924
925        Ok(())
926    })?;
927
928    Ok(entries)
929}
930
931// A visited entry must agree with its owner in namespace, components and suffix.
932// Unrelated entries retain their framing and size checks without building physical keys.
933fn validate_index_entry(
934    entity: &EntitySchema,
935    info: &RowInfo,
936    owner: RowKey,
937    key: &[u8],
938) -> Result<(), Error> {
939    if info.key != owner {
940        return Err(Error::Corrupt);
941    }
942    let (header, payload) = key
943        .split_at_checked(INDEX_PREFIX_BYTES)
944        .ok_or(Error::Corrupt)?;
945    if header[0] != 3 || header[1..ENTITY_PREFIX_BYTES] != entity.id.to_be_bytes() {
946        return Err(Error::Corrupt);
947    }
948    let mut matches = false;
949    let owner = owner.encode();
950    visit_index_components(entity, info, |index, values| {
951        let suffix = if index.unique {
952            &[][..]
953        } else {
954            owner.as_slice()
955        };
956        if INDEX_PREFIX_BYTES + values.len() + suffix.len() > crate::MAX_INDEX_KEY_BYTES {
957            return Err(Error::Limit);
958        }
959        if header[ENTITY_PREFIX_BYTES..] == index.id.to_be_bytes() {
960            matches = payload.strip_prefix(values) == Some(suffix);
961        }
962
963        Ok(())
964    })?;
965    if !matches {
966        return Err(Error::Corrupt);
967    }
968
969    Ok(())
970}