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