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