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