Skip to main content

ic_db/
schema.rs

1//! One compiled contract, canonical fingerprint and inspection projection.
2
3use crate::{
4    __private::RowInfo,
5    Error, IndexValue,
6    codec::Decoder,
7    key,
8    named_schema::{TypeGraph, TypeLink},
9    primary::RowKey,
10};
11use sha2::{Digest, Sha256};
12use std::{collections::BTreeSet, sync::Arc};
13
14/// Verify producer-owned membership during constant evaluation. Entries are Rust
15/// paths relative to the crate, separated by a character forbidden in identifiers.
16/// Root entries end with `::` so sibling names sharing a prefix stay independent.
17#[doc(hidden)]
18#[must_use]
19pub const fn check_schema_member(path: &str, root: &str, members: Option<&str>) -> bool {
20    const fn listed(path: &[u8], list: &[u8]) -> bool {
21        let mut start = 0;
22        while start < list.len() {
23            let mut end = start;
24            let mut same = true;
25            while end < list.len() && list[end] != b'|' {
26                let i = end - start;
27                same = same && i < path.len() && path[i] == list[end];
28                end += 1;
29            }
30            if same && end - start == path.len() {
31                return true;
32            }
33            start = end + 1;
34        }
35
36        false
37    }
38    let path = path.as_bytes();
39    let mut first_separator = 0;
40    while first_separator < path.len() && path[first_separator] != b':' {
41        first_separator += 1;
42    }
43    let (_, relative) = path.split_at(first_separator);
44
45    let root = root.as_bytes();
46    let mut index = 0;
47    while index < root.len() {
48        if index == relative.len() || relative[index] != root[index] {
49            return true;
50        }
51        index += 1;
52    }
53
54    match members {
55        Some(paths) => listed(relative, paths.as_bytes()),
56        None => false,
57    }
58}
59
60pub(crate) const MAX_ENTITIES: u8 = 128;
61pub(crate) const MAX_FIELDS: usize = 32;
62
63// FNV-1a is only a compact physical handle, never schema authority. Admission
64// rejects collisions; full names and semantics enter the SHA-256 contract.
65#[doc(hidden)]
66#[must_use]
67pub const fn handle(name: &str) -> u32 {
68    let bytes = name.as_bytes();
69    let mut value = 2_166_136_261_u32;
70    let mut position = 0;
71    while position < bytes.len() {
72        value = (value ^ bytes[position] as u32).wrapping_mul(16_777_619);
73        position += 1;
74    }
75
76    value
77}
78
79/// Stored value semantics supported by this increment.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
81pub enum FieldType {
82    /// An ordered bounded list of scalars or named values.
83    List {
84        /// Exact element type; optional elements and inline lists are not admitted yet.
85        item: &'static FieldType,
86        /// Maximum number of elements, from zero through 256.
87        max_items: u32,
88    },
89    /// A compiler-resolved named value. Scalar newtypes and unit enums support
90    /// secondary keys. Primary and reference keys require supported primitives.
91    Named(TypeLink),
92    /// Exact unsigned 8-bit integer.
93    Nat8,
94    /// Exact unsigned 16-bit integer.
95    Nat16,
96    /// Exact unsigned 32-bit integer.
97    Nat32,
98    /// Exact signed 8-bit integer.
99    Int8,
100    /// Exact signed 16-bit integer.
101    Int16,
102    /// Exact signed 32-bit integer.
103    Int32,
104    /// Exact unsigned 64-bit integer.
105    Nat64,
106    /// Exact signed 64-bit integer, without unsigned or floating-point coercion.
107    Int64,
108    /// Exact unsigned 128-bit integer, without narrowing or floating-point coercion.
109    Nat128,
110    /// Exact signed 128-bit integer, without narrowing or floating-point coercion.
111    Int128,
112    /// Exact unsigned 256-bit integer, stored as 32 big-endian bytes.
113    U256,
114    /// Exact 16-byte ULID, ordered by timestamp prefix then remaining bits.
115    Ulid,
116    /// Gregorian epoch days, bounded to years 0000 through 9999.
117    Date,
118    /// Signed Unix milliseconds; full i64 domain.
119    Timestamp,
120    /// Nonnegative milliseconds; full u64 domain.
121    Duration,
122    /// Exact decimal, stored at the declared fractional scale without rounding.
123    Decimal {
124        /// Number of fractional places, 0 through 28.
125        scale: u32,
126    },
127    /// Finite IEEE-754 single precision, canonical positive zero.
128    Float32,
129    /// Finite IEEE-754 double precision, canonical positive zero.
130    Float64,
131    /// Boolean, without numeric coercion.
132    Bool,
133    /// Opaque IC identity, zero to 29 significant bytes; no authority policy.
134    Principal,
135    /// Exact 32-byte opaque subaccount, ordered lexicographically.
136    Subaccount,
137    /// Platform account identity: owner then effective subaccount; absent and zero agree.
138    Account,
139    /// Exact UTF-8 text, bounded in bytes without implicit normalization.
140    Text {
141        /// Maximum UTF-8 byte length (0..=32768); zero admits only empty text.
142        max_bytes: u32,
143    },
144    /// Exact binary bytes without UTF-8 interpretation or normalization.
145    Blob {
146        /// Maximum payload length (0..=32768); zero admits only an empty value.
147        max_bytes: u32,
148    },
149}
150
151/// One named stored field; type, bounds, optionality and write policy define identity.
152#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
153pub struct FieldSchema {
154    /// Database-owned insertion/update time policy, never applied during decode.
155    pub managed: Option<crate::ManagedTimestamp>,
156    /// Compiled insert-omission policy; no default is applied during decode/update.
157    pub default: Option<&'static crate::LiteralDefault>,
158    /// Stable field identity within its entity.
159    pub name: &'static str,
160    /// Declared primitive and its bounds.
161    pub value: FieldType,
162    /// Whether absence is a stored value, distinct from empty/zero/false.
163    pub optional: bool,
164    /// Present targets must exist; deletion is restricted through a declared index.
165    pub reference: Option<ReferenceSchema>,
166}
167
168/// A required or optional typed reference using an ordinary reverse-lookup index.
169/// An absent optional value has no target; zero remains an ordinary target key.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
171pub struct ReferenceSchema {
172    /// Full logical target identity; its required key type must match this field.
173    pub entity_name: &'static str,
174    /// Generated target storage handle.
175    #[doc(hidden)]
176    pub entity: u32,
177    /// Index on this entity whose first component is the referencing field.
178    pub index: u32,
179}
180
181/// A compiled index over supported exact scalar components.
182#[derive(Debug, PartialEq, Eq, serde::Serialize)]
183pub struct IndexSchema {
184    /// Generated storage handle; use the name when selecting an index.
185    #[doc(hidden)]
186    pub id: u32,
187    /// Logical identity within its entity, included in the stored contract.
188    pub name: &'static str,
189    /// Fields in declared index order.
190    pub fields: &'static [&'static str],
191    /// Whether the complete key must be unique in the final batch state.
192    pub unique: bool,
193    /// Unique membership requires every optional component to be present.
194    pub present_only: bool,
195}
196
197impl IndexSchema {
198    /// An admitted equality prefix identifies at most one owner when it fixes the entire unique key.
199    pub(crate) fn is_unique_lookup(&self, fixed_components: usize) -> bool {
200        self.unique && fixed_components == self.fields.len()
201    }
202}
203
204/// Compiled entity metadata emitted by the entity macro.
205#[derive(serde::Serialize)]
206pub struct EntitySchema {
207    /// Maximum encoded row size, including keys and framing.
208    pub max_row_bytes: usize,
209    /// Generated storage handle; schema authors do not assign this number.
210    #[doc(hidden)]
211    pub id: u32,
212    /// Logical entity identity, included in the stored contract.
213    pub name: &'static str,
214    /// Fields in canonical name order.
215    pub fields: &'static [FieldSchema],
216    /// Supplied scalar primary-key field; its type must implement `PrimaryKey`.
217    pub primary_key: &'static str,
218    /// Indexes ordered by logical name.
219    pub indexes: &'static [IndexSchema],
220}
221
222impl EntitySchema {
223    pub(crate) fn field_position(&self, name: &str) -> Option<usize> {
224        self.fields.iter().position(|field| field.name == name)
225    }
226
227    pub(crate) fn field_by_name(&self, name: &str) -> Option<&FieldSchema> {
228        self.field_position(name)
229            .map(|position| &self.fields[position])
230    }
231
232    pub(crate) fn field_is_required(&self, path: &str) -> bool {
233        self.index_field(path).is_some_and(|field| !field.optional)
234    }
235
236    pub(crate) fn record_member(&self, path: &str) -> Option<(usize, crate::member::RecordMember)> {
237        let (parent, child) = path.split_once('.')?;
238        let position = self.field_position(parent)?;
239        let member =
240            crate::member::RecordMember::resolve(self.fields[position].value, child).ok()?;
241        Some((position, member))
242    }
243
244    pub(crate) fn index_field(&self, name: &str) -> Option<crate::ValueSchema> {
245        let (parent, member) = crate::member::resolve_field(self, name).ok()?;
246        let field = &self.fields[parent];
247        let leaf = member.map_or(field, |m| m.field());
248
249        Some(crate::ValueSchema {
250            value: leaf.value,
251            optional: field.optional || leaf.optional,
252        })
253    }
254
255    pub(crate) fn index_by_name(&self, name: &str) -> Option<&IndexSchema> {
256        self.indexes.iter().find(|index| index.name == name)
257    }
258
259    pub(crate) fn has_managed(&self) -> bool {
260        self.fields.iter().any(|field| field.managed.is_some())
261    }
262
263    pub(crate) fn key_type(&self) -> Result<FieldType, Error> {
264        self.field_by_name(self.primary_key)
265            .filter(|field| !field.optional)
266            .map(|f| f.value)
267            .ok_or(Error::Corrupt)
268    }
269    // Called only for an admitted schema. Validate every stored field but retain
270    // only selected key values; no entity or owned text/blob materialization.
271    pub(crate) fn inspect_row(&self, bytes: &[u8]) -> Result<RowInfo, Error> {
272        let mut values = [IndexValue::Absent; MAX_FIELDS];
273        let mut spans = [(0, 0); MAX_FIELDS];
274        self.inspect_fields(bytes, self.key_fields(), &mut values, Some(&mut spans))?;
275
276        let key = RowKey::from_index(
277            values[self
278                .field_position(self.primary_key)
279                .ok_or(Error::Corrupt)?],
280        )?;
281        let mut info = RowInfo::new(key);
282        self.fill_index_info(&values, bytes, &spans, &mut info)?;
283        Ok(info)
284    }
285
286    pub(crate) fn key_fields(&self) -> u32 {
287        self.fields
288            .iter()
289            .enumerate()
290            .fold(0, |mask, (position, field)| {
291                if field.name == self.primary_key
292                    || self.indexes.iter().any(|i| i.fields.contains(&field.name))
293                {
294                    mask | (1 << position)
295                } else {
296                    mask
297                }
298            })
299    }
300    // One bounded borrowed field view serves mutation integrity and predicates.
301    // Unselected fields are still validated, never silently trusted or materialized.
302    // Callers supply fresh absent slots; filling in place avoids copying the view.
303    // Projection captures validated byte ranges, including presence tags. There
304    // is still one row decoder and one shared depth/node/collection budget.
305    pub(crate) fn inspect_fields<'a>(
306        &self,
307        bytes: &'a [u8],
308        selected: u32,
309        keys: &mut [IndexValue<'a>; MAX_FIELDS],
310        mut spans: Option<&mut [(u16, u16); MAX_FIELDS]>,
311    ) -> Result<(), Error> {
312        let mut reader = Decoder::for_entity(bytes, self)?;
313        let mut times = [None; 2];
314        for (position, field) in self.fields.iter().enumerate() {
315            let start = reader.position();
316            let present = !field.optional || reader.boolean()?;
317            if !present {
318                // The fresh slot remains absent; its presence tag is projected.
319            } else if let Some(managed) = field.managed {
320                let value = reader.timestamp()?;
321                times[managed.slot()] = Some(value);
322                keys[position] = IndexValue::from(value);
323            } else if selected & (1 << position) != 0 {
324                *keys.get_mut(position).ok_or(Error::Corrupt)? =
325                    IndexValue::read(&mut reader, field.value)?;
326            } else {
327                reader.skip(field.value)?;
328            }
329            if let Some(spans) = &mut spans {
330                spans[position] = (start as u16, reader.position() as u16);
331            }
332        }
333        reader.finish()?;
334        crate::managed::validate_order(times)?;
335
336        Ok(())
337    }
338
339    // A scan retains the index buffers across owners of the same schema.
340    pub(crate) fn fill_index_info<'a>(
341        &self,
342        keys: &[IndexValue<'a>; MAX_FIELDS],
343        bytes: &'a [u8],
344        spans: &[(u16, u16); MAX_FIELDS],
345        info: &mut RowInfo,
346    ) -> Result<(), Error> {
347        info.indexes.resize_with(self.indexes.len(), || None);
348        for (encoded, index) in info.indexes.iter_mut().zip(self.indexes) {
349            let mut components = [key::IndexComponent {
350                value: IndexValue::Absent,
351                optional: false,
352            }; 4];
353            for (slot, name) in components.iter_mut().zip(index.fields) {
354                *slot = if let Some(position) = self.field_position(name) {
355                    key::IndexComponent {
356                        value: keys[position],
357                        optional: self.fields[position].optional,
358                    }
359                } else {
360                    let (parent, member) = self.record_member(name).ok_or(Error::Corrupt)?;
361                    let (start, end) = spans[parent];
362                    let optional = self.fields[parent].optional;
363                    key::IndexComponent {
364                        value: member
365                            .read(&bytes[usize::from(start)..usize::from(end)], optional)?,
366                        optional: optional || member.field().optional,
367                    }
368                };
369                if slot.value == IndexValue::Absent && !slot.optional {
370                    return Err(Error::Corrupt);
371                }
372            }
373
374            key::encode_index_into(
375                &components[..index.fields.len()],
376                index.present_only,
377                encoded,
378            );
379        }
380        info.list_links.clear();
381        for (field, &(start, end)) in self.fields.iter().zip(spans) {
382            if let (Some(reference), FieldType::List { item, max_items }) =
383                (field.reference, field.value)
384            {
385                let mut reader = Decoder::new(&bytes[usize::from(start)..usize::from(end)])?;
386                if !field.optional || reader.boolean()? {
387                    let count = reader.nat32()?;
388                    if count > max_items {
389                        return Err(Error::Corrupt);
390                    }
391                    for _ in 0..count {
392                        info.list_links.push((
393                            reference.index,
394                            RowKey::from_index(IndexValue::read(&mut reader, *item)?)?,
395                        ));
396                    }
397                }
398                reader.finish()?;
399            }
400        }
401        Ok(())
402    }
403}
404
405/// Validated executable schema. It is never reconstructed from stored data.
406/// Clones share the admitted entity roster and named definitions; each open still
407/// validates the current durable manifest independently. Revision reads and
408/// writes validate the affected counters when used, without caching them.
409#[derive(Clone)]
410pub struct Schema {
411    metadata: Arc<SchemaMetadata>,
412    pub(crate) fingerprint: [u8; 32],
413}
414
415struct SchemaMetadata {
416    entities: Vec<&'static EntitySchema>,
417    types: TypeGraph,
418}
419
420/// Serializable inspection of one compiled store or a single entity in it.
421#[derive(serde::Serialize)]
422pub struct SchemaDescription<'a> {
423    /// Fingerprint of the entire compiled store, including for an entity selection.
424    pub fingerprint: [u8; 32],
425    /// Selected entities in logical-name order.
426    pub entities: &'a [&'static EntitySchema],
427    /// Reachable named definitions in logical-name order. Links serialize by name.
428    pub types: Vec<&'static crate::TypeSchema>,
429}
430
431impl Schema {
432    /// Validate one bounded compiled schema and compute its canonical fingerprint.
433    /// # Errors
434    /// Refuses duplicate/invalid identities, fields, keys, indexes or capacity.
435    pub fn new(entities: &[&'static EntitySchema]) -> Result<Self, Error> {
436        Self::admit_schema(entities, |_, _, _, _| {})
437    }
438
439    // The host formats reference failures at the same check used by ordinary admission.
440    pub(crate) fn admit_schema(
441        entities: &[&'static EntitySchema],
442        report_reference: impl FnOnce(&str, &FieldSchema, &str, Option<(&str, FieldType)>),
443    ) -> Result<Self, Error> {
444        if entities.is_empty() || entities.len() > usize::from(MAX_ENTITIES) {
445            return Err(Error::InvalidSchema);
446        }
447        let mut entities = entities.to_vec();
448        entities.sort_by_key(|entity| entity.name);
449        let mut bytes = Vec::new();
450        // The hash domain identifies the compiled schema grammar. These versions
451        // identify independent row, key, semantics and supplier contracts.
452        // Supplier contract 1 is qualified with Storage 0.74.1; it is not a guess
453        // that every future supplier release uses a compatible collection format.
454        // Semantics 2 admits complete physical index keys of at most 512 bytes.
455        // Older wider-key contracts refuse intact; stored component bytes are unchanged.
456        for version in [crate::codec::ROW_CODEC_VERSION, 1, 2, 1] {
457            bytes.extend(version.to_le_bytes());
458        }
459        bytes.extend((entities.len() as u32).to_le_bytes());
460        let mut ids = BTreeSet::new();
461        let mut types = TypeGraph::default();
462        for entity in &entities {
463            if entity.id != handle(entity.name)
464                || !ids.insert(entity.id)
465                || entity.fields.is_empty()
466                || !(1..=crate::codec::MAX_ROW_BYTES).contains(&entity.max_row_bytes)
467                || entity.fields.len() > MAX_FIELDS
468                || entity.indexes.len() > 8
469                || !entity.key_type().is_ok_and(RowKey::supports)
470                || entity
471                    .fields
472                    .windows(2)
473                    .any(|pair| pair[0].name >= pair[1].name)
474            {
475                return Err(Error::InvalidSchema);
476            }
477            name(&mut bytes, entity.name)?;
478            if entity.max_row_bytes != crate::codec::DEFAULT_ROW_BYTES {
479                // A zero field count is reserved; a real entity always has a key.
480                bytes.extend(0_u32.to_le_bytes());
481                bytes.extend((entity.max_row_bytes as u32).to_le_bytes());
482            }
483            bytes.extend((entity.fields.len() as u32).to_le_bytes());
484            let mut list_fanout = 0;
485            let mut list_indexes = BTreeSet::new();
486            for field in entity.fields {
487                name(&mut bytes, field.name)?;
488                encode_type(
489                    &mut bytes,
490                    field.value,
491                    field.optional,
492                    field.reference.is_some(),
493                )?;
494                types.include(field.value)?;
495                if let Some(reference) = field.reference {
496                    let Some(target) = entities.iter().find(|target| {
497                        target.id == reference.entity && target.name == reference.entity_name
498                    }) else {
499                        report_reference(entity.name, field, reference.entity_name, None);
500
501                        return Err(Error::InvalidSchema);
502                    };
503                    let key_type = target.key_type().map_err(|_| Error::InvalidSchema)?;
504                    let referenced_type = match field.value {
505                        FieldType::List { item, .. } => *item,
506                        scalar => scalar,
507                    };
508                    if referenced_type != key_type {
509                        report_reference(
510                            entity.name,
511                            field,
512                            target.name,
513                            Some((target.primary_key, key_type)),
514                        );
515
516                        return Err(Error::InvalidSchema);
517                    }
518                    if let FieldType::List { max_items, .. } = field.value {
519                        list_fanout += max_items;
520                        if list_fanout > 32
521                            || reference.index != handle(field.name)
522                            || !list_indexes.insert(reference.index)
523                        {
524                            return Err(Error::InvalidSchema);
525                        }
526                        name(&mut bytes, target.name)?;
527                        name(&mut bytes, field.name)?;
528                        continue;
529                    }
530                    if !RowKey::supports(field.value) {
531                        return Err(Error::InvalidSchema);
532                    }
533                    let index = entity
534                        .indexes
535                        .iter()
536                        .find(|index| {
537                            index.id == reference.index
538                                && !index.present_only
539                                && index.fields.first() == Some(&field.name)
540                        })
541                        .ok_or(Error::InvalidSchema)?;
542                    name(&mut bytes, target.name)?;
543                    name(&mut bytes, index.name)?;
544                }
545            }
546            name(&mut bytes, entity.primary_key)?;
547            bytes.extend((entity.indexes.len() as u32).to_le_bytes());
548            let mut index_ids = BTreeSet::new();
549            for index in entity.indexes {
550                if index.id != handle(index.name)
551                    || !index_ids.insert(index.id)
552                    || index.fields.is_empty()
553                    || index.fields.len() > 4
554                {
555                    return Err(Error::InvalidSchema);
556                }
557                let mut fields = BTreeSet::new();
558                let has_optional = index.fields.iter().any(|name| {
559                    entity
560                        .fields
561                        .iter()
562                        .any(|field| field.name == *name && field.optional)
563                });
564                if (index.unique && has_optional && !index.present_only)
565                    || (index.present_only && (!index.unique || !has_optional))
566                {
567                    return Err(Error::InvalidSchema);
568                }
569                name(&mut bytes, index.name)?;
570                bytes.push(u8::from(index.unique) | (u8::from(index.present_only) << 1));
571                bytes.extend((index.fields.len() as u32).to_le_bytes());
572                for field in index.fields {
573                    if !fields.insert(field) {
574                        return Err(Error::InvalidSchema);
575                    }
576                    if let Some(declared) = entity.field_by_name(field) {
577                        if !key::supports(declared.value) {
578                            return Err(Error::InvalidSchema);
579                        }
580                        name(&mut bytes, field)?;
581                    } else {
582                        let (parent, member) =
583                            entity.record_member(field).ok_or(Error::InvalidSchema)?;
584                        let parent = &entity.fields[parent];
585                        let leaf = member.field();
586                        if index.unique || index.fields.len() != 1 {
587                            return Err(Error::InvalidSchema);
588                        }
589                        // Outside the 1..=64 length domain of a flat field. Each path part
590                        // owns its own frame, including when the index has an explicit name.
591                        bytes.extend(u32::MAX.to_le_bytes());
592                        name(&mut bytes, parent.name)?;
593                        name(&mut bytes, leaf.name)?;
594                    }
595                }
596            }
597            if entity
598                .indexes
599                .windows(2)
600                .any(|pair| pair[0].name >= pair[1].name)
601            {
602                return Err(Error::InvalidSchema);
603            }
604        }
605        types.encode(&mut bytes)?;
606        // Versioned policy trailer only for schemas that declare defaults. Existing
607        // contracts retain their bytes; the trailer is not a second durable catalog.
608        let defaults: Vec<_> = entities
609            .iter()
610            .flat_map(|entity| {
611                entity
612                    .fields
613                    .iter()
614                    .filter_map(move |field| field.default.map(|value| (entity, field, value)))
615            })
616            .collect();
617        if !defaults.is_empty() {
618            bytes.extend(b"ic-db:insert-defaults:v1\0");
619            bytes.extend((defaults.len() as u32).to_le_bytes());
620            for (entity, field, value) in defaults {
621                if field.name == entity.primary_key {
622                    return Err(Error::InvalidSchema);
623                }
624                name(&mut bytes, entity.name)?;
625                name(&mut bytes, field.name)?;
626                let encoded = value.encode(field.value)?;
627                bytes.extend((encoded.len() as u32).to_le_bytes());
628                bytes.extend(encoded);
629            }
630        }
631        let mut policies = Vec::new();
632        for entity in &entities {
633            let mut seen = [false; 2];
634            for field in entity.fields {
635                if let Some(managed) = field.managed {
636                    if crate::key::operand_type(field.value) != FieldType::Timestamp
637                        || field.optional
638                        || field.default.is_some()
639                        || field.reference.is_some()
640                        || field.name == entity.primary_key
641                        || seen[managed.slot()]
642                    {
643                        return Err(Error::InvalidSchema);
644                    }
645                    seen[managed.slot()] = true;
646                    policies.push((entity.name, field.name, managed));
647                }
648            }
649        }
650        if !policies.is_empty() {
651            bytes.extend(b"ic-db:managed-times:v1\0");
652            bytes.extend((policies.len() as u32).to_le_bytes());
653            for (entity, field, managed) in policies {
654                name(&mut bytes, entity)?;
655                name(&mut bytes, field)?;
656                bytes.push(managed.slot() as u8 + 1);
657            }
658        }
659        let mut hash = Sha256::new();
660        hash.update(b"ic-db:compiled-schema:v1\0");
661        hash.update(bytes);
662
663        Ok(Self {
664            metadata: Arc::new(SchemaMetadata { entities, types }),
665            fingerprint: hash.finalize().into(),
666        })
667    }
668
669    /// Full domain-separated contract identity used by the durable manifest.
670    #[must_use]
671    pub const fn fingerprint(&self) -> [u8; 32] {
672        self.fingerprint
673    }
674
675    /// Compiled entities in logical-name order, for bounded inspection.
676    #[must_use]
677    pub fn entities(&self) -> &[&'static EntitySchema] {
678        &self.metadata.entities
679    }
680
681    /// Describe the compiled schema without opening storage. A selected entity
682    /// includes its reachable named values. References identify other entities
683    /// without expanding them. Schema admission bounds the entities and definitions.
684    /// # Errors
685    /// Returns `UnknownEntity` for an unknown name or a schema error if a type
686    /// resolver fails to reproduce its admitted declaration.
687    pub fn describe(&self, selected: Option<&str>) -> Result<SchemaDescription<'_>, Error> {
688        let (entities, types) = if let Some(name) = selected {
689            let position = self
690                .entities()
691                .binary_search_by_key(&name, |entity| entity.name)
692                .map_err(|_| Error::UnknownEntity)?;
693            let entity = self.entities()[position];
694            let mut reachable = TypeGraph::default();
695            for field in entity.fields {
696                reachable.include(field.value)?;
697            }
698            if !self.metadata.types.contains(&reachable) {
699                return Err(Error::InvalidSchema);
700            }
701            (
702                &self.entities()[position..=position],
703                reachable.definitions().collect(),
704            )
705        } else {
706            (self.entities(), self.types().collect())
707        };
708        Ok(SchemaDescription {
709            fingerprint: self.fingerprint(),
710            entities,
711            types,
712        })
713    }
714
715    pub(crate) fn entity_by_id(&self, id: u32) -> Option<&'static EntitySchema> {
716        self.entities()
717            .iter()
718            .copied()
719            .find(|entity| entity.id == id)
720    }
721
722    pub(crate) fn entity_by_name(&self, name: &str) -> Option<&'static EntitySchema> {
723        self.entities()
724            .binary_search_by_key(&name, |entity| entity.name)
725            .ok()
726            .map(|position| self.entities()[position])
727    }
728
729    /// Reachable named definitions in logical-name order, without expanding cycles.
730    pub fn types(&self) -> impl Iterator<Item = &'static crate::TypeSchema> + '_ {
731        self.metadata.types.definitions()
732    }
733
734    // Return the existing admitted descriptor after checking the complete type
735    // contract. Typed callers can use it without specializing execution around
736    // their executable's descriptor address.
737    pub(crate) fn admits(&self, proposed: &EntitySchema) -> Result<&'static EntitySchema, Error> {
738        let current = self.entity_by_id(proposed.id).ok_or(Error::UnknownEntity)?;
739        // The exact immutable descriptor and its compiled links were checked by Schema::new.
740        if std::ptr::eq(current, proposed) {
741            return Ok(current);
742        }
743        if current.max_row_bytes != proposed.max_row_bytes
744            || current.name != proposed.name
745            || current.fields != proposed.fields
746            || current.primary_key != proposed.primary_key
747            || current.indexes != proposed.indexes
748        {
749            return Err(Error::UnknownEntity);
750        }
751        let mut proposed_types = TypeGraph::default();
752        for field in proposed.fields {
753            proposed_types
754                .include(field.value)
755                .map_err(|_| Error::UnknownEntity)?;
756        }
757        if !self.metadata.types.contains(&proposed_types) {
758            return Err(Error::UnknownEntity);
759        }
760
761        Ok(current)
762    }
763}
764
765pub(crate) fn name(bytes: &mut Vec<u8>, value: &str) -> Result<(), Error> {
766    if value.is_empty() || value.len() > 64 {
767        return Err(Error::InvalidSchema);
768    }
769    bytes.extend((value.len() as u32).to_le_bytes());
770    bytes.extend(value.as_bytes());
771
772    Ok(())
773}
774
775pub(crate) fn encode_type(
776    bytes: &mut Vec<u8>,
777    value: FieldType,
778    optional: bool,
779    reference: bool,
780) -> Result<(), Error> {
781    let tag = match value {
782        FieldType::Nat64 => 1,
783        FieldType::Bool => 2,
784        FieldType::Text { .. } => 3,
785        FieldType::Int64 => 4,
786        FieldType::Nat128 => 5,
787        FieldType::Int128 => 6,
788        FieldType::Blob { .. } => 7,
789        FieldType::Nat8 => 8,
790        FieldType::Nat16 => 9,
791        FieldType::Nat32 => 10,
792        FieldType::Int8 => 11,
793        FieldType::Int16 => 12,
794        FieldType::Int32 => 13,
795        FieldType::Principal => 14,
796        FieldType::Named(_) => 15,
797        FieldType::List { .. } => 16,
798        FieldType::U256 => 17,
799        FieldType::Float32 => 18,
800        FieldType::Float64 => 19,
801        FieldType::Subaccount => 20,
802        FieldType::Account => 21,
803        FieldType::Ulid => 22,
804        FieldType::Date => 23,
805        FieldType::Timestamp => 24,
806        FieldType::Duration => 25,
807        FieldType::Decimal { .. } => 26,
808    };
809    bytes.push(tag | if optional { 0x80 } else { 0 } | if reference { 0x40 } else { 0 });
810    match value {
811        FieldType::Decimal { scale } => {
812            if scale > crate::Decimal::MAX_SCALE {
813                return Err(Error::InvalidSchema);
814            }
815            bytes.extend(scale.to_le_bytes());
816        }
817        FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => {
818            if max_bytes > crate::codec::MAX_ROW_BYTES as u32 {
819                return Err(Error::InvalidSchema);
820            }
821            bytes.extend(max_bytes.to_le_bytes());
822        }
823        FieldType::Named(link) => name(bytes, link.name)?,
824        FieldType::List { item, max_items } => {
825            if max_items > crate::named_schema::MAX_COLLECTION_ITEMS as u32
826                || matches!(item, FieldType::List { .. })
827            {
828                return Err(Error::InvalidSchema);
829            }
830            for bound in [
831                max_items,
832                crate::named_schema::MAX_DEPTH as u32,
833                crate::named_schema::MAX_NODES as u32,
834                crate::named_schema::MAX_COLLECTION_ITEMS as u32,
835            ] {
836                bytes.extend(bound.to_le_bytes());
837            }
838            encode_type(bytes, *item, false, false)?;
839        }
840        _ => {}
841    }
842
843    Ok(())
844}