Skip to main content

ic_db/store/
mod.rs

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