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        let mut index_runs = Vec::new();
758        for mut mutation in batch.mutations {
759            let direction = deleted.last().and_then(|&(entity, key)| {
760                (entity == mutation.entity.id && matches!(mutation.kind, Kind::Delete))
761                    .then(|| mutation.key < key)
762            });
763            if direction.is_none() {
764                index_runs.clear();
765            }
766            self.schema.admits(mutation.entity)?;
767            let key = row_key(mutation.entity.id, mutation.key);
768            if !targets.insert(key.clone()) {
769                return Err(Error::DuplicateTarget);
770            }
771            let old = self.map.get(&key);
772            match (&mutation.kind, &old) {
773                (Kind::Put(WriteMode::Insert, ..) | Kind::CopyInsert(..), Some(_)) => {
774                    return Err(Error::Exists);
775                }
776                (Kind::Put(WriteMode::Replace, ..), None) => return Err(Error::Missing),
777                (Kind::Delete, None) => continue,
778                _ => {}
779            }
780            if mutation.entity.has_managed() {
781                match &mut mutation.kind {
782                    Kind::Put(mode, bytes, info) => {
783                        if crate::managed::save(
784                            mutation.entity,
785                            bytes,
786                            old.as_deref(),
787                            *mode == WriteMode::Upsert,
788                            batch.operation_time.ok_or(Error::MissingOperationTime)?,
789                        )? {
790                            *info = mutation.entity.inspect_row(bytes)?;
791                        }
792                    }
793                    Kind::CopyInsert(bytes, _, expected) => {
794                        if crate::managed::values(mutation.entity, bytes)? != *expected {
795                            return Err(Error::ManagedField);
796                        }
797                    }
798                    Kind::Delete => {}
799                }
800            }
801            if let Kind::Put(_, bytes, _) = &mutation.kind
802                && let Some(selected) = returning
803                    .take_if(|row| row.entity == mutation.entity.id && row.key == mutation.key)
804            {
805                (selected.decode)(bytes)?;
806            }
807            // Admit complete after-image keys even when the row is a no-op.
808            // Retain these buffers for publication instead of encoding twice.
809            let mut after_indexes = match &mutation.kind {
810                Kind::Put(_, _, info) | Kind::CopyInsert(_, info, _) => {
811                    index_entries(mutation.entity, info)?
812                }
813                Kind::Delete => Vec::new(),
814            };
815            let (_, changed, delta) = match entities.entry(mutation.entity.id) {
816                std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
817                std::collections::btree_map::Entry::Vacant(entry) => entry.insert((
818                    read_entity_state(&self.map, mutation.entity.id)?,
819                    false,
820                    0_i64,
821                )),
822            };
823            if let (Kind::Put(_, bytes, _), Some(old)) = (&mutation.kind, &old)
824                && bytes == old
825            {
826                continue;
827            }
828            if let Some(old) = &old {
829                let info = mutation.entity.inspect_row(old)?;
830                if info.key != mutation.key {
831                    return Err(Error::Corrupt);
832                }
833                let owner = info.key.encode();
834                for (slot, (key, _)) in index_entries(mutation.entity, &info)?
835                    .into_iter()
836                    .enumerate()
837                {
838                    let value = if let Some(descending) = direction
839                        && key.first() == Some(&3)
840                    {
841                        read_adjacent_index(&self.map, &mut index_runs, slot, &key, descending)
842                    } else {
843                        self.map.get(&key)
844                    };
845                    if value.as_deref() != Some(owner.as_slice()) {
846                        return Err(Error::Corrupt);
847                    }
848
849                    // Same physical key and owner: leave the verified entry in place.
850                    // Its unique value remains occupied during final-state admission.
851                    if let Some(position) =
852                        after_indexes.iter().position(|(after, _)| *after == key)
853                    {
854                        after_indexes.remove(position);
855                    } else {
856                        removes.insert(key);
857                    }
858                }
859            }
860            *changed = true;
861            *delta += match &mutation.kind {
862                Kind::Put(..) | Kind::CopyInsert(..) => i64::from(old.is_none()),
863                Kind::Delete => -1,
864            };
865            // Private migration inserts may precede their targets. The frozen
866            // complete target validates references before it can be published.
867            let copy_insert = matches!(&mutation.kind, Kind::CopyInsert(..));
868
869            match mutation.kind {
870                Kind::Delete => {
871                    deleted.push((mutation.entity.id, mutation.key));
872                    removes.insert(key);
873                }
874                Kind::Put(_, bytes, info) | Kind::CopyInsert(bytes, info, _) => {
875                    writes.insert(key, bytes);
876                    for (key, is_unique) in after_indexes {
877                        if is_unique && !unique.insert(key.clone()) {
878                            return Err(Error::UniqueViolation);
879                        }
880                        writes.insert(key, info.key.encode());
881                    }
882                    if !copy_insert {
883                        collect_references(mutation.entity, &info, &mut required)?;
884                    }
885                }
886            }
887        }
888        drop(index_runs);
889        if returning.is_some() {
890            return Err(Error::Missing);
891        }
892        // Check existing owners only after all releases in this batch are known.
893        let mut skip_insert = false;
894        for key in unique {
895            if let Some((entity, _)) = conflict_target.filter(|(_, prefix)| key.starts_with(prefix))
896            {
897                if let Some(encoded) = self.map.get(&key) {
898                    let (owner, bytes) =
899                        read_index_owner(&self.map, entity.id, entity.key_type()?, &encoded)?;
900                    validate_index_entry(entity, &entity.inspect_row(&bytes)?, owner, &key)?;
901                    skip_insert = true;
902                }
903                continue;
904            }
905            if self.map.contains_key(&key) && !removes.contains(&key) {
906                return Err(Error::UniqueViolation);
907            }
908        }
909        if skip_insert {
910            // No candidate row will be published to satisfy its own references.
911            self.validate_references(&required, &deleted, &removes, &BTreeMap::new())?;
912            return Ok(false);
913        }
914        self.validate_references(&required, &deleted, &removes, &writes)?;
915        for (entity, (mut state, changed, delta)) in entities {
916            if changed {
917                state.revision = state.revision.checked_add(1).ok_or(Error::Limit)?;
918                state.count = if delta >= 0 {
919                    state.count.checked_add(delta as u64).ok_or(Error::Limit)?
920                } else {
921                    state
922                        .count
923                        .checked_sub((-delta) as u64)
924                        .ok_or(Error::Corrupt)?
925                };
926                writes.insert(entity_state_key(entity), state.encode());
927            }
928        }
929        // Proven IC rollback boundary: no recoverable Result branch below this line.
930        let expected = removes.len() as u64;
931        assert_eq!(
932            self.map.remove_many(removes),
933            expected,
934            "prepared removal set changed"
935        );
936        for (key, value) in writes {
937            self.map.insert(key, value);
938        }
939
940        Ok(true)
941    }
942
943    // Reuse the prepared final rows and ordinary index changes. No durable
944    // relationship catalog or second mutation executor is involved.
945    fn validate_references(
946        &self,
947        required: &BTreeSet<(u32, RowKey)>,
948        deleted: &[(u32, RowKey)],
949        removes: &BTreeSet<StoreKey>,
950        writes: &BTreeMap<StoreKey, Vec<u8>>,
951    ) -> Result<(), Error> {
952        for &(entity, id) in required {
953            let key = row_key(entity, id);
954            if writes.contains_key(&key) {
955                continue;
956            } // prepared, validated final target
957            if removes.contains(&key) {
958                return Err(Error::ReferenceViolation);
959            }
960            validate_reference_target(&self.map, &self.schema, entity, id)?;
961        }
962        // A lower-bound seek proves the gap before its first physical key is empty.
963        // Keep one such gap only for this immutable preparation pass.
964        let mut gap: Option<(StoreKey, Option<StoreKey>)> = None;
965        for &(target, id) in deleted {
966            for entity in self.schema.entities() {
967                for field in entity.fields {
968                    let Some(reference) = field.reference.filter(|value| value.entity == target)
969                    else {
970                        continue;
971                    };
972                    let prefix = if matches!(field.value, FieldType::List { .. }) {
973                        list_target_prefix(entity.id, reference.index, id)
974                    } else {
975                        let mut prefix = index_prefix(entity.id, reference.index);
976                        id.index_value()
977                            .append_component(field.optional, &mut prefix);
978                        prefix
979                    };
980                    let prefix = StoreKey::new(prefix)?;
981                    if let Some((start, next)) = &gap
982                        && start <= &prefix
983                        && next
984                            .as_ref()
985                            .is_none_or(|key| key > &prefix && !key.starts_with(&prefix))
986                    {
987                        continue;
988                    }
989                    // Each skipped entry belongs to a distinct changed row in
990                    // this range. At most MAX_BATCH skips plus one survivor.
991                    let mut entries = self.map.range(prefix.clone()..);
992                    for position in 0..=MAX_BATCH {
993                        let entry = match entries.next() {
994                            Some(entry) if entry.key().starts_with(&prefix) => entry,
995                            boundary => {
996                                if position == 0 && deleted.len() > 1 {
997                                    gap = Some((prefix, boundary.map(|entry| entry.key().clone())));
998                                }
999                                break;
1000                            }
1001                        };
1002                        if removes.contains(entry.key()) {
1003                            if position == MAX_BATCH {
1004                                return Err(Error::Corrupt);
1005                            }
1006                            continue;
1007                        }
1008                        let (owner, bytes) = read_index_owner(
1009                            &self.map,
1010                            entity.id,
1011                            entity.key_type()?,
1012                            &entry.value(),
1013                        )?;
1014                        let info = entity.inspect_row(&bytes)?;
1015                        validate_index_entry(entity, &info, owner, entry.key())?;
1016
1017                        return Err(Error::ReferenceViolation);
1018                    }
1019                }
1020            }
1021        }
1022
1023        Ok(())
1024    }
1025}
1026
1027// Probe at most one neighboring entry per expected secondary key. A gap or different order
1028// switches that slot to point reads for the rest of the same-entity delete run.
1029// Every successful probe checks the full key; the caller checks its stored owner.
1030fn read_adjacent_index<'a, M: Memory>(
1031    map: &'a Map<M>,
1032    runs: &mut Vec<Option<MapIter<'a, StoreKey, Vec<u8>, M>>>,
1033    slot: usize,
1034    key: &StoreKey,
1035    descending: bool,
1036) -> Option<Vec<u8>> {
1037    if slot == runs.len() {
1038        let entries = if descending {
1039            map.range(..=key.clone())
1040        } else {
1041            map.range(key.clone()..)
1042        };
1043        runs.push(Some(entries));
1044    }
1045    let run = &mut runs[slot];
1046    if let Some(entry) = run.as_mut().and_then(|entries| {
1047        if descending {
1048            entries.next_back()
1049        } else {
1050            entries.next()
1051        }
1052    }) && entry.key() == key
1053    {
1054        return Some(entry.value());
1055    }
1056    *run = None;
1057    map.get(key)
1058}
1059
1060// Physical key headers contain a namespace tag and fixed-width schema handles.
1061const ENTITY_PREFIX_BYTES: usize = 1 + size_of::<u32>();
1062const INDEX_PREFIX_BYTES: usize = ENTITY_PREFIX_BYTES + size_of::<u32>();
1063
1064fn prefix(tag: u8, entity: u32, suffix: &[u8]) -> Vec<u8> {
1065    let mut key = Vec::with_capacity(ENTITY_PREFIX_BYTES + suffix.len());
1066    key.push(tag);
1067    key.extend_from_slice(&entity.to_be_bytes());
1068    key.extend_from_slice(suffix);
1069
1070    key
1071}
1072
1073fn entity_state_key(entity: u32) -> StoreKey {
1074    StoreKey::new(prefix(1, entity, &[])).expect("entity state key fits")
1075}
1076
1077fn read_revision<M: Memory>(map: &Map<M>, entity: u32) -> Result<u64, Error> {
1078    Ok(read_entity_state(map, entity)?.revision)
1079}
1080
1081/// One atomic metadata record; neither value is reconstructed during ordinary open.
1082#[derive(Default)]
1083struct EntityState {
1084    revision: u64,
1085    count: u64,
1086}
1087impl EntityState {
1088    fn encode(&self) -> Vec<u8> {
1089        let mut bytes = self.revision.to_le_bytes().to_vec();
1090        bytes.extend(self.count.to_le_bytes());
1091
1092        bytes
1093    }
1094}
1095fn read_entity_state<M: Memory>(map: &Map<M>, entity: u32) -> Result<EntityState, Error> {
1096    let bytes = map.get(&entity_state_key(entity)).ok_or(Error::Corrupt)?;
1097    let (revision, count) = bytes.split_first_chunk::<8>().ok_or(Error::Corrupt)?;
1098    let revision = u64::from_le_bytes(*revision);
1099    let count = u64::from_le_bytes(count.try_into().map_err(|_| Error::Corrupt)?);
1100    // The first insertion advances the revision in the same batch.
1101    if revision == 0 && count != 0 {
1102        return Err(Error::Corrupt);
1103    }
1104
1105    Ok(EntityState { revision, count })
1106}
1107
1108fn row_key(entity: u32, id: RowKey) -> StoreKey {
1109    let mut key = prefix(2, entity, &[]);
1110    id.append_to(&mut key);
1111
1112    StoreKey::new(key).expect("bounded primary key fits")
1113}
1114
1115fn index_prefix(entity: u32, index: u32) -> Vec<u8> {
1116    prefix(3, entity, &index.to_be_bytes())
1117}
1118// One entry per distinct target of a list field, suffixed by its owner key.
1119fn list_target_prefix(entity: u32, field: u32, target: RowKey) -> Vec<u8> {
1120    let mut key = prefix(4, entity, &field.to_be_bytes());
1121    target.append_to(&mut key);
1122    key
1123}
1124
1125// Direct lookups and fluent reads share exact prefix admission and completion bounds.
1126fn admit_index_prefix(
1127    entity: &EntitySchema,
1128    index: &crate::IndexSchema,
1129    values: &[IndexValue<'_>],
1130) -> Result<Vec<u8>, Error> {
1131    if values.len() > index.fields.len() {
1132        return Err(Error::Limit);
1133    }
1134    let mut prefix = index_prefix(entity.id, index.id);
1135    for (value, name) in values.iter().zip(index.fields) {
1136        let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1137        value.admit(field.value, field.optional)?;
1138        if index.present_only && *value == IndexValue::Absent {
1139            return Err(Error::InvalidOperand);
1140        }
1141        value.append_component(field.optional, &mut prefix);
1142        if prefix.len() > crate::MAX_INDEX_KEY_BYTES {
1143            return Err(Error::Limit);
1144        }
1145    }
1146    let mut completion = if index.unique {
1147        0
1148    } else {
1149        key::minimum_bytes(entity.key_type()?)?
1150    };
1151    for name in &index.fields[values.len()..] {
1152        let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1153        completion += if field.optional && !index.present_only {
1154            1
1155        } else {
1156            key::minimum_bytes(field.value)? + usize::from(field.optional)
1157        };
1158    }
1159    if prefix.len() + completion > crate::MAX_INDEX_KEY_BYTES {
1160        return Err(Error::Limit);
1161    }
1162
1163    Ok(prefix)
1164}
1165// RowInfo may come from a generated entity or the shared stored-row decoder.
1166fn visit_index_components(
1167    entity: &EntitySchema,
1168    info: &RowInfo,
1169    mut visit: impl FnMut(&crate::IndexSchema, &[u8]) -> Result<(), Error>,
1170) -> Result<(), Error> {
1171    if info.indexes.len() != entity.indexes.len() {
1172        return Err(Error::Corrupt);
1173    }
1174    for (index, values) in entity.indexes.iter().zip(&info.indexes) {
1175        let Some(values) = values else {
1176            if index.present_only {
1177                continue;
1178            }
1179
1180            return Err(Error::Corrupt);
1181        };
1182        let mut remaining = values.as_slice();
1183        for name in index.fields {
1184            let field = entity.index_field(name).ok_or(Error::Corrupt)?;
1185            key::consume_component(&mut remaining, field, index.present_only, Error::Corrupt)?;
1186        }
1187        if !remaining.is_empty() {
1188            return Err(Error::Corrupt);
1189        }
1190        visit(index, values)?;
1191    }
1192
1193    Ok(())
1194}
1195
1196fn index_entries(entity: &EntitySchema, info: &RowInfo) -> Result<Vec<(StoreKey, bool)>, Error> {
1197    let mut entries = Vec::new();
1198    visit_index_components(entity, info, |index, values| {
1199        let mut key = index_prefix(entity.id, index.id);
1200        key.extend_from_slice(values);
1201        if !index.unique {
1202            info.key.append_to(&mut key);
1203        }
1204        entries.push((StoreKey::new(key)?, index.unique));
1205
1206        Ok(())
1207    })?;
1208
1209    let mut links = BTreeSet::new();
1210    for &(field, target) in &info.list_links {
1211        if links.insert((field, target)) {
1212            let mut key = list_target_prefix(entity.id, field, target);
1213            info.key.append_to(&mut key);
1214            entries.push((StoreKey::new(key)?, false));
1215        }
1216    }
1217    Ok(entries)
1218}
1219
1220// A visited entry must agree with its owner in namespace, components and suffix.
1221// Unrelated entries retain their framing and size checks without building physical keys.
1222fn validate_index_entry(
1223    entity: &EntitySchema,
1224    info: &RowInfo,
1225    owner: RowKey,
1226    key: &[u8],
1227) -> Result<(), Error> {
1228    if info.key != owner {
1229        return Err(Error::Corrupt);
1230    }
1231    if key.first() == Some(&4) {
1232        return index_entries(entity, info)?
1233            .iter()
1234            .any(|(entry, _)| entry.as_ref() == key)
1235            .then_some(())
1236            .ok_or(Error::Corrupt);
1237    }
1238    let (header, payload) = key
1239        .split_at_checked(INDEX_PREFIX_BYTES)
1240        .ok_or(Error::Corrupt)?;
1241    if header[0] != 3 || header[1..ENTITY_PREFIX_BYTES] != entity.id.to_be_bytes() {
1242        return Err(Error::Corrupt);
1243    }
1244    let mut matches = false;
1245    let owner = owner.encode();
1246    visit_index_components(entity, info, |index, values| {
1247        let suffix = if index.unique {
1248            &[][..]
1249        } else {
1250            owner.as_slice()
1251        };
1252        if INDEX_PREFIX_BYTES + values.len() + suffix.len() > crate::MAX_INDEX_KEY_BYTES {
1253            return Err(Error::Limit);
1254        }
1255        if header[ENTITY_PREFIX_BYTES..] == index.id.to_be_bytes() {
1256            matches = payload.strip_prefix(values) == Some(suffix);
1257        }
1258
1259        Ok(())
1260    })?;
1261    if !matches {
1262        return Err(Error::Corrupt);
1263    }
1264
1265    Ok(())
1266}