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