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