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