Skip to main content

type_bridge/
schema.rs

1//! Schema package markers and type-branded installation handshake.
2
3use core::marker::PhantomData;
4use std::collections::HashMap;
5use std::sync::{Arc, LazyLock, PoisonError, RwLock};
6
7use type_bridge_contract::projection::{ProjectionConfig, RuntimeProjection};
8use type_bridge_contract::schema::encode_declared_schema;
9use type_bridge_contract::sdk_diagnostic::SdkProjectionEvidenceSlotPresence;
10use type_bridge_schema::{
11    MAX_SCHEMA_AUTHORITY_BYTES, VerifiedSchemaAuthority, decode_schema_authority,
12    schema_authority_capability_vocabulary,
13};
14use type_bridge_schema_codegen::RustEmitter;
15
16use crate::__codegen::{
17    CompleteModel, EncodedCreate, GroupedQueryValue, HydratedRow, HydrationCapability,
18    IntoEncodedCreate, IntoEncodedReference, IntoEncodedScalar, IntoEncodedStruct,
19    IntoHydratedSnapshot, MaterializeCreate, MaterializeModel, MaterializeReference,
20    MaterializeStruct, Model, StructValue, ValidationError, ValidationPath,
21};
22use crate::CanonicalCodecOptions;
23use crate::canonical_codec::{
24    CapturedCanonicalCodecControl, input_error as canonical_input_error,
25    output_error as canonical_output_error,
26};
27use crate::error::{Error, ModelValidationPhase, Result};
28
29#[doc(hidden)]
30pub mod sealed {
31    pub trait Sealed {}
32}
33
34/// A type-level marker representing a generated schema package.
35pub trait Schema: sealed::Sealed + Send + Sync + 'static {}
36
37/// Default marker representing an unbound database handle.
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub struct Unbound;
40
41impl sealed::Sealed for Unbound {}
42impl Schema for Unbound {}
43
44fn canonical_contract_error(error: type_bridge_contract::diagnostic::Diagnostic) -> Error {
45    let code = error.code().as_str().to_owned();
46    Error::model_validation(
47        ModelValidationPhase::Input,
48        code,
49        Vec::new(),
50        "canonical projected-record contract rejected the value",
51        Some(Box::new(error)),
52    )
53}
54
55fn canonical_codec_error(error: type_bridge_orm::ProjectedCodecError) -> Error {
56    if let Some(diagnostic) = error.record_schema_mismatch() {
57        return Error::from_sdk_execution(diagnostic, ModelValidationPhase::Input);
58    }
59    Error::model_validation(
60        ModelValidationPhase::Input,
61        "canonical_projected_codec_failure",
62        Vec::new(),
63        "installed projection rejected canonical record materialization",
64        Some(Box::new(error)),
65    )
66}
67
68/// Opaque installed projection used by generated successor runtimes.
69#[doc(hidden)]
70pub struct GeneratedProjectionValidator {
71    installed: Arc<type_bridge_orm::InstalledRuntimeProjection>,
72}
73
74impl GeneratedProjectionValidator {
75    /// Validate one generated create encoding through the common projected model authority.
76    pub fn validate_create(&self, encoded: &EncodedCreate) -> Result<(), ValidationError> {
77        crate::projected_codec::validate_encoded_create(encoded, &self.installed)
78            .map_err(generated_validation_error)
79    }
80
81    /// Validate one generated hydration row through the common projected model authority.
82    pub fn validate_hydration(&self, row: &HydratedRow) -> Result<(), ValidationError> {
83        crate::projected_codec::validate_hydrated_row(row, &self.installed)
84            .map_err(generated_validation_error)
85    }
86}
87
88fn generated_validation_error(error: Error) -> ValidationError {
89    let code = error
90        .code()
91        .expect("generated projected validation always returns a classified model error")
92        .to_owned();
93    let path = error
94        .path()
95        .map(generated_validation_path)
96        .unwrap_or_default();
97    ValidationError::new(path, code)
98}
99
100fn generated_validation_path(segments: &[String]) -> String {
101    let mut path = String::new();
102    for segment in segments {
103        if segment.starts_with('[') {
104            path.push_str(segment);
105        } else {
106            if !path.is_empty() {
107                path.push('.');
108            }
109            path.push_str(segment);
110        }
111    }
112    path
113}
114
115/// Address and length of each embedded authority evidence string.
116type AuthorityEvidenceKey = [Option<(usize, usize)>; 4];
117
118/// Verified compiled authority of every package used so far. Embedded
119/// evidence is immutable, so verifying it once per package suffices.
120static VERIFIED_AUTHORITIES: LazyLock<
121    RwLock<HashMap<AuthorityEvidenceKey, Arc<VerifiedSchemaAuthority>>>,
122> = LazyLock::new(RwLock::default);
123
124#[cfg(test)]
125thread_local! {
126    /// Full authority verifications run on this thread.
127    pub(crate) static AUTHORITY_VERIFICATIONS: std::cell::Cell<usize> =
128        const { std::cell::Cell::new(0) };
129}
130
131/// A generated schema package marker carrying fingerprint evidence branded by `S: Schema`.
132#[derive(Clone, Copy, Debug, Eq, PartialEq)]
133pub struct SchemaPackage<S: Schema> {
134    semantic_fingerprint_json: &'static str,
135    projection_fingerprint_json: &'static str,
136    runtime_projection_json: &'static str,
137    declared_schema_json: Option<&'static str>,
138    schema_authority_json: Option<&'static str>,
139    managed_scope_id: Option<&'static str>,
140    semantic_profile_id: Option<&'static str>,
141    marker: PhantomData<fn() -> S>,
142}
143
144impl<S: Schema> SchemaPackage<S> {
145    /// Encode one exact generated attribute value as canonical projected-record bytes.
146    pub fn encode_attribute<T>(&self, value: T) -> Result<Vec<u8>>
147    where
148        T: Model<Schema = S> + IntoEncodedScalar,
149    {
150        self.encode_attribute_controlled(value, &CanonicalCodecOptions::default())
151    }
152
153    /// Encode one generated attribute under cancellation, deadline, and tighten-only limits.
154    pub fn encode_attribute_controlled<T>(
155        &self,
156        value: T,
157        options: &CanonicalCodecOptions,
158    ) -> Result<Vec<u8>>
159    where
160        T: Model<Schema = S> + IntoEncodedScalar,
161    {
162        let control = CapturedCanonicalCodecControl::capture(options, false)?;
163        control.check()?;
164        let installed = self.verify_and_install()?;
165        let projected = crate::projected_codec::project_attribute_inferred(&value, &installed)?;
166        let record = type_bridge_orm::record_from_attribute(&installed, &projected)
167            .map_err(canonical_codec_error)?;
168        control.check_decoded_weight(record.decoded_weight())?;
169        control.check()?;
170        let bytes = record
171            .encode_with_limits(control.output_limits())
172            .map_err(canonical_output_error)?;
173        control.check()?;
174        Ok(bytes)
175    }
176
177    /// Decode canonical projected-record bytes as one exact generated attribute value.
178    pub fn decode_attribute<T>(&self, bytes: &[u8]) -> Result<T>
179    where
180        T: Model<Schema = S> + GroupedQueryValue,
181    {
182        self.decode_attribute_controlled(bytes, &CanonicalCodecOptions::default())
183    }
184
185    /// Decode one exact generated attribute under cancellation, deadline, and limits.
186    pub fn decode_attribute_controlled<T>(
187        &self,
188        bytes: &[u8],
189        options: &CanonicalCodecOptions,
190    ) -> Result<T>
191    where
192        T: Model<Schema = S> + GroupedQueryValue,
193    {
194        let control = CapturedCanonicalCodecControl::capture(options, false)?;
195        control.check()?;
196        let installed = self.verify_and_install()?;
197        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
198            bytes,
199            control.input_limits(),
200        )
201        .map_err(canonical_input_error)?;
202        control.check_decoded_weight(record.decoded_weight())?;
203        control.check()?;
204        let value = type_bridge_orm::materialize_record(&installed, &record)
205            .map_err(canonical_codec_error)?;
206        let type_bridge_orm::ProjectedCodecValue::Attribute(value) = value else {
207            return Err(Error::model_validation(
208                ModelValidationPhase::Input,
209                "canonical_record_kind_mismatch",
210                Vec::new(),
211                "canonical record is not a generated attribute value",
212                None,
213            ));
214        };
215        let expected = type_bridge_contract::codec::from_canonical_json::<
216            type_bridge_contract::id::TypeId,
217        >(T::TYPE_ID_JSON.as_bytes())
218        .map_err(canonical_contract_error)?;
219        if value.attribute_type() != &expected {
220            return Err(Error::model_validation(
221                ModelValidationPhase::Input,
222                "canonical_attribute_type_mismatch",
223                Vec::new(),
224                "canonical attribute record does not match the requested generated type",
225                None,
226            ));
227        }
228        let scalar = crate::projected_codec::projected_to_decoded_attribute(&value)?;
229        let decoded = T::from_group_scalar(scalar).map_err(|error| {
230            Error::model_validation(
231                ModelValidationPhase::Input,
232                "canonical_attribute_materialization_failed",
233                Vec::new(),
234                "canonical attribute could not materialize as the requested generated type",
235                Some(Box::new(error)),
236            )
237        })?;
238        control.check()?;
239        Ok(decoded)
240    }
241
242    /// Construct a type-branded schema package marker from verified JSON evidence (generated-code SPI).
243    #[doc(hidden)]
244    #[must_use]
245    pub const fn new(
246        semantic_fingerprint_json: &'static str,
247        projection_fingerprint_json: &'static str,
248        runtime_projection_json: &'static str,
249    ) -> Self {
250        Self {
251            semantic_fingerprint_json,
252            projection_fingerprint_json,
253            runtime_projection_json,
254            declared_schema_json: None,
255            schema_authority_json: None,
256            managed_scope_id: None,
257            semantic_profile_id: None,
258            marker: PhantomData,
259        }
260    }
261
262    /// Construct a generated package carrying canonical remote query
263    /// authority in addition to verified runtime projection evidence.
264    #[doc(hidden)]
265    #[must_use]
266    pub const fn new_with_declared(
267        semantic_fingerprint_json: &'static str,
268        projection_fingerprint_json: &'static str,
269        runtime_projection_json: &'static str,
270        declared_schema_json: &'static str,
271    ) -> Self {
272        Self {
273            semantic_fingerprint_json,
274            projection_fingerprint_json,
275            runtime_projection_json,
276            declared_schema_json: Some(declared_schema_json),
277            schema_authority_json: None,
278            managed_scope_id: None,
279            semantic_profile_id: None,
280            marker: PhantomData,
281        }
282    }
283
284    /// Construct a generated package carrying one exact compiled schema
285    /// authority and its constructor-extracted query inputs.
286    #[doc(hidden)]
287    #[must_use]
288    pub const fn new_with_authority(
289        semantic_fingerprint_json: &'static str,
290        projection_fingerprint_json: &'static str,
291        runtime_projection_json: &'static str,
292        schema_authority_json: &'static str,
293        declared_schema_json: &'static str,
294        managed_scope_id: &'static str,
295        semantic_profile_id: &'static str,
296    ) -> Self {
297        Self {
298            semantic_fingerprint_json,
299            projection_fingerprint_json,
300            runtime_projection_json,
301            declared_schema_json: Some(declared_schema_json),
302            schema_authority_json: Some(schema_authority_json),
303            managed_scope_id: Some(managed_scope_id),
304            semantic_profile_id: Some(semantic_profile_id),
305            marker: PhantomData,
306        }
307    }
308
309    /// Encode one exact generated create payload as canonical projected-record bytes.
310    pub fn encode_create<T>(&self, value: T) -> Result<Vec<u8>>
311    where
312        T: IntoEncodedCreate,
313    {
314        self.encode_create_controlled(value, &CanonicalCodecOptions::default())
315    }
316
317    /// Encode one generated create under cancellation, deadline, and tighten-only limits.
318    pub fn encode_create_controlled<T>(
319        &self,
320        value: T,
321        options: &CanonicalCodecOptions,
322    ) -> Result<Vec<u8>>
323    where
324        T: IntoEncodedCreate,
325    {
326        let control = CapturedCanonicalCodecControl::capture(options, false)?;
327        control.check()?;
328        let installed = self.verify_and_install()?;
329        let projected = crate::projected_codec::project_create_inferred(value, &installed)?;
330        let record = type_bridge_orm::record_from_create(&installed, &projected)
331            .map_err(canonical_codec_error)?;
332        control.check_decoded_weight(record.decoded_weight())?;
333        control.check()?;
334        let bytes = record
335            .encode_with_limits(control.output_limits())
336            .map_err(canonical_output_error)?;
337        control.check()?;
338        Ok(bytes)
339    }
340
341    /// Decode canonical projected-record bytes as one exact generated create type.
342    pub fn decode_create<T>(&self, bytes: &[u8]) -> Result<T>
343    where
344        T: MaterializeCreate<Schema = S>,
345    {
346        self.decode_create_controlled(bytes, &CanonicalCodecOptions::default())
347    }
348
349    /// Decode one exact generated create under cancellation, deadline, and limits.
350    pub fn decode_create_controlled<T>(
351        &self,
352        bytes: &[u8],
353        options: &CanonicalCodecOptions,
354    ) -> Result<T>
355    where
356        T: MaterializeCreate<Schema = S>,
357    {
358        let control = CapturedCanonicalCodecControl::capture(options, false)?;
359        control.check()?;
360        let installed = self.verify_and_install()?;
361        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
362            bytes,
363            control.input_limits(),
364        )
365        .map_err(canonical_input_error)?;
366        control.check_decoded_weight(record.decoded_weight())?;
367        control.check()?;
368        let value = type_bridge_orm::materialize_record(&installed, &record)
369            .map_err(canonical_codec_error)?;
370        let type_bridge_orm::ProjectedCodecValue::Create(value) = value else {
371            return Err(Error::model_validation(
372                ModelValidationPhase::Input,
373                "canonical_record_kind_mismatch",
374                Vec::new(),
375                "canonical record is not a generated create payload",
376                None,
377            ));
378        };
379        let decoded = crate::projected_codec::projected_to_decoded_create(&value, &installed)?;
380        let decoded =
381            T::materialize_create(&decoded, &ValidationPath::root()).map_err(|error| {
382                Error::model_validation(
383                    ModelValidationPhase::Input,
384                    "canonical_create_materialization_failed",
385                    Vec::new(),
386                    "canonical create could not materialize as the requested generated type",
387                    Some(Box::new(error)),
388                )
389            })?;
390        control.check()?;
391        Ok(decoded)
392    }
393
394    /// Encode one exact generated detached reference as canonical projected-record bytes.
395    pub fn encode_reference<T>(&self, value: T) -> Result<Vec<u8>>
396    where
397        T: IntoEncodedReference,
398    {
399        self.encode_reference_controlled(value, &CanonicalCodecOptions::default())
400    }
401
402    /// Encode one generated reference under cancellation, deadline, and tighten-only limits.
403    pub fn encode_reference_controlled<T>(
404        &self,
405        value: T,
406        options: &CanonicalCodecOptions,
407    ) -> Result<Vec<u8>>
408    where
409        T: IntoEncodedReference,
410    {
411        let control = CapturedCanonicalCodecControl::capture(options, false)?;
412        control.check()?;
413        let installed = self.verify_and_install()?;
414        let projected = crate::projected_codec::project_reference_inferred(value, &installed)?;
415        let record = type_bridge_orm::record_from_reference(&installed, &projected)
416            .map_err(canonical_codec_error)?;
417        control.check_decoded_weight(record.decoded_weight())?;
418        control.check()?;
419        let bytes = record
420            .encode_with_limits(control.output_limits())
421            .map_err(canonical_output_error)?;
422        control.check()?;
423        Ok(bytes)
424    }
425
426    /// Decode canonical projected-record bytes as one exact generated detached reference.
427    pub fn decode_reference<T>(&self, bytes: &[u8]) -> Result<T>
428    where
429        T: MaterializeReference<Schema = S>,
430    {
431        self.decode_reference_controlled(bytes, &CanonicalCodecOptions::default())
432    }
433
434    /// Decode one exact generated reference under cancellation, deadline, and limits.
435    pub fn decode_reference_controlled<T>(
436        &self,
437        bytes: &[u8],
438        options: &CanonicalCodecOptions,
439    ) -> Result<T>
440    where
441        T: MaterializeReference<Schema = S>,
442    {
443        let control = CapturedCanonicalCodecControl::capture(options, false)?;
444        control.check()?;
445        let installed = self.verify_and_install()?;
446        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
447            bytes,
448            control.input_limits(),
449        )
450        .map_err(canonical_input_error)?;
451        control.check_decoded_weight(record.decoded_weight())?;
452        control.check()?;
453        let value = type_bridge_orm::materialize_record(&installed, &record)
454            .map_err(canonical_codec_error)?;
455        let type_bridge_orm::ProjectedCodecValue::Reference(value) = value else {
456            return Err(Error::model_validation(
457                ModelValidationPhase::Input,
458                "canonical_record_kind_mismatch",
459                Vec::new(),
460                "canonical record is not a generated reference",
461                None,
462            ));
463        };
464        let decoded = crate::projected_codec::projected_to_hydrated_player(&value, &installed)?;
465        let decoded =
466            T::materialize_reference(&decoded, &ValidationPath::root()).map_err(|error| {
467                Error::model_validation(
468                    ModelValidationPhase::Input,
469                    "canonical_reference_materialization_failed",
470                    Vec::new(),
471                    "canonical reference could not materialize as the requested generated type",
472                    Some(Box::new(error)),
473                )
474            })?;
475        control.check()?;
476        Ok(decoded)
477    }
478
479    /// Encode one exact generated hydrated model as a provider-free canonical snapshot.
480    pub fn encode_snapshot<T>(&self, value: T) -> Result<Vec<u8>>
481    where
482        T: IntoHydratedSnapshot + Model<Schema = S>,
483    {
484        self.encode_snapshot_controlled(value, &CanonicalCodecOptions::default())
485    }
486
487    /// Encode one generated snapshot under cancellation, deadline, and tighten-only limits.
488    pub fn encode_snapshot_controlled<T>(
489        &self,
490        value: T,
491        options: &CanonicalCodecOptions,
492    ) -> Result<Vec<u8>>
493    where
494        T: IntoHydratedSnapshot + Model<Schema = S>,
495    {
496        let control = CapturedCanonicalCodecControl::capture(options, false)?;
497        control.check()?;
498        let installed = self.verify_and_install()?;
499        let projected = crate::projected_codec::project_snapshot_inferred(value, &installed)?;
500        let record = type_bridge_orm::record_from_snapshot(&installed, &projected)
501            .map_err(canonical_codec_error)?;
502        control.check_decoded_weight(record.decoded_weight())?;
503        control.check()?;
504        let bytes = record
505            .encode_with_limits(control.output_limits())
506            .map_err(canonical_output_error)?;
507        control.check()?;
508        Ok(bytes)
509    }
510
511    /// Decode canonical snapshot bytes as one exact detached generated model.
512    pub fn decode_snapshot<T>(&self, bytes: &[u8]) -> Result<T>
513    where
514        T: CompleteModel<Schema = S> + MaterializeModel,
515    {
516        self.decode_snapshot_controlled(bytes, &CanonicalCodecOptions::default())
517    }
518
519    /// Decode one exact detached snapshot under cancellation, deadline, and limits.
520    pub fn decode_snapshot_controlled<T>(
521        &self,
522        bytes: &[u8],
523        options: &CanonicalCodecOptions,
524    ) -> Result<T>
525    where
526        T: CompleteModel<Schema = S> + MaterializeModel,
527    {
528        let control = CapturedCanonicalCodecControl::capture(options, false)?;
529        control.check()?;
530        let installed = self.verify_and_install()?;
531        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
532            bytes,
533            control.input_limits(),
534        )
535        .map_err(canonical_input_error)?;
536        control.check_decoded_weight(record.decoded_weight())?;
537        control.check()?;
538        let value = type_bridge_orm::materialize_record(&installed, &record)
539            .map_err(canonical_codec_error)?;
540        let type_bridge_orm::ProjectedCodecValue::Snapshot(value) = value else {
541            return Err(Error::model_validation(
542                ModelValidationPhase::Hydration,
543                "canonical_record_kind_mismatch",
544                Vec::new(),
545                "canonical record is not a generated hydrated snapshot",
546                None,
547            ));
548        };
549        let mut row = crate::projected_codec::projected_to_hydrated_row(&value, &installed)?;
550        row.mark_detached_snapshot();
551        let decoded = T::materialize(&row, &HydrationCapability::new()).map_err(|error| {
552            crate::entity_codec::map_validation_error(error, ModelValidationPhase::Hydration)
553        })?;
554        control.check()?;
555        Ok(decoded)
556    }
557
558    /// Perform offline fingerprint, authority, and exact emitter-evidence verification
559    /// without connecting to a live server.
560    pub fn verify(&self) -> Result<()> {
561        let _ = self.verify_and_install_with_authority()?;
562        Ok(())
563    }
564
565    /// Verify this generated package and open a schema-bound connection,
566    /// direct or proxy as `policy` says.
567    ///
568    /// A direct connection discovers server compatibility authoritatively;
569    /// callers cannot supply or override the server version used for
570    /// admission. A proxy connection fetches and validates the server's
571    /// advertisement unless the policy pins one.
572    pub async fn connect(
573        self,
574        policy: impl Into<crate::ConnectionPolicy>,
575    ) -> Result<crate::Connection<S>> {
576        self.connect_with_cancellation(policy, type_bridge_orm::AnswerCancellation::default())
577            .await
578    }
579
580    /// [`Self::connect`] with one wakeable connection-cancellation owner.
581    pub async fn connect_with_cancellation(
582        self,
583        policy: impl Into<crate::ConnectionPolicy>,
584        cancellation: type_bridge_orm::AnswerCancellation,
585    ) -> Result<crate::Connection<S>> {
586        match policy.into() {
587            #[cfg(feature = "typedb")]
588            crate::ConnectionPolicy::Direct(policy) => {
589                let (installed, authority) = self.verify_and_install_with_authority()?;
590                let match_registry = crate::session::build_match_registry(&installed)?;
591                let inner = type_bridge_orm::Database::connect_direct(
592                    installed.as_ref(),
593                    &policy,
594                    cancellation,
595                )
596                .await
597                .map_err(Error::from_direct_connection)?;
598                Ok(crate::Connection::Direct(
599                    crate::session::Database::from_bound_parts(
600                        inner,
601                        installed,
602                        match_registry,
603                        authority.map(|authority| authority.managed_scope().id().clone()),
604                    ),
605                ))
606            }
607            crate::ConnectionPolicy::Proxy(policy) => {
608                let proxy =
609                    crate::ProxyDatabase::connect_with_cancellation(policy, cancellation).await?;
610                Ok(crate::Connection::Proxy(proxy.with_schema(self)?))
611            }
612        }
613    }
614
615    /// Install the package's exact projection for generated successor-runtime validation.
616    /// Package verification remains projection-evidence admission; generated-token package
617    /// fencing is provided by the nominal generated Rust types.
618    #[doc(hidden)]
619    pub fn generated_projection_validator(
620        &self,
621    ) -> std::result::Result<GeneratedProjectionValidator, ValidationError> {
622        self.verify_and_install()
623            .map(|installed| GeneratedProjectionValidator { installed })
624            .map_err(|_| {
625                ValidationError::new("projection_evidence", "projection_evidence_mismatch")
626            })
627    }
628
629    /// Encode one exact generated struct as canonical projected-record bytes.
630    pub fn encode_struct<T>(&self, value: T) -> Result<Vec<u8>>
631    where
632        T: IntoEncodedStruct + StructValue<Schema = S>,
633    {
634        self.encode_struct_controlled(value, &CanonicalCodecOptions::default())
635    }
636
637    /// Encode one generated struct under cancellation, deadline, and tighten-only limits.
638    pub fn encode_struct_controlled<T>(
639        &self,
640        value: T,
641        options: &CanonicalCodecOptions,
642    ) -> Result<Vec<u8>>
643    where
644        T: IntoEncodedStruct + StructValue<Schema = S>,
645    {
646        let control = CapturedCanonicalCodecControl::capture(options, false)?;
647        control.check()?;
648        let installed = self.verify_and_install()?;
649        let projected = crate::projected_codec::project_struct_inferred(value, &installed)?;
650        let record = type_bridge_orm::record_from_struct(&installed, &projected)
651            .map_err(canonical_codec_error)?;
652        control.check_decoded_weight(record.decoded_weight())?;
653        control.check()?;
654        let bytes = record
655            .encode_with_limits(control.output_limits())
656            .map_err(canonical_output_error)?;
657        control.check()?;
658        Ok(bytes)
659    }
660
661    /// Decode canonical projected-record bytes as one exact generated struct.
662    pub fn decode_struct<T>(&self, bytes: &[u8]) -> Result<T>
663    where
664        T: MaterializeStruct + StructValue<Schema = S>,
665    {
666        self.decode_struct_controlled(bytes, &CanonicalCodecOptions::default())
667    }
668
669    /// Decode one exact generated struct under cancellation, deadline, and limits.
670    pub fn decode_struct_controlled<T>(
671        &self,
672        bytes: &[u8],
673        options: &CanonicalCodecOptions,
674    ) -> Result<T>
675    where
676        T: MaterializeStruct + StructValue<Schema = S>,
677    {
678        let control = CapturedCanonicalCodecControl::capture(options, false)?;
679        control.check()?;
680        let installed = self.verify_and_install()?;
681        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
682            bytes,
683            control.input_limits(),
684        )
685        .map_err(canonical_input_error)?;
686        control.check_decoded_weight(record.decoded_weight())?;
687        control.check()?;
688        let value = type_bridge_orm::materialize_record(&installed, &record)
689            .map_err(canonical_codec_error)?;
690        let type_bridge_orm::ProjectedCodecValue::Struct(value) = value else {
691            return Err(Error::model_validation(
692                ModelValidationPhase::Input,
693                "canonical_record_kind_mismatch",
694                Vec::new(),
695                "canonical record is not a generated struct",
696                None,
697            ));
698        };
699        let decoded = crate::projected_codec::projected_to_decoded_struct(&value, &installed)?;
700        let decoded =
701            T::materialize_struct(&decoded, &ValidationPath::root()).map_err(|error| {
702                Error::model_validation(
703                    ModelValidationPhase::Input,
704                    "canonical_struct_materialization_failed",
705                    Vec::new(),
706                    "canonical struct could not materialize as the requested generated type",
707                    Some(Box::new(error)),
708                )
709            })?;
710        control.check()?;
711        Ok(decoded)
712    }
713
714    /// Compose already canonical package records into one deterministic ordered archive.
715    pub fn encode_archive<I, B>(&self, records: I) -> Result<Vec<u8>>
716    where
717        I: IntoIterator<Item = B>,
718        B: AsRef<[u8]>,
719    {
720        self.encode_archive_controlled(records, &CanonicalCodecOptions::default())
721    }
722
723    /// Compose canonical records under cancellation, deadline, and tighten-only limits.
724    pub fn encode_archive_controlled<I, B>(
725        &self,
726        records: I,
727        options: &CanonicalCodecOptions,
728    ) -> Result<Vec<u8>>
729    where
730        I: IntoIterator<Item = B>,
731        B: AsRef<[u8]>,
732    {
733        let control = CapturedCanonicalCodecControl::capture(options, true)?;
734        control.check()?;
735        let installed = self.verify_and_install()?;
736        let mut verified = Vec::new();
737        for bytes in records {
738            control.check_record_count(verified.len().saturating_add(1))?;
739            control.check()?;
740            let record =
741                type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
742                    bytes.as_ref(),
743                    control.input_limits(),
744                )
745                .map_err(canonical_input_error)?;
746            let _ = type_bridge_orm::materialize_record(&installed, &record)
747                .map_err(canonical_codec_error)?;
748            verified.push(record);
749        }
750        let archive = type_bridge_contract::projected_record::ProjectedArchive::try_new(verified)
751            .map_err(canonical_contract_error)?;
752        control.check_decoded_weight(archive.decoded_weight())?;
753        control.check()?;
754        let bytes = archive
755            .encode_with_limits(control.output_limits())
756            .map_err(canonical_output_error)?;
757        control.check()?;
758        Ok(bytes)
759    }
760
761    /// Strictly decode one complete package archive into canonical individual records.
762    pub fn decode_archive(&self, bytes: &[u8]) -> Result<Vec<Vec<u8>>> {
763        self.decode_archive_controlled(bytes, &CanonicalCodecOptions::default())
764    }
765
766    /// Decode one complete archive under cancellation, deadline, and tighten-only limits.
767    pub fn decode_archive_controlled(
768        &self,
769        bytes: &[u8],
770        options: &CanonicalCodecOptions,
771    ) -> Result<Vec<Vec<u8>>> {
772        let control = CapturedCanonicalCodecControl::capture(options, true)?;
773        control.check()?;
774        let installed = self.verify_and_install()?;
775        let archive = type_bridge_contract::projected_record::ProjectedArchive::decode_with_limits(
776            bytes,
777            control.input_limits(),
778        )
779        .map_err(canonical_input_error)?;
780        control.check_record_count(archive.records().len())?;
781        control.check_decoded_weight(archive.decoded_weight())?;
782        let mut records = Vec::with_capacity(archive.records().len());
783        let mut output_bytes = 0_usize;
784        for record in archive.records() {
785            control.check()?;
786            let _ = type_bridge_orm::materialize_record(&installed, record)
787                .map_err(canonical_codec_error)?;
788            let encoded = record
789                .encode_with_limits(control.output_limits())
790                .map_err(canonical_output_error)?;
791            output_bytes = output_bytes.saturating_add(encoded.len());
792            control.check_output_bytes(output_bytes)?;
793            records.push(encoded);
794        }
795        control.check()?;
796        Ok(records)
797    }
798
799    /// Return the semantic schema fingerprint JSON string (generated-code SPI).
800    #[doc(hidden)]
801    #[must_use]
802    pub const fn semantic_fingerprint_json(&self) -> &'static str {
803        self.semantic_fingerprint_json
804    }
805
806    /// Return the binding target projection fingerprint JSON string (generated-code SPI).
807    #[doc(hidden)]
808    #[must_use]
809    pub const fn projection_fingerprint_json(&self) -> &'static str {
810        self.projection_fingerprint_json
811    }
812
813    /// Return the canonical runtime projection JSON string (generated-code SPI).
814    #[doc(hidden)]
815    #[must_use]
816    pub const fn runtime_projection_json(&self) -> &'static str {
817        self.runtime_projection_json
818    }
819
820    /// The verified compiled authority plans of this package are built under.
821    pub(crate) fn plan_authority(&self) -> Result<Arc<VerifiedSchemaAuthority>> {
822        self.verify_embedded_authority()?.ok_or_else(|| {
823            authority_error("plans require a generated schema package with compiled authority")
824        })
825    }
826
827    pub(crate) const fn declared_schema_json(&self) -> Option<&'static str> {
828        self.declared_schema_json
829    }
830
831    /// Verify all package evidence and derive provider descriptors without provider I/O
832    /// (crate-internal).
833    pub(crate) fn verify_and_install(
834        &self,
835    ) -> Result<Arc<type_bridge_orm::InstalledRuntimeProjection>> {
836        self.verify_and_install_with_authority()
837            .map(|(projection, _authority)| projection)
838    }
839
840    pub(crate) fn verify_and_install_with_authority(
841        &self,
842    ) -> Result<(
843        Arc<type_bridge_orm::InstalledRuntimeProjection>,
844        Option<Arc<VerifiedSchemaAuthority>>,
845    )> {
846        let authority_backed = self.schema_authority_json.is_some();
847        // The detached semantic-fingerprint string is canonical evidence slot
848        // zero. Empty bytes are the generated Rust install boundary's only
849        // representable absence; every nonempty shape remains merely present
850        // until the binding-neutral rejection classifier sees the failure.
851        let semantic_fingerprint_presence = if self.semantic_fingerprint_json.is_empty() {
852            SdkProjectionEvidenceSlotPresence::Absent
853        } else {
854            SdkProjectionEvidenceSlotPresence::Present
855        };
856        let authority = self.verify_embedded_authority().map_err(|error| {
857            classify_admission_error(authority_backed, semantic_fingerprint_presence, error)
858        })?;
859        let mut projection = type_bridge_orm::InstalledRuntimeProjection::from_verified_rust_json(
860            self.runtime_projection_json.as_bytes(),
861            self.semantic_fingerprint_json.as_bytes(),
862            self.projection_fingerprint_json.as_bytes(),
863        )
864        .map_err(|err| {
865            classify_admission_error(
866                authority_backed,
867                semantic_fingerprint_presence,
868                Error::SchemaVerification {
869                    message: err.to_string(),
870                    source: Some(Box::new(err)),
871                },
872            )
873        })?;
874        if let Some(authority) = authority.as_ref() {
875            projection = projection.with_schema_authority(authority);
876        }
877        let successor =
878            authority_backed || projection_uses_ordered_collections(projection.projection());
879        if authority.as_ref().is_some_and(|authority| {
880            authority.resolved_schema().semantic_fingerprint()
881                != projection.projection().semantic_fingerprint()
882        }) {
883            return Err(classify_admission_error(
884                successor,
885                semantic_fingerprint_presence,
886                authority_error(
887                    "generated schema authority does not match the installed runtime projection",
888                ),
889            ));
890        }
891        verify_rust_projection_evidence(&projection, authority.as_deref()).map_err(|error| {
892            classify_admission_error(successor, semantic_fingerprint_presence, error)
893        })?;
894        Ok((Arc::new(projection), authority))
895    }
896
897    /// The package's verified compiled authority, verified once per package.
898    ///
899    /// Only a successful verification is cached. A package whose evidence
900    /// fails verification re-verifies on every call and so fails every call
901    /// with the same error.
902    fn verify_embedded_authority(&self) -> Result<Option<Arc<VerifiedSchemaAuthority>>> {
903        let key = self.authority_evidence_key();
904        let cached = VERIFIED_AUTHORITIES
905            .read()
906            .unwrap_or_else(PoisonError::into_inner)
907            .get(&key)
908            .cloned();
909        if let Some(authority) = cached {
910            return Ok(Some(authority));
911        }
912        // Verify outside the lock; a concurrent first use verifies twice and
913        // keeps whichever result lands first, both being identical.
914        let Some(authority) = self.verify_embedded_authority_uncached()? else {
915            return Ok(None);
916        };
917        let authority = VERIFIED_AUTHORITIES
918            .write()
919            .unwrap_or_else(PoisonError::into_inner)
920            .entry(key)
921            .or_insert_with(|| Arc::new(authority))
922            .clone();
923        Ok(Some(authority))
924    }
925
926    /// Identity of the evidence `verify_embedded_authority_uncached` reads.
927    ///
928    /// The evidence is immutable `'static` text, so equal addresses and
929    /// lengths mean equal bytes and an equal verification result. A
930    /// byte-identical copy at another address only verifies once more.
931    fn authority_evidence_key(&self) -> AuthorityEvidenceKey {
932        let identity =
933            |text: Option<&'static str>| text.map(|text| (text.as_ptr() as usize, text.len()));
934        [
935            identity(self.schema_authority_json),
936            identity(self.declared_schema_json),
937            identity(self.managed_scope_id),
938            identity(self.semantic_profile_id),
939        ]
940    }
941
942    fn verify_embedded_authority_uncached(&self) -> Result<Option<VerifiedSchemaAuthority>> {
943        let parts = (
944            self.schema_authority_json,
945            self.declared_schema_json,
946            self.managed_scope_id,
947            self.semantic_profile_id,
948        );
949        let (Some(envelope), Some(declared), Some(scope), Some(profile)) = parts else {
950            if parts.0.is_none() && parts.2.is_none() && parts.3.is_none() {
951                return Ok(None);
952            }
953            return Err(authority_error(
954                "generated schema package contains incomplete compiled authority evidence",
955            ));
956        };
957        #[cfg(test)]
958        AUTHORITY_VERIFICATIONS.with(|count| count.set(count.get() + 1));
959        if envelope.len() > MAX_SCHEMA_AUTHORITY_BYTES {
960            return Err(authority_error(
961                "generated schema authority exceeds the canonical byte ceiling",
962            ));
963        }
964        let authority = decode_schema_authority(
965            envelope.as_bytes(),
966            &schema_authority_capability_vocabulary(),
967        )
968        .map_err(|error| Error::SchemaVerification {
969            message: format!(
970                "generated schema package contains invalid compiled authority ({:?})",
971                error.code()
972            ),
973            source: Some(Box::new(error)),
974        })?;
975        let reconstructed_declared =
976            encode_declared_schema(authority.declared_schema()).map_err(|error| {
977                Error::SchemaVerification {
978                    message: "generated schema authority declaration cannot be reconstructed"
979                        .into(),
980                    source: Some(Box::new(error)),
981                }
982            })?;
983        if reconstructed_declared != declared.as_bytes()
984            || authority.managed_scope().id().as_str() != scope
985            || authority.semantic_profile().id().as_str() != profile
986        {
987            return Err(authority_error(
988                "generated schema authority disagrees with its extracted query evidence",
989            ));
990        }
991        Ok(Some(authority))
992    }
993}
994
995fn verify_rust_projection_evidence(
996    installed: &type_bridge_orm::InstalledRuntimeProjection,
997    authority: Option<&VerifiedSchemaAuthority>,
998) -> Result<()> {
999    let projection = installed.projection();
1000    let emitter = RustEmitter::new();
1001    if projection.config().rust_naming_policy() != ProjectionConfig::rust().rust_naming_policy()
1002        || projection.config().rust_create_policy() != ProjectionConfig::rust().rust_create_policy()
1003    {
1004        return Err(authority_error(
1005            "generated Rust schema package does not match the exact shipped projection configuration",
1006        ));
1007    }
1008    if let Some(authority) = authority {
1009        return type_bridge_schema_codegen::verify_projection_evidence(authority, projection)
1010            .map_err(|error| Error::SchemaVerification {
1011                message: "generated Rust schema package does not match compiled schema authority and exact shipped emitter evidence"
1012                    .into(),
1013                source: Some(Box::new(error)),
1014            });
1015    }
1016
1017    if projection_uses_ordered_collections(projection) {
1018        return Err(authority_error(
1019            "ordered Rust schema packages require compiled schema authority",
1020        ));
1021    }
1022    let resources = emitter
1023        .code_resources()
1024        .map_err(|error| Error::SchemaVerification {
1025            message: "legacy Rust schema package resource evidence cannot be reconstructed".into(),
1026            source: Some(Box::new(error)),
1027        })?;
1028    if projection.generator_handlers() != emitter.generator_handlers()
1029        || projection.code_resources() != resources
1030    {
1031        return Err(authority_error(
1032            "legacy Rust schema package does not match the exact shipped handler and resource evidence",
1033        ));
1034    }
1035
1036    Ok(())
1037}
1038
1039fn projection_uses_ordered_collections(projection: &RuntimeProjection) -> bool {
1040    projection.models().values().any(|model| {
1041        model
1042            .query_tokens()
1043            .fields()
1044            .values()
1045            .any(|field| !field.multiplicity().collection_mode().is_unordered())
1046            || model
1047                .query_tokens()
1048                .roles()
1049                .values()
1050                .any(|role| !role.multiplicity().collection_mode().is_unordered())
1051    })
1052}
1053
1054fn authority_error(message: &'static str) -> Error {
1055    Error::SchemaVerification {
1056        message: message.into(),
1057        source: None,
1058    }
1059}
1060
1061fn projection_evidence_error(presence: SdkProjectionEvidenceSlotPresence) -> Error {
1062    Error::projection_evidence_rejection(presence)
1063}
1064
1065fn classify_admission_error(
1066    successor: bool,
1067    semantic_fingerprint_presence: SdkProjectionEvidenceSlotPresence,
1068    error: Error,
1069) -> Error {
1070    if successor {
1071        projection_evidence_error(semantic_fingerprint_presence)
1072    } else {
1073        error
1074    }
1075}
1076
1077#[cfg(test)]
1078mod tests {
1079    use super::*;
1080    use serde_json::Value;
1081    use type_bridge_contract::codec::to_canonical_json;
1082    use type_bridge_contract::fingerprint::{
1083        CanonicalizationVersion, Fingerprint, FingerprintDomain, SemanticProfileId,
1084    };
1085    use type_bridge_contract::managed_scope::ManagedScopeId;
1086    use type_bridge_contract::projection::{BindingTarget, ProjectionConfig};
1087    use type_bridge_contract::schema::{DocumentId, encode_declared_schema};
1088    use type_bridge_contract::sdk_diagnostic::{
1089        SdkDiagnosticCategory, SdkDiagnosticDetailValue, SdkDiagnosticPathSegment,
1090        SdkExecutionDiagnostic,
1091    };
1092    use type_bridge_schema::{
1093        ManagedDeltaContext, SCHEMA_AUTHORITY_FINGERPRINT_CANONICALIZATION,
1094        SCHEMA_AUTHORITY_FINGERPRINT_DOMAIN, SchemaDocumentSet, build_schema_authority,
1095        encode_schema_authority, normalize_documents, project, resolve,
1096    };
1097    use type_bridge_schema_codegen::{PythonEmitter, RustEmitter};
1098    use type_bridge_schema_migration::{
1099        MigrationHistoryGraph, VerifiedMigrationHistoryBundle,
1100        encode_verified_migration_history_bundle,
1101    };
1102
1103    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1104    struct TestSchema;
1105    impl sealed::Sealed for TestSchema {}
1106    impl Schema for TestSchema {}
1107
1108    fn leak(bytes: Vec<u8>) -> &'static str {
1109        Box::leak(String::from_utf8(bytes).unwrap().into_boxed_str())
1110    }
1111
1112    fn generated_package(source: &str, scope: &str) -> SchemaPackage<TestSchema> {
1113        package_with_evidence(source, scope, None, None)
1114    }
1115
1116    fn package_with_evidence(
1117        source: &str,
1118        scope: &str,
1119        handlers: Option<Vec<type_bridge_contract::projection::ProjectionHandler>>,
1120        resources: Option<Vec<type_bridge_contract::projection::CodeResourceDigest>>,
1121    ) -> SchemaPackage<TestSchema> {
1122        let documents =
1123            SchemaDocumentSet::parse([(DocumentId::new("authority-test.yaml").unwrap(), source)])
1124                .unwrap();
1125        let declared = normalize_documents(&documents).unwrap();
1126        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
1127        let resolved = resolve(&declared, &profile).unwrap();
1128        let authority = build_schema_authority(
1129            &declared,
1130            declared.required_capabilities(),
1131            &ManagedDeltaContext::new(
1132                ManagedScopeId::new(scope).unwrap(),
1133                profile,
1134                schema_authority_capability_vocabulary(),
1135            ),
1136        )
1137        .unwrap();
1138        let emitter = RustEmitter::new();
1139        let handlers = handlers.unwrap_or_else(|| emitter.generator_handlers_for(&resolved));
1140        let resources = resources.unwrap_or_else(|| emitter.code_resources_for(&resolved).unwrap());
1141        let projection = project(
1142            &resolved,
1143            BindingTarget::Rust,
1144            &ProjectionConfig::rust(),
1145            &handlers,
1146            &resources,
1147        )
1148        .unwrap();
1149        SchemaPackage::new_with_authority(
1150            leak(to_canonical_json(projection.semantic_fingerprint()).unwrap()),
1151            leak(to_canonical_json(projection.projection_fingerprint()).unwrap()),
1152            leak(to_canonical_json(&projection).unwrap()),
1153            leak(encode_schema_authority(&authority)),
1154            leak(encode_declared_schema(&declared).unwrap()),
1155            Box::leak(scope.to_owned().into_boxed_str()),
1156            "typedb-3.12.1/v1",
1157        )
1158    }
1159
1160    fn without_authority(package: SchemaPackage<TestSchema>) -> SchemaPackage<TestSchema> {
1161        SchemaPackage::new(
1162            package.semantic_fingerprint_json,
1163            package.projection_fingerprint_json,
1164            package.runtime_projection_json,
1165        )
1166    }
1167
1168    fn with_runtime_projection(
1169        package: SchemaPackage<TestSchema>,
1170        runtime_projection_json: &'static str,
1171    ) -> SchemaPackage<TestSchema> {
1172        SchemaPackage::new_with_authority(
1173            package.semantic_fingerprint_json,
1174            package.projection_fingerprint_json,
1175            runtime_projection_json,
1176            package.schema_authority_json.unwrap(),
1177            package.declared_schema_json.unwrap(),
1178            package.managed_scope_id.unwrap(),
1179            package.semantic_profile_id.unwrap(),
1180        )
1181    }
1182
1183    fn with_envelope(
1184        package: SchemaPackage<TestSchema>,
1185        envelope: &'static str,
1186    ) -> SchemaPackage<TestSchema> {
1187        SchemaPackage::new_with_authority(
1188            package.semantic_fingerprint_json,
1189            package.projection_fingerprint_json,
1190            package.runtime_projection_json,
1191            envelope,
1192            package.declared_schema_json.unwrap(),
1193            package.managed_scope_id.unwrap(),
1194            package.semantic_profile_id.unwrap(),
1195        )
1196    }
1197
1198    fn with_semantic_fingerprint(
1199        package: SchemaPackage<TestSchema>,
1200        semantic_fingerprint_json: &'static str,
1201    ) -> SchemaPackage<TestSchema> {
1202        SchemaPackage::new_with_authority(
1203            semantic_fingerprint_json,
1204            package.projection_fingerprint_json,
1205            package.runtime_projection_json,
1206            package.schema_authority_json.unwrap(),
1207            package.declared_schema_json.unwrap(),
1208            package.managed_scope_id.unwrap(),
1209            package.semantic_profile_id.unwrap(),
1210        )
1211    }
1212
1213    fn canonical(value: &Value) -> &'static str {
1214        leak(to_canonical_json(value).unwrap())
1215    }
1216
1217    #[test]
1218    fn authority_backed_package_opens_and_fences_generated_migration_catalogs_offline() {
1219        let package = generated_package(
1220            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
1221            "rust-migration-catalog",
1222        );
1223        let graph = MigrationHistoryGraph::from_verified(std::iter::empty::<
1224            type_bridge_schema_migration::VerifiedSchemaMigrationManifest,
1225        >())
1226        .unwrap();
1227        let bundle = VerifiedMigrationHistoryBundle::from_graph(&graph).unwrap();
1228        let bytes = encode_verified_migration_history_bundle(&bundle).unwrap();
1229        let catalog = package
1230            .open_migration_catalog(&bytes)
1231            .expect("verified generated bundle opens without provider I/O");
1232        assert!(catalog.is_empty());
1233        assert_eq!(catalog.fingerprint(), bundle.fingerprint());
1234        let preview = catalog
1235            .preview_apply(Vec::new(), None)
1236            .expect("empty generated catalog previews without provider I/O");
1237        assert!(preview.is_apply());
1238        assert!(preview.is_empty());
1239        assert!(!preview.execution_authorized());
1240        let approvals = preview
1241            .approval_builder()
1242            .finish()
1243            .expect("empty exact approval set freezes");
1244        assert!(approvals.is_empty());
1245        let executable = preview
1246            .authorize(&approvals)
1247            .expect("fresh plan is authorized from the exact preview owner");
1248        assert!(executable.execution_authorized());
1249        let foreign_preview = catalog.preview_apply(Vec::new(), None).unwrap();
1250        let mismatch = foreign_preview
1251            .authorize(&approvals)
1252            .expect_err("approval owner mismatch rejects");
1253        assert!(
1254            mismatch
1255                .message()
1256                .contains("migration_approval_plan_mismatch")
1257        );
1258
1259        let mut tampered: Value = serde_json::from_slice(&bytes).unwrap();
1260        tampered["format"] = Value::String("foreign.history/v1".to_owned());
1261        let tampered = to_canonical_json(&tampered).unwrap();
1262        let error = package
1263            .open_migration_catalog(&tampered)
1264            .expect_err("foreign bundle rejects before provider I/O");
1265        assert!(matches!(error, Error::SchemaVerification { .. }));
1266    }
1267
1268    fn resign(value: &mut Value) {
1269        let content = to_canonical_json(&value["content"]).unwrap();
1270        let fingerprint = Fingerprint::compute(
1271            FingerprintDomain::new(SCHEMA_AUTHORITY_FINGERPRINT_DOMAIN).unwrap(),
1272            CanonicalizationVersion::new(SCHEMA_AUTHORITY_FINGERPRINT_CANONICALIZATION).unwrap(),
1273            None,
1274            &content,
1275        );
1276        value["authority_fingerprint"] = serde_json::to_value(fingerprint).unwrap();
1277    }
1278
1279    fn assert_projection_evidence_mismatch(error: &Error) {
1280        assert_eq!(error.category(), crate::ErrorCategory::Integrity);
1281        assert_eq!(error.model_validation_phase(), None);
1282        assert_eq!(error.code(), Some("projection_evidence_mismatch"));
1283        assert_eq!(
1284            error.path().expect("evidence mismatch has a stable path"),
1285            ["projection_evidence"],
1286        );
1287        assert_eq!(
1288            error.message(),
1289            "Generated projection evidence does not match the verified schema package",
1290        );
1291        assert!(matches!(
1292            error
1293                .diagnostic_path()
1294                .expect("evidence mismatch retains its typed path"),
1295            [crate::ErrorPathSegment::Argument(name)] if name == "projection_evidence"
1296        ));
1297        assert!(
1298            error
1299                .details()
1300                .expect("evidence mismatch retains typed details")
1301                .is_empty()
1302        );
1303
1304        let diagnostic = std::error::Error::source(error)
1305            .and_then(|source| source.downcast_ref::<SdkExecutionDiagnostic>())
1306            .expect("the public Rust error retains the common SDK diagnostic");
1307        assert_eq!(diagnostic.category(), SdkDiagnosticCategory::Integrity);
1308        assert!(matches!(
1309            diagnostic.path(),
1310            [SdkDiagnosticPathSegment::Argument(name)]
1311                if name.as_str() == "projection_evidence"
1312        ));
1313        assert!(diagnostic.details().is_empty());
1314    }
1315
1316    fn assert_missing_semantic_fingerprint(error: &Error) {
1317        assert_eq!(error.category(), crate::ErrorCategory::Integrity);
1318        assert_eq!(error.model_validation_phase(), None);
1319        assert_eq!(error.code(), Some("projection_evidence_mismatch"));
1320        assert_eq!(
1321            error.path().expect("missing evidence has a stable path"),
1322            ["projection_evidence", "[0]", "semantic_schema_fingerprint",],
1323        );
1324        assert!(matches!(
1325            error
1326                .diagnostic_path()
1327                .expect("missing evidence retains its typed path"),
1328            [
1329                crate::ErrorPathSegment::Argument(argument),
1330                crate::ErrorPathSegment::Index(0),
1331                crate::ErrorPathSegment::ContractIdentity(identity),
1332            ] if argument == "projection_evidence"
1333                && identity == "semantic_schema_fingerprint"
1334        ));
1335        assert_eq!(
1336            error
1337                .details()
1338                .expect("missing evidence retains typed details"),
1339            &std::collections::BTreeMap::from([
1340                (
1341                    "actual_occurrence_count".to_owned(),
1342                    crate::ErrorDetail::Long(0),
1343                ),
1344                (
1345                    "expected_occurrence_count".to_owned(),
1346                    crate::ErrorDetail::Long(1),
1347                ),
1348                (
1349                    "foreign_package".to_owned(),
1350                    crate::ErrorDetail::Boolean(false),
1351                ),
1352            ]),
1353        );
1354
1355        let diagnostic = std::error::Error::source(error)
1356            .and_then(|source| source.downcast_ref::<SdkExecutionDiagnostic>())
1357            .expect("the Rust error retains the exact common SDK diagnostic");
1358        assert!(matches!(
1359            diagnostic.path(),
1360            [
1361                SdkDiagnosticPathSegment::Argument(argument),
1362                SdkDiagnosticPathSegment::Index(0),
1363                SdkDiagnosticPathSegment::ContractIdentity(identity),
1364            ] if argument.as_str() == "projection_evidence"
1365                && identity.as_str() == "semantic_schema_fingerprint"
1366        ));
1367        assert_eq!(
1368            diagnostic
1369                .details()
1370                .iter()
1371                .map(|(name, value)| (name.as_str(), value))
1372                .collect::<Vec<_>>(),
1373            vec![
1374                (
1375                    "actual_occurrence_count",
1376                    &SdkDiagnosticDetailValue::Count(0),
1377                ),
1378                (
1379                    "expected_occurrence_count",
1380                    &SdkDiagnosticDetailValue::Count(1),
1381                ),
1382                ("foreign_package", &SdkDiagnosticDetailValue::Boolean(false),),
1383            ],
1384        );
1385    }
1386
1387    #[test]
1388    fn compiled_authority_is_fully_verified_and_bound_to_projection() {
1389        let package = generated_package(
1390            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
1391            "rust-authority-test",
1392        );
1393        let (projection, authority) = package.verify_and_install_with_authority().unwrap();
1394        let authority = authority.expect("generated package has compiled authority");
1395        assert_eq!(
1396            projection.projection().semantic_fingerprint(),
1397            authority.resolved_schema().semantic_fingerprint(),
1398        );
1399
1400        let foreign = generated_package(
1401            "format: typebridge.schema/v2\nentities:\n  organization: {}\n",
1402            "rust-authority-test",
1403        );
1404        let mismatched: SchemaPackage<TestSchema> = SchemaPackage::new_with_authority(
1405            package.semantic_fingerprint_json,
1406            package.projection_fingerprint_json,
1407            package.runtime_projection_json,
1408            foreign.schema_authority_json.unwrap(),
1409            foreign.declared_schema_json.unwrap(),
1410            foreign.managed_scope_id.unwrap(),
1411            foreign.semantic_profile_id.unwrap(),
1412        );
1413        let error = mismatched
1414            .verify()
1415            .expect_err("foreign semantic authority must not bind to the projection");
1416        assert_projection_evidence_mismatch(&error);
1417    }
1418
1419    #[test]
1420    fn ordered_package_requires_exact_successor_handler_and_compiled_authority() {
1421        const ORDERED: &str = "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n        distinct: true\n";
1422
1423        let valid = generated_package(ORDERED, "rust-ordered-evidence");
1424        let installed = valid.verify_and_install().unwrap();
1425        assert_eq!(
1426            installed.projection().generator_handlers(),
1427            [type_bridge_contract::projection::ProjectionHandler::rust_v2()],
1428        );
1429        let resource_ids = installed
1430            .projection()
1431            .code_resources()
1432            .iter()
1433            .map(|resource| resource.id().as_str())
1434            .collect::<Vec<_>>();
1435        assert_eq!(
1436            resource_ids,
1437            [
1438                "typebridge.generator.rust.cargo-toml",
1439                "typebridge.generator.rust.runtime-source",
1440            ],
1441        );
1442        assert_ne!(
1443            installed.projection().code_resources(),
1444            RustEmitter::new().code_resources().unwrap(),
1445            "the ordered package must carry the successor runtime-resource digest",
1446        );
1447
1448        let legacy = package_with_evidence(
1449            ORDERED,
1450            "rust-ordered-evidence",
1451            Some(vec![
1452                type_bridge_contract::projection::ProjectionHandler::rust_v1(),
1453            ]),
1454            Some(RustEmitter::new().code_resources().unwrap()),
1455        );
1456        let error = legacy
1457            .verify()
1458            .expect_err("an ordered package cannot claim the legacy Rust ledger");
1459        assert_projection_evidence_mismatch(&error);
1460
1461        let authorityless = without_authority(valid);
1462        let error = authorityless
1463            .verify()
1464            .expect_err("ordered packages require reconstructable schema authority");
1465        assert_projection_evidence_mismatch(&error);
1466
1467        let diagnostic = authorityless
1468            .generated_projection_validator()
1469            .err()
1470            .expect("ordered successor validation must reject the detached package");
1471        assert_eq!(diagnostic.code(), "projection_evidence_mismatch");
1472        assert_eq!(diagnostic.field(), "projection_evidence");
1473    }
1474
1475    #[test]
1476    fn package_rejects_missing_forged_and_foreign_resource_evidence() {
1477        const UNORDERED: &str = "format: typebridge.schema/v2\nentities:\n  person: {}\n";
1478        const ORDERED: &str = "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n";
1479
1480        let missing = package_with_evidence(
1481            ORDERED,
1482            "rust-resource-evidence",
1483            Some(vec![
1484                type_bridge_contract::projection::ProjectionHandler::rust_v2(),
1485            ]),
1486            Some(Vec::new()),
1487        );
1488        let error = missing
1489            .verify()
1490            .expect_err("ordered resource evidence is mandatory");
1491        assert_projection_evidence_mismatch(&error);
1492
1493        let emitter = RustEmitter::new();
1494        let documents =
1495            SchemaDocumentSet::parse([(DocumentId::new("forged-resource.yaml").unwrap(), ORDERED)])
1496                .unwrap();
1497        let declared = normalize_documents(&documents).unwrap();
1498        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
1499        let resolved = resolve(&declared, &profile).unwrap();
1500        let mut forged_resources = emitter.code_resources_for(&resolved).unwrap();
1501        let first_id = forged_resources[0].id().as_str().to_owned();
1502        forged_resources[0] = type_bridge_contract::projection::CodeResourceDigest::from_bytes(
1503            first_id,
1504            b"forged Rust emitter resource",
1505        )
1506        .unwrap();
1507        let forged = package_with_evidence(
1508            ORDERED,
1509            "rust-resource-evidence",
1510            Some(emitter.generator_handlers_for(&resolved)),
1511            Some(forged_resources),
1512        );
1513        let error = forged
1514            .verify()
1515            .expect_err("self-consistent forged resource evidence must reject");
1516        assert_projection_evidence_mismatch(&error);
1517
1518        let foreign_resources = type_bridge_schema_codegen::PythonEmitter::new()
1519            .code_resources_for(&resolved)
1520            .unwrap();
1521        let foreign = package_with_evidence(
1522            ORDERED,
1523            "rust-resource-evidence",
1524            Some(emitter.generator_handlers_for(&resolved)),
1525            Some(foreign_resources),
1526        );
1527        let error = foreign
1528            .verify()
1529            .expect_err("foreign binding resource evidence must reject");
1530        assert_projection_evidence_mismatch(&error);
1531
1532        let valid_legacy = generated_package(UNORDERED, "rust-resource-evidence");
1533        let installed_legacy = valid_legacy.verify_and_install().unwrap();
1534        assert_eq!(
1535            installed_legacy.projection().generator_handlers(),
1536            [type_bridge_contract::projection::ProjectionHandler::rust_v1()],
1537        );
1538        assert_eq!(
1539            installed_legacy.projection().code_resources(),
1540            RustEmitter::new().code_resources().unwrap(),
1541        );
1542        assert!(without_authority(valid_legacy).verify().is_ok());
1543    }
1544
1545    #[test]
1546    fn successor_admission_classifies_only_absent_detached_semantic_fingerprint() {
1547        let package = generated_package(
1548            "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n",
1549            "rust-missing-semantic-evidence",
1550        );
1551        let malformed = with_semantic_fingerprint(package, "{")
1552            .verify()
1553            .expect_err("nonempty malformed semantic evidence must reject");
1554        assert_projection_evidence_mismatch(&malformed);
1555
1556        let error = with_semantic_fingerprint(package, "")
1557            .verify()
1558            .expect_err("an absent detached semantic fingerprint must reject");
1559        assert_missing_semantic_fingerprint(&error);
1560    }
1561
1562    #[test]
1563    fn package_rejects_stale_and_reordered_evidence() {
1564        const UNORDERED: &str = "format: typebridge.schema/v2\nentities:\n  person: {}\n";
1565        const ORDERED: &str = "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n";
1566
1567        let emitter = RustEmitter::new();
1568        let ordered_documents =
1569            SchemaDocumentSet::parse([(DocumentId::new("stale-resource.yaml").unwrap(), ORDERED)])
1570                .unwrap();
1571        let ordered_declared = normalize_documents(&ordered_documents).unwrap();
1572        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
1573        let ordered_resolved = resolve(&ordered_declared, &profile).unwrap();
1574        let stale_successor = package_with_evidence(
1575            UNORDERED,
1576            "rust-stale-evidence",
1577            Some(emitter.generator_handlers_for(&ordered_resolved)),
1578            Some(emitter.code_resources_for(&ordered_resolved).unwrap()),
1579        );
1580        let error = stale_successor
1581            .verify()
1582            .expect_err("an unordered package cannot claim successor evidence");
1583        assert_projection_evidence_mismatch(&error);
1584
1585        let ordered = generated_package(ORDERED, "rust-reordered-evidence");
1586        let mut runtime: Value = serde_json::from_str(ordered.runtime_projection_json).unwrap();
1587        runtime["code_resources"]
1588            .as_array_mut()
1589            .expect("runtime projection has a resource ledger")
1590            .swap(0, 1);
1591        let reordered = with_runtime_projection(ordered, canonical(&runtime));
1592        let error = reordered
1593            .verify()
1594            .expect_err("resource ledger wire order is canonical and cannot be changed");
1595        assert_projection_evidence_mismatch(&error);
1596    }
1597
1598    #[test]
1599    fn authority_backed_admission_normalizes_malformed_extra_and_duplicate_evidence() {
1600        const ORDERED: &str = "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n";
1601        let package = generated_package(ORDERED, "rust-malformed-evidence");
1602
1603        let malformed = with_envelope(package, "{")
1604            .verify()
1605            .expect_err("malformed authority evidence must reject");
1606        assert_projection_evidence_mismatch(&malformed);
1607
1608        let runtime: Value = serde_json::from_str(package.runtime_projection_json).unwrap();
1609        let resource = runtime["code_resources"]
1610            .as_array()
1611            .and_then(|resources| resources.first())
1612            .cloned()
1613            .expect("successor projection carries resource evidence");
1614
1615        let mut duplicate_runtime = runtime.clone();
1616        duplicate_runtime["code_resources"]
1617            .as_array_mut()
1618            .unwrap()
1619            .push(resource.clone());
1620        let duplicate = with_runtime_projection(package, canonical(&duplicate_runtime))
1621            .verify()
1622            .expect_err("duplicate resource evidence must reject");
1623        assert_projection_evidence_mismatch(&duplicate);
1624
1625        let mut extra_resource = resource;
1626        extra_resource["id"] = Value::String("typebridge.generator.rust.zzz-extra".into());
1627        let mut extra_runtime = runtime;
1628        extra_runtime["code_resources"]
1629            .as_array_mut()
1630            .unwrap()
1631            .push(extra_resource);
1632        let extra = with_runtime_projection(package, canonical(&extra_runtime))
1633            .verify()
1634            .expect_err("extra resource evidence must reject");
1635        assert_projection_evidence_mismatch(&extra);
1636    }
1637
1638    #[test]
1639    fn compiled_authority_rejects_missing_and_stale_outer_fingerprints() {
1640        let package = generated_package(
1641            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
1642            "rust-authority-test",
1643        );
1644        let original: Value = serde_json::from_str(package.schema_authority_json.unwrap()).unwrap();
1645
1646        let mut missing = original.clone();
1647        missing
1648            .as_object_mut()
1649            .unwrap()
1650            .remove("authority_fingerprint");
1651        let error = with_envelope(package, canonical(&missing))
1652            .verify()
1653            .expect_err("missing authority fingerprint must reject");
1654        assert_projection_evidence_mismatch(&error);
1655
1656        let mut stale = original;
1657        stale["authority_fingerprint"]["digest"] = "0".repeat(64).into();
1658        let error = with_envelope(package, canonical(&stale))
1659            .verify()
1660            .expect_err("stale authority fingerprint must reject");
1661        assert_projection_evidence_mismatch(&error);
1662    }
1663
1664    #[test]
1665    fn compiled_authority_reconstructs_managed_state_and_rejects_unsupported_claims() {
1666        let package = generated_package(
1667            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
1668            "rust-authority-test",
1669        );
1670        let original: Value = serde_json::from_str(package.schema_authority_json.unwrap()).unwrap();
1671
1672        let mut managed = original.clone();
1673        managed["content"]["managed_state"]["declared_identity"]["digest"] = "0".repeat(64).into();
1674        resign(&mut managed);
1675        let error = with_envelope(package, canonical(&managed))
1676            .verify()
1677            .expect_err("detached managed-state evidence must reject");
1678        assert_projection_evidence_mismatch(&error);
1679
1680        let mut capabilities = original.clone();
1681        capabilities["content"]["required_capabilities"] =
1682            Value::Array(vec![Value::String("unsupported.runtime".into())]);
1683        resign(&mut capabilities);
1684        let error = with_envelope(package, canonical(&capabilities))
1685            .verify()
1686            .expect_err("unsupported artifact capability must fail closed");
1687        assert_projection_evidence_mismatch(&error);
1688
1689        let mut version = original;
1690        version["content"]["authority_version"] =
1691            Value::String("typebridge.schema-authority/v2".into());
1692        resign(&mut version);
1693        let error = with_envelope(package, canonical(&version))
1694            .verify()
1695            .expect_err("unsupported artifact version must fail closed");
1696        assert_projection_evidence_mismatch(&error);
1697    }
1698
1699    #[test]
1700    fn compiled_authority_rejects_oversize_and_detached_evidence() {
1701        let package = generated_package(
1702            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
1703            "rust-authority-test",
1704        );
1705        let oversized = Box::leak(" ".repeat(MAX_SCHEMA_AUTHORITY_BYTES + 1).into_boxed_str());
1706        let error = with_envelope(package, oversized)
1707            .verify()
1708            .expect_err("oversize authority must fail before parsing");
1709        assert_projection_evidence_mismatch(&error);
1710
1711        let detached: SchemaPackage<TestSchema> = SchemaPackage::new_with_authority(
1712            package.semantic_fingerprint_json,
1713            package.projection_fingerprint_json,
1714            package.runtime_projection_json,
1715            package.schema_authority_json.unwrap(),
1716            package.declared_schema_json.unwrap(),
1717            "other-scope",
1718            package.semantic_profile_id.unwrap(),
1719        );
1720        let error = detached
1721            .verify()
1722            .expect_err("detached scope must not override compiled authority");
1723        assert_projection_evidence_mismatch(&error);
1724    }
1725
1726    #[test]
1727    fn schema_package_fingerprint_verification() {
1728        let documents = SchemaDocumentSet::parse([(
1729            DocumentId::new("test.yaml").unwrap(),
1730            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
1731        )])
1732        .unwrap();
1733        let declared = normalize_documents(&documents).unwrap();
1734        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
1735        let resolved = resolve(&declared, &profile).unwrap();
1736        let emitter = RustEmitter::new();
1737        let resources = emitter.code_resources().unwrap();
1738        let projection = project(
1739            &resolved,
1740            BindingTarget::Rust,
1741            &ProjectionConfig::rust(),
1742            &emitter.generator_handlers(),
1743            &resources,
1744        )
1745        .unwrap();
1746
1747        let semantic_json =
1748            String::from_utf8(to_canonical_json(projection.semantic_fingerprint()).unwrap())
1749                .unwrap();
1750        let projection_json =
1751            String::from_utf8(to_canonical_json(projection.projection_fingerprint()).unwrap())
1752                .unwrap();
1753        let runtime_json = String::from_utf8(to_canonical_json(&projection).unwrap()).unwrap();
1754
1755        let semantic_ref: &'static str = Box::leak(semantic_json.into_boxed_str());
1756        let projection_ref: &'static str = Box::leak(projection_json.into_boxed_str());
1757        let runtime_ref: &'static str = Box::leak(runtime_json.into_boxed_str());
1758
1759        let valid_package: SchemaPackage<TestSchema> =
1760            SchemaPackage::new(semantic_ref, projection_ref, runtime_ref);
1761        assert!(valid_package.verify().is_ok());
1762
1763        let tampered_package: SchemaPackage<TestSchema> =
1764            SchemaPackage::new(semantic_ref, r#""rust/v1-tampered""#, runtime_ref);
1765        match tampered_package.verify() {
1766            Err(err) => {
1767                use std::error::Error as _;
1768                assert_eq!(err.category(), crate::ErrorCategory::Schema);
1769                assert_eq!(err.code(), None);
1770                assert_eq!(err.path(), None);
1771                assert!(err.source().is_some());
1772            }
1773            Ok(_) => panic!("tampered schema package must fail verification"),
1774        }
1775    }
1776
1777    #[test]
1778    fn rejects_non_rust_target_projection() {
1779        let documents = SchemaDocumentSet::parse([(
1780            DocumentId::new("test.yaml").unwrap(),
1781            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
1782        )])
1783        .unwrap();
1784        let declared = normalize_documents(&documents).unwrap();
1785        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
1786        let resolved = resolve(&declared, &profile).unwrap();
1787        let py_emitter = PythonEmitter::new();
1788        let py_resources = py_emitter.code_resources().unwrap();
1789        let py_projection = project(
1790            &resolved,
1791            BindingTarget::Python,
1792            &ProjectionConfig::python(),
1793            &py_emitter.generator_handlers(),
1794            &py_resources,
1795        )
1796        .unwrap();
1797
1798        let semantic_json =
1799            String::from_utf8(to_canonical_json(py_projection.semantic_fingerprint()).unwrap())
1800                .unwrap();
1801        let projection_json =
1802            String::from_utf8(to_canonical_json(py_projection.projection_fingerprint()).unwrap())
1803                .unwrap();
1804        let runtime_json = String::from_utf8(to_canonical_json(&py_projection).unwrap()).unwrap();
1805
1806        let semantic_ref: &'static str = Box::leak(semantic_json.into_boxed_str());
1807        let projection_ref: &'static str = Box::leak(projection_json.into_boxed_str());
1808        let runtime_ref: &'static str = Box::leak(runtime_json.into_boxed_str());
1809
1810        let py_package: SchemaPackage<TestSchema> =
1811            SchemaPackage::new(semantic_ref, projection_ref, runtime_ref);
1812        let err = py_package.verify().unwrap_err();
1813        assert_eq!(err.category(), crate::ErrorCategory::Schema);
1814        assert_eq!(err.code(), None);
1815        assert_eq!(err.path(), None);
1816        assert!(err.to_string().contains("target mismatch") || err.to_string().contains("Rust"));
1817    }
1818}