Skip to main content

ic_db/store/
mod.rs

1//! Shared commit and traversal over one supplier-owned collection.
2//! Typed codecs stay at the boundary; no executor is generated per entity.
3
4mod maintenance;
5mod query;
6
7use crate::{
8    __private::RowInfo, Entity, EntitySchema, Error, FieldType, IndexValue, PrimaryKey, Schema,
9    UniqueKey, key, primary::RowKey, store_key::StoreKey,
10};
11use ic_storage::{
12    Memory, RuntimeMemory,
13    adapter::{MapIter, StableBTreeMap},
14};
15pub use maintenance::{
16    CopyStatus, CopyStep, Maintenance, RetiredSource, SchemaCopy, SchemaTransition,
17};
18pub use query::{
19    Aggregate, AggregateJobs, Column, Comparison, GetMany, GroupCount, GroupCursor, GroupOrder,
20    GroupPage, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue, JobHandle, JobOutcome,
21    JobStep, Query, QueryCursor, QueryOperand, QueryPage, SelectColumns, SelectedGetMany,
22    SelectedQuery, Selection, SortDirection, SummaryMeasure,
23};
24use std::collections::{BTreeMap, BTreeSet};
25
26const MANIFEST: &[u8] = b"ICDBMF02";
27const MAX_BATCH: usize = 32;
28const MAX_BATCH_BYTES: usize = 128 * 1024;
29type Map<M> = StableBTreeMap<StoreKey, Vec<u8>, M>;
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            validate_index_entry(entity, &row.__row_info(), id, &key)?;
679            rows.push(row);
680        }
681
682        Ok(rows)
683    }
684
685    /// Prepare final state, then synchronously apply rows, indexes, revisions and counts.
686    /// A normal refusal occurs before persistent writes. Success is not a separate
687    /// durability point from the surrounding IC message. Empty/no-op batches preserve revisions.
688    /// # Errors
689    /// Refuses missing/existing rows, duplicate targets, uniqueness/reference violations,
690    /// corruption or limits. References use the intended final batch state.
691    /// # Panics
692    /// Supplier failures after the first mutation trap; never catch and continue an IC commit.
693    pub fn commit(&mut self, batch: Batch) -> Result<(), Error> {
694        observe!(commit, { self.commit_batch(batch, None, None).map(|_| ()) })
695    }
696
697    /// Insert or replace one row by primary key and return its stored value.
698    /// # Errors
699    /// Propagates batch preparation and commit errors, including unique conflicts.
700    /// # Panics
701    /// Supplier failures during publication trap as in [`Self::commit`].
702    pub fn upsert<E: Entity>(&mut self, row: &E) -> Result<E, Error> {
703        let mut batch = Batch::new();
704        batch.upsert(row)?;
705        self.commit_returning(batch, row.id())
706    }
707
708    /// Commit the whole batch and return the selected insert or replacement,
709    /// including its final managed timestamps. The row is decoded during preparation.
710    /// # Errors
711    /// Returns [`Error::Missing`] if the batch has no insert or replacement for
712    /// this entity and key. All ordinary [`Self::commit`] refusals apply.
713    /// # Panics
714    /// Supplier failures during publication trap as in [`Self::commit`].
715    pub fn commit_returning<E: Entity>(
716        &mut self,
717        batch: Batch,
718        key: impl Into<crate::Id<E>>,
719    ) -> Result<E, Error> {
720        observe!(commit, {
721            self.schema.admits(E::SCHEMA)?;
722            let mut row = None;
723            let selected = ReturningRow {
724                entity: E::SCHEMA.id,
725                key: key.into().key().into_row_key(),
726                decode: &mut |bytes| {
727                    row = Some(E::decode(bytes)?);
728                    Ok(())
729                },
730            };
731            self.commit_batch(batch, Some(selected), None)?;
732            Ok(row.expect("commit validated the selected row before publication"))
733        })
734    }
735
736    pub(crate) fn insert_if_absent<K: UniqueKey>(
737        &mut self,
738        input: impl crate::InsertInput<Entity = K::Entity>,
739    ) -> Result<crate::InsertOutcome<K::Entity>, Error> {
740        let entity = K::Entity::SCHEMA;
741        let index = entity
742            .index_by_name(K::INDEX)
743            .filter(|i| i.unique)
744            .ok_or(Error::InvalidQuery)?;
745        let mut batch = Batch::new();
746        let row = batch.insert_input(input)?;
747        let prefix = index_prefix(entity.id, index.id);
748        let applied = observe!(commit, {
749            self.commit_batch(batch, None, Some((entity, &prefix)))
750        })?;
751        Ok(if applied {
752            crate::InsertOutcome::Inserted(row)
753        } else {
754            crate::InsertOutcome::AlreadyPresent
755        })
756    }
757
758    // False means the single conditional insert was validated and skipped.
759    fn commit_batch(
760        &mut self,
761        batch: Batch,
762        returning: Option<ReturningRow<'_>>,
763        conflict_target: Option<(&EntitySchema, &[u8])>,
764    ) -> Result<bool, Error> {
765        let Some(prepared) = self.prepare_batch(batch, returning, conflict_target)? else {
766            return Ok(false);
767        };
768        self.apply_batch(prepared);
769        Ok(true)
770    }
771
772    // Supplier failures during stable writes trap and roll back the IC message.
773    fn apply_batch(&mut self, prepared: PreparedBatch) {
774        let PreparedBatch { removes, writes } = prepared;
775        let expected = removes.len() as u64;
776        assert_eq!(
777            self.map.remove_many(removes),
778            expected,
779            "prepared removal set changed"
780        );
781        for (key, value) in writes {
782            self.map.insert(key, value);
783        }
784    }
785
786    fn prepare_batch(
787        &self,
788        batch: Batch,
789        mut returning: Option<ReturningRow<'_>>,
790        conflict_target: Option<(&EntitySchema, &[u8])>,
791    ) -> Result<Option<PreparedBatch>, Error> {
792        let mut targets = BTreeSet::new();
793        let mut removes = BTreeSet::new();
794        let mut writes = BTreeMap::new();
795        let mut unique = BTreeSet::new();
796        // Observe each entity once, then apply its final net row delta. A balanced
797        // delete/insert batch must not depend on mutation order. No state survives calls.
798        let mut entities = BTreeMap::new();
799        let mut required = BTreeSet::new();
800        let mut deleted = Vec::new();
801        let mut index_runs = Vec::new();
802        for mut mutation in batch.mutations {
803            let direction = deleted.last().and_then(|&(entity, key)| {
804                (entity == mutation.entity.id && matches!(mutation.kind, Kind::Delete))
805                    .then(|| mutation.key < key)
806            });
807            if direction.is_none() {
808                index_runs.clear();
809            }
810            self.schema.admits(mutation.entity)?;
811            let key = row_key(mutation.entity.id, mutation.key);
812            if !targets.insert(key.clone()) {
813                return Err(Error::DuplicateTarget);
814            }
815            let old = self.map.get(&key);
816            match (&mutation.kind, &old) {
817                (Kind::Put(WriteMode::Insert, ..) | Kind::CopyInsert(..), Some(_)) => {
818                    return Err(Error::Exists);
819                }
820                (Kind::Put(WriteMode::Replace, ..), None) => return Err(Error::Missing),
821                (Kind::Delete, None) => continue,
822                _ => {}
823            }
824            if mutation.entity.has_managed() {
825                match &mut mutation.kind {
826                    Kind::Put(mode, bytes, info) => {
827                        if crate::managed::save(
828                            mutation.entity,
829                            bytes,
830                            old.as_deref(),
831                            *mode == WriteMode::Upsert,
832                            batch.operation_time.ok_or(Error::MissingOperationTime)?,
833                        )? {
834                            *info = mutation.entity.inspect_row(bytes)?;
835                        }
836                    }
837                    Kind::CopyInsert(bytes, _, expected) => {
838                        if crate::managed::values(mutation.entity, bytes)? != *expected {
839                            return Err(Error::ManagedField);
840                        }
841                    }
842                    Kind::Delete => {}
843                }
844            }
845            if let Kind::Put(_, bytes, _) = &mutation.kind
846                && let Some(selected) = returning
847                    .take_if(|row| row.entity == mutation.entity.id && row.key == mutation.key)
848            {
849                (selected.decode)(bytes)?;
850            }
851            // Admit complete after-image keys even when the row is a no-op.
852            // Retain these buffers for publication instead of encoding twice.
853            let mut after_indexes = match &mutation.kind {
854                Kind::Put(_, _, info) | Kind::CopyInsert(_, info, _) => {
855                    index_entries(mutation.entity, info)?
856                }
857                Kind::Delete => Vec::new(),
858            };
859            let (_, changed, delta) = match entities.entry(mutation.entity.id) {
860                std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
861                std::collections::btree_map::Entry::Vacant(entry) => entry.insert((
862                    read_entity_state(&self.map, mutation.entity.id)?,
863                    false,
864                    0_i64,
865                )),
866            };
867            if let (Kind::Put(_, bytes, _), Some(old)) = (&mutation.kind, &old)
868                && bytes == old
869            {
870                continue;
871            }
872            if let Some(old) = &old {
873                let info = mutation.entity.inspect_row(old)?;
874                if info.key != mutation.key {
875                    return Err(Error::Corrupt);
876                }
877                let owner = info.key.encode();
878                for (slot, (key, _)) in index_entries(mutation.entity, &info)?
879                    .into_iter()
880                    .enumerate()
881                {
882                    let value = if let Some(descending) = direction
883                        && key.first() == Some(&3)
884                    {
885                        read_adjacent_index(&self.map, &mut index_runs, slot, &key, descending)
886                    } else {
887                        self.map.get(&key)
888                    };
889                    if value.as_deref() != Some(owner.as_slice()) {
890                        return Err(Error::Corrupt);
891                    }
892
893                    // Same physical key and owner: leave the verified entry in place.
894                    // Its unique value remains occupied during final-state admission.
895                    if let Some(position) =
896                        after_indexes.iter().position(|(after, _)| *after == key)
897                    {
898                        after_indexes.remove(position);
899                    } else {
900                        removes.insert(key);
901                    }
902                }
903            }
904            *changed = true;
905            *delta += match &mutation.kind {
906                Kind::Put(..) | Kind::CopyInsert(..) => i64::from(old.is_none()),
907                Kind::Delete => -1,
908            };
909            // Private migration inserts may precede their targets. The frozen
910            // complete target validates references before it can be published.
911            let copy_insert = matches!(&mutation.kind, Kind::CopyInsert(..));
912
913            match mutation.kind {
914                Kind::Delete => {
915                    deleted.push((mutation.entity.id, mutation.key));
916                    removes.insert(key);
917                }
918                Kind::Put(_, bytes, info) | Kind::CopyInsert(bytes, info, _) => {
919                    writes.insert(key, bytes);
920                    for (key, is_unique) in after_indexes {
921                        if is_unique && !unique.insert(key.clone()) {
922                            return Err(Error::UniqueViolation);
923                        }
924                        writes.insert(key, info.key.encode());
925                    }
926                    if !copy_insert {
927                        collect_references(mutation.entity, &info, &mut required)?;
928                    }
929                }
930            }
931        }
932        drop(index_runs);
933        if returning.is_some() {
934            return Err(Error::Missing);
935        }
936        // Check existing owners only after all releases in this batch are known.
937        let mut skip_insert = false;
938        for key in unique {
939            if let Some((entity, _)) = conflict_target.filter(|(_, prefix)| key.starts_with(prefix))
940            {
941                if let Some(encoded) = self.map.get(&key) {
942                    let (owner, bytes) =
943                        read_index_owner(&self.map, entity.id, entity.key_type()?, &encoded)?;
944                    validate_index_entry(entity, &entity.inspect_row(&bytes)?, owner, &key)?;
945                    skip_insert = true;
946                }
947                continue;
948            }
949            if self.map.contains_key(&key) && !removes.contains(&key) {
950                return Err(Error::UniqueViolation);
951            }
952        }
953        if skip_insert {
954            // No candidate row will be published to satisfy its own references.
955            self.validate_references(&required, &deleted, &removes, &BTreeMap::new())?;
956            return Ok(None);
957        }
958        self.validate_references(&required, &deleted, &removes, &writes)?;
959        for (entity, (mut state, changed, delta)) in entities {
960            if changed {
961                state.revision = state.revision.checked_add(1).ok_or(Error::Limit)?;
962                state.count = if delta >= 0 {
963                    state.count.checked_add(delta as u64).ok_or(Error::Limit)?
964                } else {
965                    state
966                        .count
967                        .checked_sub((-delta) as u64)
968                        .ok_or(Error::Corrupt)?
969                };
970                writes.insert(entity_state_key(entity), state.encode());
971            }
972        }
973        Ok(Some(PreparedBatch { removes, writes }))
974    }
975
976    // Reuse the prepared final rows and ordinary index changes. No durable
977    // relationship catalog or second mutation executor is involved.
978    fn validate_references(
979        &self,
980        required: &BTreeSet<(u32, RowKey)>,
981        deleted: &[(u32, RowKey)],
982        removes: &BTreeSet<StoreKey>,
983        writes: &BTreeMap<StoreKey, Vec<u8>>,
984    ) -> Result<(), Error> {
985        for &(entity, id) in required {
986            let key = row_key(entity, id);
987            if writes.contains_key(&key) {
988                continue;
989            } // prepared, validated final target
990            if removes.contains(&key) {
991                return Err(Error::ReferenceViolation);
992            }
993            validate_reference_target(&self.map, &self.schema, entity, id)?;
994        }
995        // A lower-bound seek proves the gap before its first physical key is empty.
996        // Keep one such gap only for this immutable preparation pass.
997        let mut gap: Option<(StoreKey, Option<StoreKey>)> = None;
998        for &(target, id) in deleted {
999            for entity in self.schema.entities() {
1000                for field in entity.fields {
1001                    let Some(reference) = field.reference.filter(|value| value.entity == target)
1002                    else {
1003                        continue;
1004                    };
1005                    let prefix = if matches!(field.value, FieldType::List { .. }) {
1006                        list_target_prefix(entity.id, reference.index, id)
1007                    } else {
1008                        let mut prefix = index_prefix(entity.id, reference.index);
1009                        id.index_value()
1010                            .append_component(field.optional, &mut prefix);
1011                        prefix
1012                    };
1013                    let prefix = StoreKey::new(prefix)?;
1014                    if let Some((start, next)) = &gap
1015                        && start <= &prefix
1016                        && next
1017                            .as_ref()
1018                            .is_none_or(|key| key > &prefix && !key.starts_with(&prefix))
1019                    {
1020                        continue;
1021                    }
1022                    // Each skipped entry belongs to a distinct changed row in
1023                    // this range. At most MAX_BATCH skips plus one survivor.
1024                    let mut entries = self.map.range(prefix.clone()..);
1025                    for position in 0..=MAX_BATCH {
1026                        let entry = match entries.next() {
1027                            Some(entry) if entry.key().starts_with(&prefix) => entry,
1028                            boundary => {
1029                                if position == 0 && deleted.len() > 1 {
1030                                    gap = Some((prefix, boundary.map(|entry| entry.key().clone())));
1031                                }
1032                                break;
1033                            }
1034                        };
1035                        if removes.contains(entry.key()) {
1036                            if position == MAX_BATCH {
1037                                return Err(Error::Corrupt);
1038                            }
1039                            continue;
1040                        }
1041                        let (owner, bytes) = read_index_owner(
1042                            &self.map,
1043                            entity.id,
1044                            entity.key_type()?,
1045                            &entry.value(),
1046                        )?;
1047                        let info = entity.inspect_row(&bytes)?;
1048                        validate_index_entry(entity, &info, owner, entry.key())?;
1049
1050                        return Err(Error::ReferenceViolation);
1051                    }
1052                }
1053            }
1054        }
1055
1056        Ok(())
1057    }
1058}
1059
1060// Probe at most one neighboring entry per expected secondary key. A gap or different order
1061// switches that slot to point reads for the rest of the same-entity delete run.
1062// Every successful probe checks the full key; the caller checks its stored owner.
1063fn read_adjacent_index<'a, M: Memory>(
1064    map: &'a Map<M>,
1065    runs: &mut Vec<Option<MapIter<'a, StoreKey, Vec<u8>, M>>>,
1066    slot: usize,
1067    key: &StoreKey,
1068    descending: bool,
1069) -> Option<Vec<u8>> {
1070    if slot == runs.len() {
1071        let entries = if descending {
1072            map.range(..=key.clone())
1073        } else {
1074            map.range(key.clone()..)
1075        };
1076        runs.push(Some(entries));
1077    }
1078    let run = &mut runs[slot];
1079    if let Some(entry) = run.as_mut().and_then(|entries| {
1080        if descending {
1081            entries.next_back()
1082        } else {
1083            entries.next()
1084        }
1085    }) && entry.key() == key
1086    {
1087        return Some(entry.value());
1088    }
1089    *run = None;
1090    map.get(key)
1091}
1092
1093// Physical key headers contain a namespace tag and fixed-width schema handles.
1094const ENTITY_PREFIX_BYTES: usize = 1 + size_of::<u32>();
1095const INDEX_PREFIX_BYTES: usize = ENTITY_PREFIX_BYTES + size_of::<u32>();
1096
1097fn prefix(tag: u8, entity: u32, suffix: &[u8]) -> Vec<u8> {
1098    let mut key = Vec::with_capacity(ENTITY_PREFIX_BYTES + suffix.len());
1099    key.push(tag);
1100    key.extend_from_slice(&entity.to_be_bytes());
1101    key.extend_from_slice(suffix);
1102
1103    key
1104}
1105
1106fn entity_state_key(entity: u32) -> StoreKey {
1107    StoreKey::new(prefix(1, entity, &[])).expect("entity state key fits")
1108}
1109
1110fn read_revision<M: Memory>(map: &Map<M>, entity: u32) -> Result<u64, Error> {
1111    Ok(read_entity_state(map, entity)?.revision)
1112}
1113
1114/// One atomic metadata record; neither value is reconstructed during ordinary open.
1115#[derive(Default)]
1116struct EntityState {
1117    revision: u64,
1118    count: u64,
1119}
1120impl EntityState {
1121    fn encode(&self) -> Vec<u8> {
1122        let mut bytes = self.revision.to_le_bytes().to_vec();
1123        bytes.extend(self.count.to_le_bytes());
1124
1125        bytes
1126    }
1127}
1128fn read_entity_state<M: Memory>(map: &Map<M>, entity: u32) -> Result<EntityState, Error> {
1129    let bytes = map.get(&entity_state_key(entity)).ok_or(Error::Corrupt)?;
1130    let (revision, count) = bytes.split_first_chunk::<8>().ok_or(Error::Corrupt)?;
1131    let revision = u64::from_le_bytes(*revision);
1132    let count = u64::from_le_bytes(count.try_into().map_err(|_| Error::Corrupt)?);
1133    // The first insertion advances the revision in the same batch.
1134    if revision == 0 && count != 0 {
1135        return Err(Error::Corrupt);
1136    }
1137
1138    Ok(EntityState { revision, count })
1139}
1140
1141fn row_key(entity: u32, id: RowKey) -> StoreKey {
1142    let mut key = prefix(2, entity, &[]);
1143    id.append_to(&mut key);
1144
1145    StoreKey::new(key).expect("bounded primary key fits")
1146}
1147
1148fn index_prefix(entity: u32, index: u32) -> Vec<u8> {
1149    prefix(3, entity, &index.to_be_bytes())
1150}
1151// One entry per distinct target of a list field, suffixed by its owner key.
1152fn list_target_prefix(entity: u32, field: u32, target: RowKey) -> Vec<u8> {
1153    let mut key = prefix(4, entity, &field.to_be_bytes());
1154    target.append_to(&mut key);
1155    key
1156}
1157
1158// Direct lookups and fluent reads share exact prefix admission and completion bounds.
1159fn admit_index_prefix(
1160    entity: &EntitySchema,
1161    index: &crate::IndexSchema,
1162    values: &[IndexValue<'_>],
1163) -> Result<Vec<u8>, Error> {
1164    if values.len() > index.fields.len() {
1165        return Err(Error::Limit);
1166    }
1167    let mut prefix = index_prefix(entity.id, index.id);
1168    for (value, name) in values.iter().zip(index.fields) {
1169        let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1170        value.admit(field.value, field.optional)?;
1171        if index.present_only && *value == IndexValue::Absent {
1172            return Err(Error::InvalidOperand);
1173        }
1174        value.append_component(field.optional, &mut prefix);
1175        if prefix.len() > crate::MAX_INDEX_KEY_BYTES {
1176            return Err(Error::Limit);
1177        }
1178    }
1179    let mut completion = if index.unique {
1180        0
1181    } else {
1182        key::minimum_bytes(entity.key_type()?)?
1183    };
1184    for name in &index.fields[values.len()..] {
1185        let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1186        completion += if field.optional && !index.present_only {
1187            1
1188        } else {
1189            key::minimum_bytes(field.value)? + usize::from(field.optional)
1190        };
1191    }
1192    if prefix.len() + completion > crate::MAX_INDEX_KEY_BYTES {
1193        return Err(Error::Limit);
1194    }
1195
1196    Ok(prefix)
1197}
1198// RowInfo may come from a generated entity or the shared stored-row decoder.
1199fn visit_index_components(
1200    entity: &EntitySchema,
1201    info: &RowInfo,
1202    mut visit: impl FnMut(&crate::IndexSchema, &[u8]) -> Result<(), Error>,
1203) -> Result<(), Error> {
1204    if info.indexes.len() != entity.indexes.len() {
1205        return Err(Error::Corrupt);
1206    }
1207    for (index, values) in entity.indexes.iter().zip(&info.indexes) {
1208        let Some(values) = values else {
1209            if index.present_only {
1210                continue;
1211            }
1212
1213            return Err(Error::Corrupt);
1214        };
1215        let mut remaining = values.as_slice();
1216        for name in index.fields {
1217            let field = entity.index_field(name).ok_or(Error::Corrupt)?;
1218            key::consume_component(&mut remaining, field, index.present_only, Error::Corrupt)?;
1219        }
1220        if !remaining.is_empty() {
1221            return Err(Error::Corrupt);
1222        }
1223        visit(index, values)?;
1224    }
1225
1226    Ok(())
1227}
1228
1229fn index_entries(entity: &EntitySchema, info: &RowInfo) -> Result<Vec<(StoreKey, bool)>, Error> {
1230    let mut entries = Vec::new();
1231    visit_index_components(entity, info, |index, values| {
1232        let mut key = index_prefix(entity.id, index.id);
1233        key.extend_from_slice(values);
1234        if !index.unique {
1235            info.key.append_to(&mut key);
1236        }
1237        entries.push((StoreKey::new(key)?, index.unique));
1238
1239        Ok(())
1240    })?;
1241
1242    let mut links = BTreeSet::new();
1243    for &(field, target) in &info.list_links {
1244        if links.insert((field, target)) {
1245            let mut key = list_target_prefix(entity.id, field, target);
1246            info.key.append_to(&mut key);
1247            entries.push((StoreKey::new(key)?, false));
1248        }
1249    }
1250    Ok(entries)
1251}
1252
1253// A visited entry must agree with its owner in namespace, components and suffix.
1254// Unrelated entries retain their framing and size checks without building physical keys.
1255fn validate_index_entry(
1256    entity: &EntitySchema,
1257    info: &RowInfo,
1258    owner: RowKey,
1259    key: &[u8],
1260) -> Result<(), Error> {
1261    if info.key != owner {
1262        return Err(Error::Corrupt);
1263    }
1264    if key.first() == Some(&4) {
1265        return index_entries(entity, info)?
1266            .iter()
1267            .any(|(entry, _)| entry.as_ref() == key)
1268            .then_some(())
1269            .ok_or(Error::Corrupt);
1270    }
1271    let (header, payload) = key
1272        .split_at_checked(INDEX_PREFIX_BYTES)
1273        .ok_or(Error::Corrupt)?;
1274    if header[0] != 3 || header[1..ENTITY_PREFIX_BYTES] != entity.id.to_be_bytes() {
1275        return Err(Error::Corrupt);
1276    }
1277    let mut matches = false;
1278    let owner = owner.encode();
1279    visit_index_components(entity, info, |index, values| {
1280        let suffix = if index.unique {
1281            &[][..]
1282        } else {
1283            owner.as_slice()
1284        };
1285        if INDEX_PREFIX_BYTES + values.len() + suffix.len() > crate::MAX_INDEX_KEY_BYTES {
1286            return Err(Error::Limit);
1287        }
1288        if header[ENTITY_PREFIX_BYTES..] == index.id.to_be_bytes() {
1289            matches = payload.strip_prefix(values) == Some(suffix);
1290        }
1291
1292        Ok(())
1293    })?;
1294    if !matches {
1295        return Err(Error::Corrupt);
1296    }
1297
1298    Ok(())
1299}