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