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