Skip to main content

ic_db/store/
mod.rs

1//! Shared commit and traversal over one supplier-owned collection.
2//! Typed codecs stay at the boundary; no executor is generated per entity.
3
4mod maintenance;
5mod query;
6
7use crate::{
8    __private::RowInfo, Entity, EntitySchema, Error, FieldType, IndexValue, PrimaryKey, Schema,
9    UniqueKey, key, primary::RowKey, store_key::StoreKey,
10};
11use ic_storage::{
12    Memory, RuntimeMemory,
13    adapter::{MapIter, StableBTreeMap},
14};
15pub use maintenance::{
16    CopyStatus, CopyStep, Maintenance, RetiredSource, SchemaCopy, SchemaTransition,
17};
18pub use query::{
19    Aggregate, AggregateJobs, Column, Comparison, GetMany, GroupCount, GroupCursor, GroupOrder,
20    GroupPage, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue, JobHandle, JobOutcome,
21    JobStep, Query, QueryCursor, QueryOperand, QueryPage, SelectColumns, SelectedGetMany,
22    SelectedQuery, Selection, SortDirection, SummaryMeasure,
23};
24use std::collections::{BTreeMap, BTreeSet};
25
26const MANIFEST: &[u8] = b"ICDBMF02";
27const MAX_BATCH: usize = 32;
28const MAX_BATCH_BYTES: usize = 128 * 1024;
29type Map<M> = StableBTreeMap<StoreKey, Vec<u8>, M>;
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    // Share grouping and storage reads across raw/branded keys and result shapes.
507    #[inline(never)]
508    fn get_many_typed<K: PrimaryKey, R>(
509        &self,
510        entity: &EntitySchema,
511        keys: &[K],
512        decode: impl Fn(&EntitySchema, K, &[u8]) -> Result<R, Error>,
513    ) -> Result<Vec<Option<R>>, Error> {
514        let mut rows: Vec<_> = (0..keys.len()).map(|_| None).collect();
515        let mut handled = 0_u32;
516        for (i, &key) in keys.iter().enumerate() {
517            if handled & (1 << i) != 0 {
518                continue;
519            }
520            let bytes = self.map.get(&row_key(entity.id, key.into_row_key()));
521            for (j, &other) in keys.iter().enumerate().skip(i) {
522                if other == key {
523                    handled |= 1 << j;
524                    if let Some(bytes) = &bytes {
525                        rows[j] = Some(decode(entity, key, bytes)?);
526                    }
527                }
528            }
529        }
530
531        Ok(rows)
532    }
533
534    // Keep traversal separate from the static type's admission call. Passing
535    // its admitted descriptor lets compatible typed readers share machine code.
536    #[inline(never)]
537    fn get_typed<E: Entity>(&self, entity: &EntitySchema, key: E::Key) -> Result<Option<E>, Error> {
538        self.map
539            .get(&row_key(entity.id, key.into_row_key()))
540            .map(|bytes| decode_primary::<E>(&bytes, key))
541            .transpose()
542    }
543
544    /// Read at most 32 rows in primary-key order; continuation is live, not a snapshot.
545    /// # Errors
546    /// Refuses zero/oversized limits, unadmitted types or corrupt rows.
547    /// # Panics
548    /// Supplier corruption, including overlong stored keys, traps without repair.
549    #[inline]
550    pub fn page<E: Entity>(&self, after: Option<E::Key>, limit: usize) -> Result<Page<E>, Error> {
551        let entity = self.schema.admits(E::SCHEMA)?;
552
553        self.page_typed::<E>(entity, after, limit)
554    }
555
556    #[inline(never)]
557    fn page_typed<E: Entity>(
558        &self,
559        entity: &EntitySchema,
560        after: Option<E::Key>,
561        limit: usize,
562    ) -> Result<Page<E>, Error> {
563        if !(1..=32).contains(&limit) {
564            return Err(Error::Limit);
565        }
566        let prefix = prefix(2, entity.id, &[]);
567        let start = after.map_or_else(
568            || StoreKey::new(prefix.clone()).expect("row namespace fits"),
569            |key| row_key(entity.id, key.into_row_key()),
570        );
571        let lower = if after.is_some() {
572            std::ops::Bound::Excluded(start)
573        } else {
574            std::ops::Bound::Included(start)
575        };
576        let mut entries = self.map.range((lower, std::ops::Bound::Unbounded));
577        let key_type = entity.key_type()?;
578        let mut rows = Vec::new();
579        let mut last = None;
580        for _ in 0..limit {
581            let Some((id, bytes)) = next_primary(&mut entries, &prefix, key_type)? else {
582                break;
583            };
584            let id = E::Key::from_row_key(id)?;
585            rows.push(decode_primary::<E>(&bytes, id)?);
586            last = Some(id);
587        }
588
589        // Look ahead only on a full page. The next row is decoded on its own page.
590        let more = rows.len() == limit
591            && entries
592                .next()
593                .is_some_and(|entry| entry.key().starts_with(&prefix));
594        Ok(Page {
595            next_after: if more { last } else { None },
596            rows,
597        })
598    }
599
600    /// Read the first bounded collection under an exact, nonempty leading index prefix.
601    /// Exact operands obey field bounds and the 512-byte complete-key budget.
602    /// Use `IndexValue::Absent` for an absent optional component. A present-only
603    /// unique index refuses absent operands because it does not enumerate those rows.
604    /// # Errors
605    /// Refuses unknown indexes, mismatched operand types, invalid prefix/limit or
606    /// inconsistent index entries. This method does not yet return continuation.
607    #[inline]
608    pub fn index_prefix<E: Entity>(
609        &self,
610        index: &str,
611        values: &[IndexValue<'_>],
612        limit: usize,
613    ) -> Result<Vec<E>, Error> {
614        let entity = self.schema.admits(E::SCHEMA)?;
615
616        self.index_prefix_typed::<E>(entity, index, values, limit)
617    }
618
619    #[inline(never)]
620    fn index_prefix_typed<E: Entity>(
621        &self,
622        entity: &EntitySchema,
623        index: &str,
624        values: &[IndexValue<'_>],
625        limit: usize,
626    ) -> Result<Vec<E>, Error> {
627        let prefix = index_prefix_key(entity, index, values, limit)?;
628        let mut rows = Vec::new();
629        let mut entries = self.map.range(prefix.clone()..);
630        let key_type = entity.key_type()?;
631        for _ in 0..limit {
632            let Some((key, id, bytes)) =
633                next_index(&self.map, &mut entries, &prefix, entity.id, key_type)?
634            else {
635                break;
636            };
637            let row = E::decode(&bytes)?;
638            validate_index_entry(entity, &row.__row_info(), id, &key)?;
639            rows.push(row);
640        }
641
642        Ok(rows)
643    }
644
645    /// Prepare final state, then synchronously apply rows, indexes, revisions and counts.
646    /// A normal refusal occurs before persistent writes. Success is not a separate
647    /// durability point from the surrounding IC message. Empty/no-op batches preserve revisions.
648    /// # Errors
649    /// Refuses missing/existing rows, duplicate targets, uniqueness/reference violations,
650    /// corruption or limits. References use the intended final batch state.
651    /// # Panics
652    /// Supplier failures after the first mutation trap; never catch and continue an IC commit.
653    pub fn commit(&mut self, batch: Batch) -> Result<(), Error> {
654        observe!(commit, { self.commit_batch(batch, None, None).map(|_| ()) })
655    }
656
657    /// Insert or replace one row by primary key and return its stored value.
658    /// # Errors
659    /// Propagates batch preparation and commit errors, including unique conflicts.
660    /// # Panics
661    /// Supplier failures during publication trap as in [`Self::commit`].
662    pub fn upsert<E: Entity>(&mut self, row: &E) -> Result<E, Error> {
663        let mut batch = Batch::new();
664        batch.upsert(row)?;
665        self.commit_returning(batch, row.id())
666    }
667
668    /// Commit the whole batch and return the selected insert or replacement,
669    /// including its final managed timestamps. The row is decoded during preparation.
670    /// # Errors
671    /// Returns [`Error::Missing`] if the batch has no insert or replacement for
672    /// this entity and key. All ordinary [`Self::commit`] refusals apply.
673    /// # Panics
674    /// Supplier failures during publication trap as in [`Self::commit`].
675    pub fn commit_returning<E: Entity>(
676        &mut self,
677        batch: Batch,
678        key: impl Into<crate::Id<E>>,
679    ) -> Result<E, Error> {
680        observe!(commit, {
681            self.schema.admits(E::SCHEMA)?;
682            let mut row = None;
683            let selected = ReturningRow {
684                entity: E::SCHEMA.id,
685                key: key.into().key().into_row_key(),
686                decode: &mut |bytes| {
687                    row = Some(E::decode(bytes)?);
688                    Ok(())
689                },
690            };
691            self.commit_batch(batch, Some(selected), None)?;
692            Ok(row.expect("commit validated the selected row before publication"))
693        })
694    }
695
696    pub(crate) fn insert_if_absent<K: UniqueKey>(
697        &mut self,
698        input: impl crate::InsertInput<Entity = K::Entity>,
699    ) -> Result<crate::InsertOutcome<K::Entity>, Error> {
700        let entity = K::Entity::SCHEMA;
701        let index = entity
702            .index_by_name(K::INDEX)
703            .filter(|i| i.unique)
704            .ok_or(Error::InvalidQuery)?;
705        let mut batch = Batch::new();
706        let row = batch.insert_input(input)?;
707        let prefix = index_prefix(entity.id, index.id);
708        let applied = observe!(commit, {
709            self.commit_batch(batch, None, Some((entity, &prefix)))
710        })?;
711        Ok(if applied {
712            crate::InsertOutcome::Inserted(row)
713        } else {
714            crate::InsertOutcome::AlreadyPresent
715        })
716    }
717
718    // False means the single conditional insert was validated and skipped.
719    fn commit_batch(
720        &mut self,
721        batch: Batch,
722        mut returning: Option<ReturningRow<'_>>,
723        conflict_target: Option<(&EntitySchema, &[u8])>,
724    ) -> Result<bool, Error> {
725        let mut targets = BTreeSet::new();
726        let mut removes = BTreeSet::new();
727        let mut writes = BTreeMap::new();
728        let mut unique = BTreeSet::new();
729        // Observe each entity once, then apply its final net row delta. A balanced
730        // delete/insert batch must not depend on mutation order. No state survives calls.
731        let mut entities = BTreeMap::new();
732        let mut required = BTreeSet::new();
733        let mut deleted = Vec::new();
734        let mut index_runs = Vec::new();
735        for mut mutation in batch.mutations {
736            let direction = deleted.last().and_then(|&(entity, key)| {
737                (entity == mutation.entity.id && matches!(mutation.kind, Kind::Delete))
738                    .then(|| mutation.key < key)
739            });
740            if direction.is_none() {
741                index_runs.clear();
742            }
743            self.schema.admits(mutation.entity)?;
744            let key = row_key(mutation.entity.id, mutation.key);
745            if !targets.insert(key.clone()) {
746                return Err(Error::DuplicateTarget);
747            }
748            let old = self.map.get(&key);
749            match (&mutation.kind, &old) {
750                (Kind::Put(WriteMode::Insert, ..) | Kind::CopyInsert(..), Some(_)) => {
751                    return Err(Error::Exists);
752                }
753                (Kind::Put(WriteMode::Replace, ..), None) => return Err(Error::Missing),
754                (Kind::Delete, None) => continue,
755                _ => {}
756            }
757            if mutation.entity.has_managed() {
758                match &mut mutation.kind {
759                    Kind::Put(mode, bytes, info) => {
760                        if crate::managed::save(
761                            mutation.entity,
762                            bytes,
763                            old.as_deref(),
764                            *mode == WriteMode::Upsert,
765                            batch.operation_time.ok_or(Error::MissingOperationTime)?,
766                        )? {
767                            *info = mutation.entity.inspect_row(bytes)?;
768                        }
769                    }
770                    Kind::CopyInsert(bytes, _, expected) => {
771                        if crate::managed::values(mutation.entity, bytes)? != *expected {
772                            return Err(Error::ManagedField);
773                        }
774                    }
775                    Kind::Delete => {}
776                }
777            }
778            if let Kind::Put(_, bytes, _) = &mutation.kind
779                && let Some(selected) = returning
780                    .take_if(|row| row.entity == mutation.entity.id && row.key == mutation.key)
781            {
782                (selected.decode)(bytes)?;
783            }
784            // Admit complete after-image keys even when the row is a no-op.
785            // Retain these buffers for publication instead of encoding twice.
786            let mut after_indexes = match &mutation.kind {
787                Kind::Put(_, _, info) | Kind::CopyInsert(_, info, _) => {
788                    index_entries(mutation.entity, info)?
789                }
790                Kind::Delete => Vec::new(),
791            };
792            let (_, changed, delta) = match entities.entry(mutation.entity.id) {
793                std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
794                std::collections::btree_map::Entry::Vacant(entry) => entry.insert((
795                    read_entity_state(&self.map, mutation.entity.id)?,
796                    false,
797                    0_i64,
798                )),
799            };
800            if let (Kind::Put(_, bytes, _), Some(old)) = (&mutation.kind, &old)
801                && bytes == old
802            {
803                continue;
804            }
805            if let Some(old) = &old {
806                let info = mutation.entity.inspect_row(old)?;
807                if info.key != mutation.key {
808                    return Err(Error::Corrupt);
809                }
810                let owner = info.key.encode();
811                for (slot, (key, _)) in index_entries(mutation.entity, &info)?
812                    .into_iter()
813                    .enumerate()
814                {
815                    let value = if let Some(descending) = direction
816                        && key.first() == Some(&3)
817                    {
818                        read_adjacent_index(&self.map, &mut index_runs, slot, &key, descending)
819                    } else {
820                        self.map.get(&key)
821                    };
822                    if value.as_deref() != Some(owner.as_slice()) {
823                        return Err(Error::Corrupt);
824                    }
825
826                    // Same physical key and owner: leave the verified entry in place.
827                    // Its unique value remains occupied during final-state admission.
828                    if let Some(position) =
829                        after_indexes.iter().position(|(after, _)| *after == key)
830                    {
831                        after_indexes.remove(position);
832                    } else {
833                        removes.insert(key);
834                    }
835                }
836            }
837            *changed = true;
838            *delta += match &mutation.kind {
839                Kind::Put(..) | Kind::CopyInsert(..) => i64::from(old.is_none()),
840                Kind::Delete => -1,
841            };
842            // Private migration inserts may precede their targets. The frozen
843            // complete target validates references before it can be published.
844            let copy_insert = matches!(&mutation.kind, Kind::CopyInsert(..));
845
846            match mutation.kind {
847                Kind::Delete => {
848                    deleted.push((mutation.entity.id, mutation.key));
849                    removes.insert(key);
850                }
851                Kind::Put(_, bytes, info) | Kind::CopyInsert(bytes, info, _) => {
852                    writes.insert(key, bytes);
853                    for (key, is_unique) in after_indexes {
854                        if is_unique && !unique.insert(key.clone()) {
855                            return Err(Error::UniqueViolation);
856                        }
857                        writes.insert(key, info.key.encode());
858                    }
859                    if !copy_insert {
860                        collect_references(mutation.entity, &info, &mut required)?;
861                    }
862                }
863            }
864        }
865        drop(index_runs);
866        if returning.is_some() {
867            return Err(Error::Missing);
868        }
869        // Check existing owners only after all releases in this batch are known.
870        let mut skip_insert = false;
871        for key in unique {
872            if let Some((entity, _)) = conflict_target.filter(|(_, prefix)| key.starts_with(prefix))
873            {
874                if let Some(encoded) = self.map.get(&key) {
875                    let (owner, bytes) =
876                        read_index_owner(&self.map, entity.id, entity.key_type()?, &encoded)?;
877                    validate_index_entry(entity, &entity.inspect_row(&bytes)?, owner, &key)?;
878                    skip_insert = true;
879                }
880                continue;
881            }
882            if self.map.contains_key(&key) && !removes.contains(&key) {
883                return Err(Error::UniqueViolation);
884            }
885        }
886        if skip_insert {
887            // No candidate row will be published to satisfy its own references.
888            self.validate_references(&required, &deleted, &removes, &BTreeMap::new())?;
889            return Ok(false);
890        }
891        self.validate_references(&required, &deleted, &removes, &writes)?;
892        for (entity, (mut state, changed, delta)) in entities {
893            if changed {
894                state.revision = state.revision.checked_add(1).ok_or(Error::Limit)?;
895                state.count = if delta >= 0 {
896                    state.count.checked_add(delta as u64).ok_or(Error::Limit)?
897                } else {
898                    state
899                        .count
900                        .checked_sub((-delta) as u64)
901                        .ok_or(Error::Corrupt)?
902                };
903                writes.insert(entity_state_key(entity), state.encode());
904            }
905        }
906        // Proven IC rollback boundary: no recoverable Result branch below this line.
907        let expected = removes.len() as u64;
908        assert_eq!(
909            self.map.remove_many(removes),
910            expected,
911            "prepared removal set changed"
912        );
913        for (key, value) in writes {
914            self.map.insert(key, value);
915        }
916
917        Ok(true)
918    }
919
920    // Reuse the prepared final rows and ordinary index changes. No durable
921    // relationship catalog or second mutation executor is involved.
922    fn validate_references(
923        &self,
924        required: &BTreeSet<(u32, RowKey)>,
925        deleted: &[(u32, RowKey)],
926        removes: &BTreeSet<StoreKey>,
927        writes: &BTreeMap<StoreKey, Vec<u8>>,
928    ) -> Result<(), Error> {
929        for &(entity, id) in required {
930            let key = row_key(entity, id);
931            if writes.contains_key(&key) {
932                continue;
933            } // prepared, validated final target
934            if removes.contains(&key) {
935                return Err(Error::ReferenceViolation);
936            }
937            validate_reference_target(&self.map, &self.schema, entity, id)?;
938        }
939        // A lower-bound seek proves the gap before its first physical key is empty.
940        // Keep one such gap only for this immutable preparation pass.
941        let mut gap: Option<(StoreKey, Option<StoreKey>)> = None;
942        for &(target, id) in deleted {
943            for entity in self.schema.entities() {
944                for field in entity.fields {
945                    let Some(reference) = field.reference.filter(|value| value.entity == target)
946                    else {
947                        continue;
948                    };
949                    let prefix = if matches!(field.value, FieldType::List { .. }) {
950                        list_target_prefix(entity.id, reference.index, id)
951                    } else {
952                        let mut prefix = index_prefix(entity.id, reference.index);
953                        id.index_value()
954                            .append_component(field.optional, &mut prefix);
955                        prefix
956                    };
957                    let prefix = StoreKey::new(prefix)?;
958                    if let Some((start, next)) = &gap
959                        && start <= &prefix
960                        && next
961                            .as_ref()
962                            .is_none_or(|key| key > &prefix && !key.starts_with(&prefix))
963                    {
964                        continue;
965                    }
966                    // Each skipped entry belongs to a distinct changed row in
967                    // this range. At most MAX_BATCH skips plus one survivor.
968                    let mut entries = self.map.range(prefix.clone()..);
969                    for position in 0..=MAX_BATCH {
970                        let entry = match entries.next() {
971                            Some(entry) if entry.key().starts_with(&prefix) => entry,
972                            boundary => {
973                                if position == 0 && deleted.len() > 1 {
974                                    gap = Some((prefix, boundary.map(|entry| entry.key().clone())));
975                                }
976                                break;
977                            }
978                        };
979                        if removes.contains(entry.key()) {
980                            if position == MAX_BATCH {
981                                return Err(Error::Corrupt);
982                            }
983                            continue;
984                        }
985                        let (owner, bytes) = read_index_owner(
986                            &self.map,
987                            entity.id,
988                            entity.key_type()?,
989                            &entry.value(),
990                        )?;
991                        let info = entity.inspect_row(&bytes)?;
992                        validate_index_entry(entity, &info, owner, entry.key())?;
993
994                        return Err(Error::ReferenceViolation);
995                    }
996                }
997            }
998        }
999
1000        Ok(())
1001    }
1002}
1003
1004// Probe at most one neighboring entry per expected secondary key. A gap or different order
1005// switches that slot to point reads for the rest of the same-entity delete run.
1006// Every successful probe checks the full key; the caller checks its stored owner.
1007fn read_adjacent_index<'a, M: Memory>(
1008    map: &'a Map<M>,
1009    runs: &mut Vec<Option<MapIter<'a, StoreKey, Vec<u8>, M>>>,
1010    slot: usize,
1011    key: &StoreKey,
1012    descending: bool,
1013) -> Option<Vec<u8>> {
1014    if slot == runs.len() {
1015        let entries = if descending {
1016            map.range(..=key.clone())
1017        } else {
1018            map.range(key.clone()..)
1019        };
1020        runs.push(Some(entries));
1021    }
1022    let run = &mut runs[slot];
1023    if let Some(entry) = run.as_mut().and_then(|entries| {
1024        if descending {
1025            entries.next_back()
1026        } else {
1027            entries.next()
1028        }
1029    }) && entry.key() == key
1030    {
1031        return Some(entry.value());
1032    }
1033    *run = None;
1034    map.get(key)
1035}
1036
1037// Physical key headers contain a namespace tag and fixed-width schema handles.
1038const ENTITY_PREFIX_BYTES: usize = 1 + size_of::<u32>();
1039const INDEX_PREFIX_BYTES: usize = ENTITY_PREFIX_BYTES + size_of::<u32>();
1040
1041fn prefix(tag: u8, entity: u32, suffix: &[u8]) -> Vec<u8> {
1042    let mut key = Vec::with_capacity(ENTITY_PREFIX_BYTES + suffix.len());
1043    key.push(tag);
1044    key.extend_from_slice(&entity.to_be_bytes());
1045    key.extend_from_slice(suffix);
1046
1047    key
1048}
1049
1050fn entity_state_key(entity: u32) -> StoreKey {
1051    StoreKey::new(prefix(1, entity, &[])).expect("entity state key fits")
1052}
1053
1054fn read_revision<M: Memory>(map: &Map<M>, entity: u32) -> Result<u64, Error> {
1055    Ok(read_entity_state(map, entity)?.revision)
1056}
1057
1058/// One atomic metadata record; neither value is reconstructed during ordinary open.
1059#[derive(Default)]
1060struct EntityState {
1061    revision: u64,
1062    count: u64,
1063}
1064impl EntityState {
1065    fn encode(&self) -> Vec<u8> {
1066        let mut bytes = self.revision.to_le_bytes().to_vec();
1067        bytes.extend(self.count.to_le_bytes());
1068
1069        bytes
1070    }
1071}
1072fn read_entity_state<M: Memory>(map: &Map<M>, entity: u32) -> Result<EntityState, Error> {
1073    let bytes = map.get(&entity_state_key(entity)).ok_or(Error::Corrupt)?;
1074    let (revision, count) = bytes.split_first_chunk::<8>().ok_or(Error::Corrupt)?;
1075    let revision = u64::from_le_bytes(*revision);
1076    let count = u64::from_le_bytes(count.try_into().map_err(|_| Error::Corrupt)?);
1077    // The first insertion advances the revision in the same batch.
1078    if revision == 0 && count != 0 {
1079        return Err(Error::Corrupt);
1080    }
1081
1082    Ok(EntityState { revision, count })
1083}
1084
1085fn row_key(entity: u32, id: RowKey) -> StoreKey {
1086    let mut key = prefix(2, entity, &[]);
1087    id.append_to(&mut key);
1088
1089    StoreKey::new(key).expect("bounded primary key fits")
1090}
1091
1092fn index_prefix(entity: u32, index: u32) -> Vec<u8> {
1093    prefix(3, entity, &index.to_be_bytes())
1094}
1095// One entry per distinct target of a list field, suffixed by its owner key.
1096fn list_target_prefix(entity: u32, field: u32, target: RowKey) -> Vec<u8> {
1097    let mut key = prefix(4, entity, &field.to_be_bytes());
1098    target.append_to(&mut key);
1099    key
1100}
1101
1102// Direct lookups and fluent reads share exact prefix admission and completion bounds.
1103fn admit_index_prefix(
1104    entity: &EntitySchema,
1105    index: &crate::IndexSchema,
1106    values: &[IndexValue<'_>],
1107) -> Result<Vec<u8>, Error> {
1108    if values.len() > index.fields.len() {
1109        return Err(Error::Limit);
1110    }
1111    let mut prefix = index_prefix(entity.id, index.id);
1112    for (value, name) in values.iter().zip(index.fields) {
1113        let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1114        value.admit(field.value, field.optional)?;
1115        if index.present_only && *value == IndexValue::Absent {
1116            return Err(Error::InvalidOperand);
1117        }
1118        value.append_component(field.optional, &mut prefix);
1119        if prefix.len() > crate::MAX_INDEX_KEY_BYTES {
1120            return Err(Error::Limit);
1121        }
1122    }
1123    let mut completion = if index.unique {
1124        0
1125    } else {
1126        key::minimum_bytes(entity.key_type()?)?
1127    };
1128    for name in &index.fields[values.len()..] {
1129        let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1130        completion += if field.optional && !index.present_only {
1131            1
1132        } else {
1133            key::minimum_bytes(field.value)? + usize::from(field.optional)
1134        };
1135    }
1136    if prefix.len() + completion > crate::MAX_INDEX_KEY_BYTES {
1137        return Err(Error::Limit);
1138    }
1139
1140    Ok(prefix)
1141}
1142// RowInfo may come from a generated entity or the shared stored-row decoder.
1143fn visit_index_components(
1144    entity: &EntitySchema,
1145    info: &RowInfo,
1146    mut visit: impl FnMut(&crate::IndexSchema, &[u8]) -> Result<(), Error>,
1147) -> Result<(), Error> {
1148    if info.indexes.len() != entity.indexes.len() {
1149        return Err(Error::Corrupt);
1150    }
1151    for (index, values) in entity.indexes.iter().zip(&info.indexes) {
1152        let Some(values) = values else {
1153            if index.present_only {
1154                continue;
1155            }
1156
1157            return Err(Error::Corrupt);
1158        };
1159        let mut remaining = values.as_slice();
1160        for name in index.fields {
1161            let field = entity.index_field(name).ok_or(Error::Corrupt)?;
1162            key::consume_component(&mut remaining, field, index.present_only, Error::Corrupt)?;
1163        }
1164        if !remaining.is_empty() {
1165            return Err(Error::Corrupt);
1166        }
1167        visit(index, values)?;
1168    }
1169
1170    Ok(())
1171}
1172
1173fn index_entries(entity: &EntitySchema, info: &RowInfo) -> Result<Vec<(StoreKey, bool)>, Error> {
1174    let mut entries = Vec::new();
1175    visit_index_components(entity, info, |index, values| {
1176        let mut key = index_prefix(entity.id, index.id);
1177        key.extend_from_slice(values);
1178        if !index.unique {
1179            info.key.append_to(&mut key);
1180        }
1181        entries.push((StoreKey::new(key)?, index.unique));
1182
1183        Ok(())
1184    })?;
1185
1186    let mut links = BTreeSet::new();
1187    for &(field, target) in &info.list_links {
1188        if links.insert((field, target)) {
1189            let mut key = list_target_prefix(entity.id, field, target);
1190            info.key.append_to(&mut key);
1191            entries.push((StoreKey::new(key)?, false));
1192        }
1193    }
1194    Ok(entries)
1195}
1196
1197// A visited entry must agree with its owner in namespace, components and suffix.
1198// Unrelated entries retain their framing and size checks without building physical keys.
1199fn validate_index_entry(
1200    entity: &EntitySchema,
1201    info: &RowInfo,
1202    owner: RowKey,
1203    key: &[u8],
1204) -> Result<(), Error> {
1205    if info.key != owner {
1206        return Err(Error::Corrupt);
1207    }
1208    if key.first() == Some(&4) {
1209        return index_entries(entity, info)?
1210            .iter()
1211            .any(|(entry, _)| entry.as_ref() == key)
1212            .then_some(())
1213            .ok_or(Error::Corrupt);
1214    }
1215    let (header, payload) = key
1216        .split_at_checked(INDEX_PREFIX_BYTES)
1217        .ok_or(Error::Corrupt)?;
1218    if header[0] != 3 || header[1..ENTITY_PREFIX_BYTES] != entity.id.to_be_bytes() {
1219        return Err(Error::Corrupt);
1220    }
1221    let mut matches = false;
1222    let owner = owner.encode();
1223    visit_index_components(entity, info, |index, values| {
1224        let suffix = if index.unique {
1225            &[][..]
1226        } else {
1227            owner.as_slice()
1228        };
1229        if INDEX_PREFIX_BYTES + values.len() + suffix.len() > crate::MAX_INDEX_KEY_BYTES {
1230            return Err(Error::Limit);
1231        }
1232        if header[ENTITY_PREFIX_BYTES..] == index.id.to_be_bytes() {
1233            matches = payload.strip_prefix(values) == Some(suffix);
1234        }
1235
1236        Ok(())
1237    })?;
1238    if !matches {
1239        return Err(Error::Corrupt);
1240    }
1241
1242    Ok(())
1243}