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