Skip to main content

stateknot_core/
model_invocation.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Durable, integrity-bound state machine for logical model invocations.
5//!
6//! A logical invocation snapshots one validated model binding and request while
7//! every real provider exchange receives a new [`AttemptId`]. The runtime first
8//! commits `prepared`, durably claims `executing`, performs exactly one provider
9//! exchange with SDK retries disabled, and finally commits a complete response
10//! or public-safe failure. Partial streaming output is never a committed result.
11
12use std::{fmt, str::FromStr};
13
14use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
15use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
16use thiserror::Error;
17
18use crate::decimal::{UnsignedDecimalError, parse_bounded_u64};
19use crate::{
20    AttemptId, CapabilityLifecycleState, Digest, InvocationId, JournalHead, JournalSequence,
21    ModelCapabilityMismatch, ModelDescriptor, ModelError, ModelErrorPhase,
22    ModelErrorValidationError, ModelRequest, ModelResponse, ModelResponseError, NodeActivation,
23    RunId, TenantId, Timestamp,
24};
25
26const MAX_DATABASE_ORDINAL: u64 = i64::MAX as u64;
27const INVOCATION_REVISION_PATTERN: &str = "^(0|[1-9][0-9]{0,18})$";
28const INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-model-invocation-intent-v1\0";
29const TRANSITION_DIGEST_DOMAIN: &[u8] = b"stateknot-model-invocation-transition-v1\0";
30const RECORD_DIGEST_DOMAIN: &[u8] = b"stateknot-model-invocation-record-v1\0";
31
32/// Monotonic zero-based revision of one logical model invocation.
33///
34/// The decimal-string wire form preserves exact values across languages and
35/// the maximum matches a signed `PostgreSQL BIGINT`.
36#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
37pub struct ModelInvocationRevision(u64);
38
39impl ModelInvocationRevision {
40    /// Preparation record revision.
41    pub const INITIAL: Self = Self(0);
42    /// Largest revision supported by the v1 storage contract.
43    pub const MAX: Self = Self(MAX_DATABASE_ORDINAL);
44
45    /// Constructs a storage-compatible revision.
46    ///
47    /// # Errors
48    ///
49    /// Returns [`ModelInvocationRevisionError::AboveMaximum`] above signed
50    /// `BIGINT`.
51    pub const fn new(value: u64) -> Result<Self, ModelInvocationRevisionError> {
52        if value > MAX_DATABASE_ORDINAL {
53            return Err(ModelInvocationRevisionError::AboveMaximum);
54        }
55        Ok(Self(value))
56    }
57
58    /// Returns the integer revision.
59    #[must_use]
60    pub const fn get(self) -> u64 {
61        self.0
62    }
63
64    /// Returns the exact next revision or `None` at the storage ceiling.
65    #[must_use]
66    pub const fn checked_next(self) -> Option<Self> {
67        if self.0 == MAX_DATABASE_ORDINAL {
68            None
69        } else {
70            Some(Self(self.0 + 1))
71        }
72    }
73}
74
75impl fmt::Display for ModelInvocationRevision {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        self.0.fmt(formatter)
78    }
79}
80
81impl FromStr for ModelInvocationRevision {
82    type Err = ModelInvocationRevisionError;
83
84    fn from_str(value: &str) -> Result<Self, Self::Err> {
85        let value = parse_bounded_u64(value, MAX_DATABASE_ORDINAL)
86            .map_err(ModelInvocationRevisionError::from_decimal_error)?;
87        Self::new(value)
88    }
89}
90
91impl Serialize for ModelInvocationRevision {
92    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
93    where
94        S: Serializer,
95    {
96        serializer.collect_str(self)
97    }
98}
99
100impl<'de> Deserialize<'de> for ModelInvocationRevision {
101    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
102    where
103        D: Deserializer<'de>,
104    {
105        deserializer.deserialize_str(ModelInvocationRevisionVisitor)
106    }
107}
108
109struct ModelInvocationRevisionVisitor;
110
111impl de::Visitor<'_> for ModelInvocationRevisionVisitor {
112    type Value = ModelInvocationRevision;
113
114    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
115        formatter.write_str("a canonical non-negative decimal PostgreSQL BIGINT revision")
116    }
117
118    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
119    where
120        E: de::Error,
121    {
122        value.parse().map_err(E::custom)
123    }
124}
125
126impl JsonSchema for ModelInvocationRevision {
127    fn schema_name() -> std::borrow::Cow<'static, str> {
128        "ModelInvocationRevision".into()
129    }
130
131    fn schema_id() -> std::borrow::Cow<'static, str> {
132        concat!(module_path!(), "::ModelInvocationRevision").into()
133    }
134
135    fn json_schema(_: &mut SchemaGenerator) -> Schema {
136        json_schema!({
137            "type": "string",
138            "minLength": 1,
139            "maxLength": 19,
140            "pattern": INVOCATION_REVISION_PATTERN
141        })
142    }
143
144    fn inline_schema() -> bool {
145        true
146    }
147}
148
149/// Invalid canonical model invocation revision.
150#[derive(Clone, Debug, Eq, Error, PartialEq)]
151#[non_exhaustive]
152pub enum ModelInvocationRevisionError {
153    /// The wire value was empty or contained a non-decimal byte.
154    #[error("model invocation revision must contain only unsigned ASCII decimal digits")]
155    InvalidFormat,
156    /// The decimal text contained a leading zero.
157    #[error("model invocation revision must use canonical decimal text")]
158    NonCanonical,
159    /// The value exceeded signed `PostgreSQL BIGINT`.
160    #[error("model invocation revision exceeds the PostgreSQL BIGINT maximum")]
161    AboveMaximum,
162}
163
164impl ModelInvocationRevisionError {
165    const fn from_decimal_error(error: UnsignedDecimalError) -> Self {
166        match error {
167            UnsignedDecimalError::Empty | UnsignedDecimalError::InvalidCharacter { .. } => {
168                Self::InvalidFormat
169            }
170            UnsignedDecimalError::LeadingZero => Self::NonCanonical,
171            UnsignedDecimalError::TooLong { .. } | UnsignedDecimalError::Overflow => {
172                Self::AboveMaximum
173            }
174        }
175    }
176}
177
178/// Immutable preparation intent for one logical model invocation.
179///
180/// The descriptor and request are complete execution snapshots. Credentials,
181/// SDK clients, provider aliases, process-local cancellation state, and mutable
182/// budget counters remain outside this durable value.
183#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
184#[serde(deny_unknown_fields)]
185pub struct ModelInvocationIntent {
186    activation: NodeActivation,
187    invocation_id: InvocationId,
188    descriptor: ModelDescriptor,
189    request: ModelRequest,
190    intent_digest: Digest,
191}
192
193impl ModelInvocationIntent {
194    /// Constructs, negotiates, and checksums a durable model invocation intent.
195    ///
196    /// # Errors
197    ///
198    /// Returns [`ModelInvocationIntentError`] when a retired binding is selected,
199    /// the exact descriptor does not satisfy the request, or canonical integrity
200    /// material cannot be produced.
201    pub fn new(
202        activation: NodeActivation,
203        invocation_id: InvocationId,
204        descriptor: ModelDescriptor,
205        request: ModelRequest,
206    ) -> Result<Self, ModelInvocationIntentError> {
207        validate_intent_shape(&descriptor, &request)?;
208        let intent_digest = compute_intent_digest(&ModelInvocationIntentDigestWire {
209            activation: &activation,
210            invocation_id,
211            descriptor: &descriptor,
212            request: &request,
213        })?;
214        Ok(Self {
215            activation,
216            invocation_id,
217            descriptor,
218            request,
219            intent_digest,
220        })
221    }
222
223    /// Restores an intent and verifies its negotiation and checksum layers.
224    ///
225    /// # Errors
226    ///
227    /// Returns [`ModelInvocationIntentError`] when validation or integrity fails.
228    pub fn restore(
229        activation: NodeActivation,
230        invocation_id: InvocationId,
231        descriptor: ModelDescriptor,
232        request: ModelRequest,
233        intent_digest: Digest,
234    ) -> Result<Self, ModelInvocationIntentError> {
235        let restored = Self::new(activation, invocation_id, descriptor, request)?;
236        if restored.intent_digest != intent_digest {
237            return Err(ModelInvocationIntentError::DigestMismatch);
238        }
239        Ok(restored)
240    }
241
242    /// Returns the owning graph-node activation.
243    #[must_use]
244    pub const fn activation(&self) -> &NodeActivation {
245        &self.activation
246    }
247
248    /// Returns the stable logical invocation identifier.
249    #[must_use]
250    pub const fn invocation_id(&self) -> InvocationId {
251        self.invocation_id
252    }
253
254    /// Returns the exact registered model binding snapshot.
255    #[must_use]
256    pub const fn descriptor(&self) -> &ModelDescriptor {
257        &self.descriptor
258    }
259
260    /// Returns the complete immutable provider-neutral request.
261    #[must_use]
262    pub const fn request(&self) -> &ModelRequest {
263        &self.request
264    }
265
266    /// Returns the domain-separated preparation fingerprint.
267    #[must_use]
268    pub const fn intent_digest(&self) -> Digest {
269        self.intent_digest
270    }
271
272    /// Returns the tenant boundary inherited from the activation.
273    #[must_use]
274    pub const fn tenant_id(&self) -> &TenantId {
275        self.activation.tenant_id()
276    }
277
278    /// Returns the run identity inherited from the activation.
279    #[must_use]
280    pub const fn run_id(&self) -> RunId {
281        self.activation.run_id()
282    }
283}
284
285impl fmt::Debug for ModelInvocationIntent {
286    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
287        formatter
288            .debug_struct("ModelInvocationIntent")
289            .field("activation", &self.activation)
290            .field("invocation_id", &self.invocation_id)
291            .field("descriptor", &self.descriptor)
292            .field("request", &self.request)
293            .field("intent_digest", &self.intent_digest)
294            .finish_non_exhaustive()
295    }
296}
297
298impl<'de> Deserialize<'de> for ModelInvocationIntent {
299    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
300    where
301        D: Deserializer<'de>,
302    {
303        #[derive(Deserialize)]
304        #[serde(deny_unknown_fields)]
305        struct Wire {
306            activation: NodeActivation,
307            invocation_id: InvocationId,
308            descriptor: ModelDescriptor,
309            request: ModelRequest,
310            intent_digest: Digest,
311        }
312
313        let wire = Wire::deserialize(deserializer)?;
314        Self::restore(
315            wire.activation,
316            wire.invocation_id,
317            wire.descriptor,
318            wire.request,
319            wire.intent_digest,
320        )
321        .map_err(de::Error::custom)
322    }
323}
324
325/// Invalid durable model invocation intent.
326#[derive(Clone, Debug, Eq, Error, PartialEq)]
327#[non_exhaustive]
328pub enum ModelInvocationIntentError {
329    /// A historical-only model binding was selected for new execution.
330    #[error("retired model binding cannot be selected for a new invocation")]
331    RetiredModel,
332    /// The exact binding cannot satisfy every request requirement.
333    #[error("model binding does not satisfy the invocation request: {mismatch:?}")]
334    CapabilityMismatch {
335        /// Deterministic complete mismatch set.
336        mismatch: Box<ModelCapabilityMismatch>,
337    },
338    /// Canonical integrity material could not be serialized.
339    #[error("model invocation intent integrity calculation failed: {source}")]
340    Integrity {
341        /// Exact integrity failure.
342        #[source]
343        source: ModelInvocationIntegrityError,
344    },
345    /// Persisted intent checksum did not match caller-controlled fields.
346    #[error("model invocation intent digest does not match its fields")]
347    DigestMismatch,
348}
349
350impl From<ModelInvocationIntegrityError> for ModelInvocationIntentError {
351    fn from(source: ModelInvocationIntegrityError) -> Self {
352        Self::Integrity { source }
353    }
354}
355
356/// Durable lifecycle state of one logical model invocation.
357#[derive(
358    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
359)]
360#[serde(rename_all = "snake_case")]
361pub enum ModelInvocationStatus {
362    /// Intent is committed but no provider attempt has started.
363    Prepared,
364    /// Exactly one physical provider attempt has been durably claimed.
365    Executing,
366    /// A complete validated response is durable.
367    Committed,
368    /// A public-safe failed attempt is durable and retry remains policy-gated.
369    Failed,
370}
371
372/// Integrity-bound state payload of one model invocation revision.
373#[derive(Clone, Debug, JsonSchema, Serialize)]
374#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
375#[allow(clippy::large_enum_variant)]
376pub enum ModelInvocationState {
377    /// Prepared request awaiting an attempt claim.
378    Prepared,
379    /// In-flight physical provider attempt.
380    Executing {
381        /// Unique physical attempt identifier.
382        attempt_id: AttemptId,
383    },
384    /// Complete validated provider-neutral response.
385    Committed {
386        /// Exact response and attempt provenance.
387        response: ModelResponse,
388    },
389    /// Failed provider attempt.
390    Failed {
391        /// Public-safe failure, correlation, and optional usage evidence.
392        error: ModelError,
393    },
394}
395
396impl ModelInvocationState {
397    /// Returns the lifecycle discriminator.
398    #[must_use]
399    pub const fn status(&self) -> ModelInvocationStatus {
400        match self {
401            Self::Prepared => ModelInvocationStatus::Prepared,
402            Self::Executing { .. } => ModelInvocationStatus::Executing,
403            Self::Committed { .. } => ModelInvocationStatus::Committed,
404            Self::Failed { .. } => ModelInvocationStatus::Failed,
405        }
406    }
407
408    /// Returns the physical attempt represented by this state, if any.
409    #[must_use]
410    pub const fn attempt_id(&self) -> Option<AttemptId> {
411        match self {
412            Self::Prepared => None,
413            Self::Executing { attempt_id } => Some(*attempt_id),
414            Self::Committed { response } => Some(response.provenance().attempt_id()),
415            Self::Failed { error } => Some(error.provenance().attempt_id()),
416        }
417    }
418}
419
420impl<'de> Deserialize<'de> for ModelInvocationState {
421    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
422    where
423        D: Deserializer<'de>,
424    {
425        #[derive(Deserialize)]
426        #[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
427        #[allow(clippy::large_enum_variant)]
428        enum Wire {
429            Prepared,
430            Executing { attempt_id: AttemptId },
431            Committed { response: ModelResponse },
432            Failed { error: ModelError },
433        }
434
435        Ok(match Wire::deserialize(deserializer)? {
436            Wire::Prepared => Self::Prepared,
437            Wire::Executing { attempt_id } => Self::Executing { attempt_id },
438            Wire::Committed { response } => Self::Committed { response },
439            Wire::Failed { error } => Self::Failed { error },
440        })
441    }
442}
443
444/// Kind of one explicit model invocation state transition.
445#[derive(
446    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
447)]
448#[serde(rename_all = "snake_case")]
449pub enum ModelInvocationTransitionKind {
450    /// Claim a new physical provider attempt.
451    StartAttempt,
452    /// Commit the executing attempt's complete response.
453    RecordResponse,
454    /// Commit the executing attempt's failure evidence.
455    RecordError,
456}
457
458/// Explicit transition appended to the run journal and model history.
459#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize)]
460#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
461#[allow(clippy::large_enum_variant)]
462pub enum ModelInvocationTransition {
463    /// Claim a unique physical attempt after preparation or a safe retry.
464    StartAttempt {
465        /// New physical attempt identity.
466        attempt_id: AttemptId,
467    },
468    /// Commit a complete response from the current executing attempt.
469    RecordResponse {
470        /// Validated provider-neutral response.
471        response: ModelResponse,
472    },
473    /// Commit public-safe failure and optional normalized usage evidence.
474    RecordError {
475        /// Validated attempt failure.
476        error: ModelError,
477    },
478}
479
480impl ModelInvocationTransition {
481    /// Returns the closed transition discriminator.
482    #[must_use]
483    pub const fn kind(&self) -> ModelInvocationTransitionKind {
484        match self {
485            Self::StartAttempt { .. } => ModelInvocationTransitionKind::StartAttempt,
486            Self::RecordResponse { .. } => ModelInvocationTransitionKind::RecordResponse,
487            Self::RecordError { .. } => ModelInvocationTransitionKind::RecordError,
488        }
489    }
490}
491
492/// Compact exact identity of a validated model invocation revision.
493///
494/// A head is an optimistic comparison token. It intentionally omits prompts,
495/// response content, and failures; obtain it from [`ModelInvocation::head`] or
496/// storage that restored and verified the corresponding full record.
497#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
498#[serde(deny_unknown_fields)]
499pub struct ModelInvocationHead {
500    tenant_id: TenantId,
501    run_id: RunId,
502    invocation_id: InvocationId,
503    revision: ModelInvocationRevision,
504    status: ModelInvocationStatus,
505    #[serde(skip_serializing_if = "Option::is_none")]
506    attempt_id: Option<AttemptId>,
507    journal_head: JournalHead,
508    digest: Digest,
509}
510
511impl ModelInvocationHead {
512    /// Constructs a trusted compact head while enforcing scope and state shape.
513    ///
514    /// # Errors
515    ///
516    /// Returns [`ModelInvocationHeadError`] for crossed journal scope or an
517    /// impossible status/attempt/revision combination.
518    #[allow(clippy::too_many_arguments)]
519    pub fn new(
520        tenant_id: TenantId,
521        run_id: RunId,
522        invocation_id: InvocationId,
523        revision: ModelInvocationRevision,
524        status: ModelInvocationStatus,
525        attempt_id: Option<AttemptId>,
526        journal_head: JournalHead,
527        digest: Digest,
528    ) -> Result<Self, ModelInvocationHeadError> {
529        validate_journal_scope(&tenant_id, run_id, &journal_head)
530            .map_err(ModelInvocationHeadError::from_scope)?;
531        validate_status_attempt(status, attempt_id)?;
532        validate_revision_status(revision, status)?;
533        Ok(Self {
534            tenant_id,
535            run_id,
536            invocation_id,
537            revision,
538            status,
539            attempt_id,
540            journal_head,
541            digest,
542        })
543    }
544
545    /// Returns the tenant boundary.
546    #[must_use]
547    pub const fn tenant_id(&self) -> &TenantId {
548        &self.tenant_id
549    }
550
551    /// Returns the durable run identity.
552    #[must_use]
553    pub const fn run_id(&self) -> RunId {
554        self.run_id
555    }
556
557    /// Returns the stable logical invocation identity.
558    #[must_use]
559    pub const fn invocation_id(&self) -> InvocationId {
560        self.invocation_id
561    }
562
563    /// Returns the exact record revision.
564    #[must_use]
565    pub const fn revision(&self) -> ModelInvocationRevision {
566        self.revision
567    }
568
569    /// Returns the lifecycle state at this revision.
570    #[must_use]
571    pub const fn status(&self) -> ModelInvocationStatus {
572        self.status
573    }
574
575    /// Returns the physical attempt represented by this revision, if any.
576    #[must_use]
577    pub const fn attempt_id(&self) -> Option<AttemptId> {
578        self.attempt_id
579    }
580
581    /// Returns the exact journal prefix anchoring this revision.
582    #[must_use]
583    pub const fn journal_head(&self) -> &JournalHead {
584        &self.journal_head
585    }
586
587    /// Returns the complete model-invocation record checksum.
588    #[must_use]
589    pub const fn digest(&self) -> Digest {
590        self.digest
591    }
592}
593
594impl<'de> Deserialize<'de> for ModelInvocationHead {
595    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
596    where
597        D: Deserializer<'de>,
598    {
599        #[derive(Deserialize)]
600        #[serde(deny_unknown_fields)]
601        struct Wire {
602            tenant_id: TenantId,
603            run_id: RunId,
604            invocation_id: InvocationId,
605            revision: ModelInvocationRevision,
606            status: ModelInvocationStatus,
607            attempt_id: Option<AttemptId>,
608            journal_head: JournalHead,
609            digest: Digest,
610        }
611
612        let wire = Wire::deserialize(deserializer)?;
613        Self::new(
614            wire.tenant_id,
615            wire.run_id,
616            wire.invocation_id,
617            wire.revision,
618            wire.status,
619            wire.attempt_id,
620            wire.journal_head,
621            wire.digest,
622        )
623        .map_err(de::Error::custom)
624    }
625}
626
627/// Invalid compact model invocation head.
628#[derive(Clone, Debug, Eq, Error, PartialEq)]
629#[non_exhaustive]
630pub enum ModelInvocationHeadError {
631    /// Journal head crossed the invocation tenant boundary.
632    #[error("model invocation journal head crosses the tenant boundary")]
633    JournalTenantMismatch,
634    /// Journal head named another run.
635    #[error("model invocation journal head does not belong to the run")]
636    JournalRunMismatch,
637    /// Prepared status unexpectedly named a physical attempt.
638    #[error("prepared model invocation head must not contain an attempt")]
639    PreparedHasAttempt,
640    /// A non-prepared status omitted its physical attempt.
641    #[error("non-prepared model invocation head must contain an attempt")]
642    AttemptMissing,
643    /// Revision zero named a state other than preparation.
644    #[error("model invocation head revision zero must be prepared")]
645    InitialStatusMismatch,
646    /// A later revision tried to return to preparation.
647    #[error("prepared model invocation head must use revision zero")]
648    PreparedRevisionMismatch,
649}
650
651impl ModelInvocationHeadError {
652    const fn from_scope(error: InvocationScopeError) -> Self {
653        match error {
654            InvocationScopeError::Tenant => Self::JournalTenantMismatch,
655            InvocationScopeError::Run => Self::JournalRunMismatch,
656        }
657    }
658}
659
660/// One immutable, journal-anchored revision of a logical model invocation.
661///
662/// Deserialization verifies local checksums, scope, descriptor/request/result
663/// binding, and predecessor-head shape. Stream the complete ascending history
664/// through [`ModelInvocationHistoryVerifier`] to prove delayed retry legality.
665#[derive(Clone, JsonSchema, Serialize)]
666#[serde(deny_unknown_fields)]
667pub struct ModelInvocation {
668    intent: ModelInvocationIntent,
669    revision: ModelInvocationRevision,
670    state: ModelInvocationState,
671    #[serde(skip_serializing_if = "Option::is_none")]
672    previous: Option<ModelInvocationHead>,
673    journal_head: JournalHead,
674    #[serde(skip_serializing_if = "Option::is_none")]
675    transition: Option<ModelInvocationTransition>,
676    #[serde(skip_serializing_if = "Option::is_none")]
677    transition_digest: Option<Digest>,
678    digest: Digest,
679}
680
681impl ModelInvocation {
682    /// Materializes the initial prepared revision after its journal event commits.
683    ///
684    /// The journal head must belong to the activation's tenant/run and strictly
685    /// advance the exact base checkpoint without regressing durable time.
686    ///
687    /// # Errors
688    ///
689    /// Returns [`ModelInvocationError`] for scope, ordering, or integrity failure.
690    pub fn prepare(
691        intent: ModelInvocationIntent,
692        journal_head: JournalHead,
693    ) -> Result<Self, ModelInvocationError> {
694        validate_preparation_journal(&intent, &journal_head)?;
695        let revision = ModelInvocationRevision::INITIAL;
696        let state = ModelInvocationState::Prepared;
697        let digest = compute_record_digest(&ModelInvocationRecordDigestWire {
698            intent_digest: intent.intent_digest,
699            revision,
700            state: &state,
701            previous: None,
702            journal_head: &journal_head,
703            transition_digest: None,
704        })?;
705        Ok(Self {
706            intent,
707            revision,
708            state,
709            previous: None,
710            journal_head,
711            transition: None,
712            transition_digest: None,
713            digest,
714        })
715    }
716
717    /// Applies one legal transition and constructs its next immutable revision.
718    ///
719    /// This enforces exact response/error provenance, request/descriptor
720    /// bindings, minimum retry delay, journal order, and revision overflow.
721    /// Stores must still compare [`Self::head`] under the run lock and current
722    /// fencing token, and must enforce run-wide physical attempt uniqueness.
723    ///
724    /// # Errors
725    ///
726    /// Returns [`ModelInvocationError`] when the transition cannot safely commit.
727    pub fn advance(
728        &self,
729        transition: ModelInvocationTransition,
730        journal_head: JournalHead,
731    ) -> Result<Self, ModelInvocationError> {
732        validate_successor_journal(self, &journal_head)?;
733        let revision = self
734            .revision
735            .checked_next()
736            .ok_or(ModelInvocationError::RevisionOverflow)?;
737        let state = apply_transition(self, &transition, journal_head.recorded_at())?;
738        let transition_digest = compute_transition_digest(&transition)?;
739        let previous = self.head();
740        let digest = compute_record_digest(&ModelInvocationRecordDigestWire {
741            intent_digest: self.intent.intent_digest,
742            revision,
743            state: &state,
744            previous: Some(&previous),
745            journal_head: &journal_head,
746            transition_digest: Some(transition_digest),
747        })?;
748        Ok(Self {
749            intent: self.intent.clone(),
750            revision,
751            state,
752            previous: Some(previous),
753            journal_head,
754            transition: Some(transition),
755            transition_digest: Some(transition_digest),
756            digest,
757        })
758    }
759
760    /// Restores a record and verifies every invariant available locally.
761    ///
762    /// Failed-to-executing retry authorization depends on the predecessor's full
763    /// error and is therefore verified by [`ModelInvocationHistoryVerifier`],
764    /// not by a compact predecessor head.
765    ///
766    /// # Errors
767    ///
768    /// Returns [`ModelInvocationError`] for malformed state, provenance, scope,
769    /// ordering, transition checksum, or record checksum.
770    #[allow(clippy::too_many_arguments)]
771    pub fn restore(
772        intent: ModelInvocationIntent,
773        revision: ModelInvocationRevision,
774        state: ModelInvocationState,
775        previous: Option<ModelInvocationHead>,
776        journal_head: JournalHead,
777        transition: Option<ModelInvocationTransition>,
778        transition_digest: Option<Digest>,
779        digest: Digest,
780    ) -> Result<Self, ModelInvocationError> {
781        validate_record_shape(
782            &intent,
783            revision,
784            &state,
785            previous.as_ref(),
786            &journal_head,
787            transition.as_ref(),
788            transition_digest,
789        )?;
790        let expected = compute_record_digest(&ModelInvocationRecordDigestWire {
791            intent_digest: intent.intent_digest,
792            revision,
793            state: &state,
794            previous: previous.as_ref(),
795            journal_head: &journal_head,
796            transition_digest,
797        })?;
798        if digest != expected {
799            return Err(ModelInvocationError::DigestMismatch);
800        }
801        Ok(Self {
802            intent,
803            revision,
804            state,
805            previous,
806            journal_head,
807            transition,
808            transition_digest,
809            digest,
810        })
811    }
812
813    /// Returns the immutable preparation intent.
814    #[must_use]
815    pub const fn intent(&self) -> &ModelInvocationIntent {
816        &self.intent
817    }
818
819    /// Returns this record's monotonic revision.
820    #[must_use]
821    pub const fn revision(&self) -> ModelInvocationRevision {
822        self.revision
823    }
824
825    /// Returns the integrity-bound lifecycle state.
826    #[must_use]
827    pub const fn state(&self) -> &ModelInvocationState {
828        &self.state
829    }
830
831    /// Returns the lifecycle discriminator.
832    #[must_use]
833    pub const fn status(&self) -> ModelInvocationStatus {
834        self.state.status()
835    }
836
837    /// Returns the physical attempt represented by this revision, if any.
838    #[must_use]
839    pub const fn attempt_id(&self) -> Option<AttemptId> {
840        self.state.attempt_id()
841    }
842
843    /// Returns the exact predecessor head, absent only for preparation.
844    #[must_use]
845    pub const fn previous(&self) -> Option<&ModelInvocationHead> {
846        self.previous.as_ref()
847    }
848
849    /// Returns the exact journal prefix anchoring this revision.
850    #[must_use]
851    pub const fn journal_head(&self) -> &JournalHead {
852        &self.journal_head
853    }
854
855    /// Returns the explicit transition, absent only for preparation.
856    #[must_use]
857    pub const fn transition(&self) -> Option<&ModelInvocationTransition> {
858        self.transition.as_ref()
859    }
860
861    /// Returns the transition fingerprint, absent only for preparation.
862    #[must_use]
863    pub const fn transition_digest(&self) -> Option<Digest> {
864        self.transition_digest
865    }
866
867    /// Returns the complete domain-separated record checksum.
868    #[must_use]
869    pub const fn digest(&self) -> Digest {
870        self.digest
871    }
872
873    /// Returns a compact exact optimistic-comparison token.
874    #[must_use]
875    pub fn head(&self) -> ModelInvocationHead {
876        ModelInvocationHead {
877            tenant_id: self.intent.tenant_id().clone(),
878            run_id: self.intent.run_id(),
879            invocation_id: self.intent.invocation_id,
880            revision: self.revision,
881            status: self.status(),
882            attempt_id: self.attempt_id(),
883            journal_head: self.journal_head.clone(),
884            digest: self.digest,
885        }
886    }
887}
888
889impl fmt::Debug for ModelInvocation {
890    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
891        formatter
892            .debug_struct("ModelInvocation")
893            .field("intent", &self.intent)
894            .field("revision", &self.revision)
895            .field("state", &self.state)
896            .field("previous", &self.previous)
897            .field("journal_head", &self.journal_head)
898            .field("transition", &self.transition)
899            .field("transition_digest", &self.transition_digest)
900            .field("digest", &self.digest)
901            .finish_non_exhaustive()
902    }
903}
904
905impl<'de> Deserialize<'de> for ModelInvocation {
906    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
907    where
908        D: Deserializer<'de>,
909    {
910        #[derive(Deserialize)]
911        #[serde(deny_unknown_fields)]
912        struct Wire {
913            intent: ModelInvocationIntent,
914            revision: ModelInvocationRevision,
915            state: ModelInvocationState,
916            previous: Option<ModelInvocationHead>,
917            journal_head: JournalHead,
918            transition: Option<ModelInvocationTransition>,
919            transition_digest: Option<Digest>,
920            digest: Digest,
921        }
922
923        let wire = Wire::deserialize(deserializer)?;
924        Self::restore(
925            wire.intent,
926            wire.revision,
927            wire.state,
928            wire.previous,
929            wire.journal_head,
930            wire.transition,
931            wire.transition_digest,
932            wire.digest,
933        )
934        .map_err(de::Error::custom)
935    }
936}
937
938/// Streaming validator for one complete ascending model invocation history.
939///
940/// Rejections are transactional: [`Self::verify_next`] never advances the last
941/// accepted record on failure.
942#[derive(Clone, Debug, Default)]
943pub struct ModelInvocationHistoryVerifier {
944    last: Option<ModelInvocation>,
945}
946
947impl ModelInvocationHistoryVerifier {
948    /// Constructs an empty verifier expecting revision zero.
949    #[must_use]
950    pub const fn new() -> Self {
951        Self { last: None }
952    }
953
954    /// Continues after one already trusted, fully restored record.
955    ///
956    /// A paged store must reload and compare the cursor's exact canonical record
957    /// before using it. The full predecessor failure is needed for retry checks.
958    #[must_use]
959    pub fn after(record: ModelInvocation) -> Self {
960        Self { last: Some(record) }
961    }
962
963    /// Returns the last verified head, if any.
964    #[must_use]
965    pub fn head(&self) -> Option<ModelInvocationHead> {
966        self.last.as_ref().map(ModelInvocation::head)
967    }
968
969    /// Returns whether at least one revision has been verified.
970    #[must_use]
971    pub const fn has_records(&self) -> bool {
972        self.last.is_some()
973    }
974
975    /// Verifies and then advances to the next ascending revision.
976    ///
977    /// # Errors
978    ///
979    /// Returns [`ModelInvocationHistoryError`] for a non-initial first record,
980    /// intent substitution, head mismatch, unsafe retry, or any other state
981    /// transition failure.
982    pub fn verify_next(
983        &mut self,
984        record: &ModelInvocation,
985    ) -> Result<(), ModelInvocationHistoryError> {
986        let Some(previous) = self.last.as_ref() else {
987            if record.revision != ModelInvocationRevision::INITIAL {
988                return Err(ModelInvocationHistoryError::FirstRecordNotInitial {
989                    actual: record.revision,
990                });
991            }
992            self.last = Some(record.clone());
993            return Ok(());
994        };
995
996        if record.intent != previous.intent {
997            return Err(ModelInvocationHistoryError::IntentMismatch);
998        }
999        if record.previous.as_ref() != Some(&previous.head()) {
1000            return Err(ModelInvocationHistoryError::PreviousHeadMismatch);
1001        }
1002        let transition = record
1003            .transition
1004            .as_ref()
1005            .ok_or(ModelInvocationHistoryError::TransitionMissing)?;
1006        let expected = previous
1007            .advance(transition.clone(), record.journal_head.clone())
1008            .map_err(|source| ModelInvocationHistoryError::Transition { source })?;
1009        if !canonical_equal(&expected, record)
1010            .map_err(|source| ModelInvocationHistoryError::Integrity { source })?
1011        {
1012            return Err(ModelInvocationHistoryError::RecordMismatch);
1013        }
1014
1015        self.last = Some(record.clone());
1016        Ok(())
1017    }
1018}
1019
1020/// Invalid ascending model invocation history.
1021#[derive(Clone, Debug, Eq, Error, PartialEq)]
1022#[non_exhaustive]
1023pub enum ModelInvocationHistoryError {
1024    /// The first supplied record was not preparation revision zero.
1025    #[error("first model invocation record is revision {actual}; expected 0")]
1026    FirstRecordNotInitial {
1027        /// Rejected first revision.
1028        actual: ModelInvocationRevision,
1029    },
1030    /// A successor substituted immutable preparation fields.
1031    #[error("model invocation history changed its immutable intent")]
1032    IntentMismatch,
1033    /// A successor did not name the exact previously verified head.
1034    #[error("model invocation history predecessor head mismatch")]
1035    PreviousHeadMismatch,
1036    /// A non-initial record omitted its transition.
1037    #[error("model invocation history successor is missing its transition")]
1038    TransitionMissing,
1039    /// Applying the transition to the full predecessor failed.
1040    #[error("model invocation history transition is invalid: {source}")]
1041    Transition {
1042        /// Exact state-machine failure.
1043        #[source]
1044        source: ModelInvocationError,
1045    },
1046    /// Expected and persisted successor bytes did not match exactly.
1047    #[error("model invocation history successor does not match the applied transition")]
1048    RecordMismatch,
1049    /// Exact record comparison could not be canonicalized.
1050    #[error("model invocation history integrity comparison failed: {source}")]
1051    Integrity {
1052        /// Exact canonicalization failure.
1053        #[source]
1054        source: ModelInvocationIntegrityError,
1055    },
1056}
1057
1058/// Invalid model invocation record, transition, provenance, or integrity layer.
1059#[derive(Clone, Debug, Eq, Error, PartialEq)]
1060#[non_exhaustive]
1061pub enum ModelInvocationError {
1062    /// Canonical typed integrity material could not be serialized.
1063    #[error("model invocation integrity calculation failed: {source}")]
1064    Integrity {
1065        /// Exact canonical integrity failure.
1066        #[source]
1067        source: ModelInvocationIntegrityError,
1068    },
1069    /// Journal head crossed the invocation tenant boundary.
1070    #[error("model invocation journal head crosses the tenant boundary")]
1071    JournalTenantMismatch,
1072    /// Journal head named another run.
1073    #[error("model invocation journal head does not belong to the run")]
1074    JournalRunMismatch,
1075    /// A revision did not strictly advance its required journal predecessor.
1076    #[error("model invocation journal sequence {actual} does not advance {previous}")]
1077    JournalDidNotAdvance {
1078        /// Required prior sequence.
1079        previous: JournalSequence,
1080        /// Rejected current sequence.
1081        actual: JournalSequence,
1082    },
1083    /// A revision's durable clock preceded its required predecessor.
1084    #[error("model invocation journal clock regressed from {previous} to {actual}")]
1085    ClockRegression {
1086        /// Required prior durable timestamp.
1087        previous: Timestamp,
1088        /// Rejected current timestamp.
1089        actual: Timestamp,
1090    },
1091    /// No storage-compatible successor revision exists.
1092    #[error("model invocation revision exceeds the PostgreSQL BIGINT maximum")]
1093    RevisionOverflow,
1094    /// Revision zero did not use the exact preparation shape.
1095    #[error("initial model invocation revision must be prepared with no predecessor or transition")]
1096    InvalidInitialShape,
1097    /// A successor omitted or unexpectedly added predecessor/transition fields.
1098    #[error(
1099        "model invocation successor must contain predecessor, transition, and transition digest"
1100    )]
1101    InvalidSuccessorShape,
1102    /// Compact predecessor crossed the immutable tenant boundary.
1103    #[error("model invocation predecessor crosses the tenant boundary")]
1104    PreviousTenantMismatch,
1105    /// Compact predecessor named another run.
1106    #[error("model invocation predecessor names another run")]
1107    PreviousRunMismatch,
1108    /// Compact predecessor named another logical invocation.
1109    #[error("model invocation predecessor names another invocation")]
1110    PreviousInvocationMismatch,
1111    /// Current revision was not the exact successor of its compact predecessor.
1112    #[error("model invocation revision {actual} does not follow predecessor {previous}")]
1113    PreviousRevisionMismatch {
1114        /// Predecessor revision.
1115        previous: ModelInvocationRevision,
1116        /// Rejected current revision.
1117        actual: ModelInvocationRevision,
1118    },
1119    /// Persisted transition checksum did not match its transition payload.
1120    #[error("model invocation transition digest does not match its payload")]
1121    TransitionDigestMismatch,
1122    /// Transition is not legal from the predecessor lifecycle state.
1123    #[error("model invocation transition {transition:?} is invalid from {status:?}")]
1124    InvalidTransition {
1125        /// Predecessor status.
1126        status: ModelInvocationStatus,
1127        /// Rejected transition kind.
1128        transition: ModelInvocationTransitionKind,
1129    },
1130    /// Transition payload and resulting state differed.
1131    #[error("model invocation transition payload does not match its resulting state")]
1132    TransitionStateMismatch,
1133    /// A retry reused the immediately preceding physical attempt identity.
1134    #[error("model invocation retry must use a new physical attempt identifier")]
1135    ReusedAttemptId,
1136    /// Failed outcome did not explicitly authorize a safe retry.
1137    #[error("model invocation failure does not authorize retry")]
1138    RetryNotAuthorized,
1139    /// Retry time could not be represented in the canonical timestamp range.
1140    #[error("model invocation retry delay exceeds the supported timestamp range")]
1141    RetryDelayOutOfRange,
1142    /// Retry occurred before the failure's explicit minimum delay elapsed.
1143    #[error("model invocation retry at {actual} precedes not-before time {not_before}")]
1144    RetryDelayNotElapsed {
1145        /// Earliest permitted durable retry timestamp.
1146        not_before: Timestamp,
1147        /// Rejected retry timestamp.
1148        actual: Timestamp,
1149    },
1150    /// Successful response named another physical attempt.
1151    #[error("model response names another physical attempt")]
1152    ResponseAttemptMismatch,
1153    /// Successful response did not match the descriptor/request snapshot.
1154    #[error("model response does not match the invocation: {source}")]
1155    ResponseBinding {
1156        /// Exact response validation failure.
1157        #[source]
1158        source: ModelResponseError,
1159    },
1160    /// Failure evidence did not match attempt, model, mode, or request limits.
1161    #[error("model failure does not match the invocation: {source}")]
1162    ErrorBinding {
1163        /// Exact failure validation error.
1164        #[source]
1165        source: ModelErrorValidationError,
1166    },
1167    /// A pre-dispatch preparation failure claimed provider usage.
1168    #[error("model preparation failure cannot contain provider usage")]
1169    PreparationFailureHasUsage,
1170    /// Persisted complete record checksum did not match its fields.
1171    #[error("model invocation record digest does not match its fields")]
1172    DigestMismatch,
1173}
1174
1175impl From<ModelInvocationIntegrityError> for ModelInvocationError {
1176    fn from(source: ModelInvocationIntegrityError) -> Self {
1177        Self::Integrity { source }
1178    }
1179}
1180
1181/// Failure to canonicalize a closed model invocation checksum preimage.
1182#[derive(Clone, Debug, Eq, Error, PartialEq)]
1183#[non_exhaustive]
1184pub enum ModelInvocationIntegrityError {
1185    /// Typed values could not be represented as canonical JSON.
1186    #[error("model invocation checksum preimage canonical serialization failed")]
1187    CanonicalSerialization,
1188}
1189
1190#[derive(Serialize)]
1191struct ModelInvocationIntentDigestWire<'a> {
1192    activation: &'a NodeActivation,
1193    invocation_id: InvocationId,
1194    descriptor: &'a ModelDescriptor,
1195    request: &'a ModelRequest,
1196}
1197
1198#[derive(Serialize)]
1199struct ModelInvocationRecordDigestWire<'a> {
1200    intent_digest: Digest,
1201    revision: ModelInvocationRevision,
1202    state: &'a ModelInvocationState,
1203    #[serde(skip_serializing_if = "Option::is_none")]
1204    previous: Option<&'a ModelInvocationHead>,
1205    journal_head: &'a JournalHead,
1206    #[serde(skip_serializing_if = "Option::is_none")]
1207    transition_digest: Option<Digest>,
1208}
1209
1210fn compute_intent_digest(
1211    value: &ModelInvocationIntentDigestWire<'_>,
1212) -> Result<Digest, ModelInvocationIntegrityError> {
1213    domain_separated_digest(INTENT_DIGEST_DOMAIN, value)
1214}
1215
1216fn compute_transition_digest(
1217    value: &ModelInvocationTransition,
1218) -> Result<Digest, ModelInvocationIntegrityError> {
1219    domain_separated_digest(TRANSITION_DIGEST_DOMAIN, value)
1220}
1221
1222fn compute_record_digest(
1223    value: &ModelInvocationRecordDigestWire<'_>,
1224) -> Result<Digest, ModelInvocationIntegrityError> {
1225    domain_separated_digest(RECORD_DIGEST_DOMAIN, value)
1226}
1227
1228fn domain_separated_digest<T: Serialize>(
1229    domain: &[u8],
1230    value: &T,
1231) -> Result<Digest, ModelInvocationIntegrityError> {
1232    let canonical = serde_json_canonicalizer::to_vec(value)
1233        .map_err(|_| ModelInvocationIntegrityError::CanonicalSerialization)?;
1234    let mut preimage = Vec::with_capacity(domain.len() + canonical.len());
1235    preimage.extend_from_slice(domain);
1236    preimage.extend_from_slice(&canonical);
1237    Ok(Digest::sha256(preimage))
1238}
1239
1240fn canonical_equal<T: Serialize>(
1241    left: &T,
1242    right: &T,
1243) -> Result<bool, ModelInvocationIntegrityError> {
1244    let left = serde_json_canonicalizer::to_vec(left)
1245        .map_err(|_| ModelInvocationIntegrityError::CanonicalSerialization)?;
1246    let right = serde_json_canonicalizer::to_vec(right)
1247        .map_err(|_| ModelInvocationIntegrityError::CanonicalSerialization)?;
1248    Ok(left == right)
1249}
1250
1251fn validate_intent_shape(
1252    descriptor: &ModelDescriptor,
1253    request: &ModelRequest,
1254) -> Result<(), ModelInvocationIntentError> {
1255    if descriptor.metadata().lifecycle().state() == CapabilityLifecycleState::Retired {
1256        return Err(ModelInvocationIntentError::RetiredModel);
1257    }
1258    descriptor
1259        .capabilities()
1260        .satisfies(request.requirements())
1261        .map_err(|mismatch| ModelInvocationIntentError::CapabilityMismatch {
1262            mismatch: Box::new(mismatch),
1263        })
1264}
1265
1266#[derive(Clone, Copy)]
1267enum InvocationScopeError {
1268    Tenant,
1269    Run,
1270}
1271
1272fn validate_journal_scope(
1273    tenant_id: &TenantId,
1274    run_id: RunId,
1275    head: &JournalHead,
1276) -> Result<(), InvocationScopeError> {
1277    if head.tenant_id() != tenant_id {
1278        return Err(InvocationScopeError::Tenant);
1279    }
1280    if head.run_id() != run_id {
1281        return Err(InvocationScopeError::Run);
1282    }
1283    Ok(())
1284}
1285
1286fn validate_status_attempt(
1287    status: ModelInvocationStatus,
1288    attempt_id: Option<AttemptId>,
1289) -> Result<(), ModelInvocationHeadError> {
1290    match (status, attempt_id) {
1291        (ModelInvocationStatus::Prepared, None)
1292        | (
1293            ModelInvocationStatus::Executing
1294            | ModelInvocationStatus::Committed
1295            | ModelInvocationStatus::Failed,
1296            Some(_),
1297        ) => Ok(()),
1298        (ModelInvocationStatus::Prepared, Some(_)) => {
1299            Err(ModelInvocationHeadError::PreparedHasAttempt)
1300        }
1301        (
1302            ModelInvocationStatus::Executing
1303            | ModelInvocationStatus::Committed
1304            | ModelInvocationStatus::Failed,
1305            None,
1306        ) => Err(ModelInvocationHeadError::AttemptMissing),
1307    }
1308}
1309
1310fn validate_revision_status(
1311    revision: ModelInvocationRevision,
1312    status: ModelInvocationStatus,
1313) -> Result<(), ModelInvocationHeadError> {
1314    match (revision == ModelInvocationRevision::INITIAL, status) {
1315        (true, ModelInvocationStatus::Prepared)
1316        | (
1317            false,
1318            ModelInvocationStatus::Executing
1319            | ModelInvocationStatus::Committed
1320            | ModelInvocationStatus::Failed,
1321        ) => Ok(()),
1322        (true, _) => Err(ModelInvocationHeadError::InitialStatusMismatch),
1323        (false, ModelInvocationStatus::Prepared) => {
1324            Err(ModelInvocationHeadError::PreparedRevisionMismatch)
1325        }
1326    }
1327}
1328
1329fn map_scope_error(error: InvocationScopeError) -> ModelInvocationError {
1330    match error {
1331        InvocationScopeError::Tenant => ModelInvocationError::JournalTenantMismatch,
1332        InvocationScopeError::Run => ModelInvocationError::JournalRunMismatch,
1333    }
1334}
1335
1336fn validate_journal_advances(
1337    previous: &JournalHead,
1338    actual: &JournalHead,
1339) -> Result<(), ModelInvocationError> {
1340    if actual.sequence() <= previous.sequence() {
1341        return Err(ModelInvocationError::JournalDidNotAdvance {
1342            previous: previous.sequence(),
1343            actual: actual.sequence(),
1344        });
1345    }
1346    if actual.recorded_at() < previous.recorded_at() {
1347        return Err(ModelInvocationError::ClockRegression {
1348            previous: previous.recorded_at(),
1349            actual: actual.recorded_at(),
1350        });
1351    }
1352    Ok(())
1353}
1354
1355fn validate_preparation_journal(
1356    intent: &ModelInvocationIntent,
1357    journal_head: &JournalHead,
1358) -> Result<(), ModelInvocationError> {
1359    validate_journal_scope(intent.tenant_id(), intent.run_id(), journal_head)
1360        .map_err(map_scope_error)?;
1361    validate_journal_advances(
1362        intent.activation.base_checkpoint().journal_head(),
1363        journal_head,
1364    )
1365}
1366
1367fn validate_successor_journal(
1368    invocation: &ModelInvocation,
1369    journal_head: &JournalHead,
1370) -> Result<(), ModelInvocationError> {
1371    validate_journal_scope(
1372        invocation.intent.tenant_id(),
1373        invocation.intent.run_id(),
1374        journal_head,
1375    )
1376    .map_err(map_scope_error)?;
1377    validate_journal_advances(&invocation.journal_head, journal_head)
1378}
1379
1380#[allow(clippy::too_many_arguments)]
1381fn validate_record_shape(
1382    intent: &ModelInvocationIntent,
1383    revision: ModelInvocationRevision,
1384    state: &ModelInvocationState,
1385    previous: Option<&ModelInvocationHead>,
1386    journal_head: &JournalHead,
1387    transition: Option<&ModelInvocationTransition>,
1388    transition_digest: Option<Digest>,
1389) -> Result<(), ModelInvocationError> {
1390    validate_journal_scope(intent.tenant_id(), intent.run_id(), journal_head)
1391        .map_err(map_scope_error)?;
1392    validate_state_binding(intent, state)?;
1393
1394    if revision == ModelInvocationRevision::INITIAL {
1395        if !matches!(state, ModelInvocationState::Prepared)
1396            || previous.is_some()
1397            || transition.is_some()
1398            || transition_digest.is_some()
1399        {
1400            return Err(ModelInvocationError::InvalidInitialShape);
1401        }
1402        return validate_preparation_journal(intent, journal_head);
1403    }
1404
1405    let (Some(previous), Some(transition), Some(transition_digest)) =
1406        (previous, transition, transition_digest)
1407    else {
1408        return Err(ModelInvocationError::InvalidSuccessorShape);
1409    };
1410    if previous.tenant_id() != intent.tenant_id() {
1411        return Err(ModelInvocationError::PreviousTenantMismatch);
1412    }
1413    if previous.run_id() != intent.run_id() {
1414        return Err(ModelInvocationError::PreviousRunMismatch);
1415    }
1416    if previous.invocation_id() != intent.invocation_id() {
1417        return Err(ModelInvocationError::PreviousInvocationMismatch);
1418    }
1419    if previous.revision().checked_next() != Some(revision) {
1420        return Err(ModelInvocationError::PreviousRevisionMismatch {
1421            previous: previous.revision(),
1422            actual: revision,
1423        });
1424    }
1425    validate_journal_advances(previous.journal_head(), journal_head)?;
1426
1427    if compute_transition_digest(transition)? != transition_digest {
1428        return Err(ModelInvocationError::TransitionDigestMismatch);
1429    }
1430    validate_transition_shape(intent, previous, transition, state)
1431}
1432
1433fn validate_state_binding(
1434    intent: &ModelInvocationIntent,
1435    state: &ModelInvocationState,
1436) -> Result<(), ModelInvocationError> {
1437    match state {
1438        ModelInvocationState::Prepared | ModelInvocationState::Executing { .. } => Ok(()),
1439        ModelInvocationState::Committed { response } => {
1440            validate_response_binding(intent, response.provenance().attempt_id(), response)
1441        }
1442        ModelInvocationState::Failed { error } => {
1443            validate_error_binding(intent, error.provenance().attempt_id(), error)
1444        }
1445    }
1446}
1447
1448fn validate_response_binding(
1449    intent: &ModelInvocationIntent,
1450    expected_attempt: AttemptId,
1451    response: &ModelResponse,
1452) -> Result<(), ModelInvocationError> {
1453    if response.provenance().attempt_id() != expected_attempt {
1454        return Err(ModelInvocationError::ResponseAttemptMismatch);
1455    }
1456    response
1457        .validate_for(&intent.descriptor, &intent.request)
1458        .map_err(|source| ModelInvocationError::ResponseBinding { source })
1459}
1460
1461fn validate_error_binding(
1462    intent: &ModelInvocationIntent,
1463    expected_attempt: AttemptId,
1464    error: &ModelError,
1465) -> Result<(), ModelInvocationError> {
1466    error
1467        .validate_for_attempt(expected_attempt, &intent.descriptor, &intent.request)
1468        .map_err(|source| ModelInvocationError::ErrorBinding { source })?;
1469    if error.phase() == ModelErrorPhase::Preparation && error.usage().is_some() {
1470        return Err(ModelInvocationError::PreparationFailureHasUsage);
1471    }
1472    Ok(())
1473}
1474
1475fn validate_transition_shape(
1476    intent: &ModelInvocationIntent,
1477    previous: &ModelInvocationHead,
1478    transition: &ModelInvocationTransition,
1479    state: &ModelInvocationState,
1480) -> Result<(), ModelInvocationError> {
1481    let valid = match (previous.status(), transition, state) {
1482        (
1483            ModelInvocationStatus::Prepared | ModelInvocationStatus::Failed,
1484            ModelInvocationTransition::StartAttempt { attempt_id },
1485            ModelInvocationState::Executing {
1486                attempt_id: state_attempt,
1487            },
1488        ) => {
1489            if previous.attempt_id() == Some(*attempt_id) {
1490                return Err(ModelInvocationError::ReusedAttemptId);
1491            }
1492            attempt_id == state_attempt
1493        }
1494        (
1495            ModelInvocationStatus::Executing,
1496            ModelInvocationTransition::RecordResponse { response },
1497            ModelInvocationState::Committed {
1498                response: state_response,
1499            },
1500        ) => canonical_equal(response, state_response)?,
1501        (
1502            ModelInvocationStatus::Executing,
1503            ModelInvocationTransition::RecordError { error },
1504            ModelInvocationState::Failed { error: state_error },
1505        ) => canonical_equal(error, state_error)?,
1506        _ => {
1507            return Err(ModelInvocationError::InvalidTransition {
1508                status: previous.status(),
1509                transition: transition.kind(),
1510            });
1511        }
1512    };
1513    if !valid {
1514        return Err(ModelInvocationError::TransitionStateMismatch);
1515    }
1516
1517    let expected_attempt = previous.attempt_id();
1518    match transition {
1519        ModelInvocationTransition::StartAttempt { .. } => {}
1520        ModelInvocationTransition::RecordResponse { response } => {
1521            validate_response_binding(
1522                intent,
1523                expected_attempt.ok_or(ModelInvocationError::TransitionStateMismatch)?,
1524                response,
1525            )?;
1526        }
1527        ModelInvocationTransition::RecordError { error } => {
1528            validate_error_binding(
1529                intent,
1530                expected_attempt.ok_or(ModelInvocationError::TransitionStateMismatch)?,
1531                error,
1532            )?;
1533        }
1534    }
1535    Ok(())
1536}
1537
1538fn apply_transition(
1539    invocation: &ModelInvocation,
1540    transition: &ModelInvocationTransition,
1541    recorded_at: Timestamp,
1542) -> Result<ModelInvocationState, ModelInvocationError> {
1543    match (&invocation.state, transition) {
1544        (
1545            ModelInvocationState::Prepared,
1546            ModelInvocationTransition::StartAttempt { attempt_id },
1547        ) => Ok(ModelInvocationState::Executing {
1548            attempt_id: *attempt_id,
1549        }),
1550        (
1551            ModelInvocationState::Failed { error },
1552            ModelInvocationTransition::StartAttempt { attempt_id },
1553        ) => {
1554            let previous_attempt = error.provenance().attempt_id();
1555            if previous_attempt == *attempt_id {
1556                return Err(ModelInvocationError::ReusedAttemptId);
1557            }
1558            validate_retry(invocation, error, recorded_at)?;
1559            Ok(ModelInvocationState::Executing {
1560                attempt_id: *attempt_id,
1561            })
1562        }
1563        (
1564            ModelInvocationState::Executing { attempt_id },
1565            ModelInvocationTransition::RecordResponse { response },
1566        ) => {
1567            validate_response_binding(&invocation.intent, *attempt_id, response)?;
1568            Ok(ModelInvocationState::Committed {
1569                response: response.clone(),
1570            })
1571        }
1572        (
1573            ModelInvocationState::Executing { attempt_id },
1574            ModelInvocationTransition::RecordError { error },
1575        ) => {
1576            validate_error_binding(&invocation.intent, *attempt_id, error)?;
1577            Ok(ModelInvocationState::Failed {
1578                error: error.clone(),
1579            })
1580        }
1581        _ => Err(ModelInvocationError::InvalidTransition {
1582            status: invocation.status(),
1583            transition: transition.kind(),
1584        }),
1585    }
1586}
1587
1588fn validate_retry(
1589    invocation: &ModelInvocation,
1590    error: &ModelError,
1591    recorded_at: Timestamp,
1592) -> Result<(), ModelInvocationError> {
1593    let Some(delay) = error.failure().retry_advice().safe_after_delay() else {
1594        return Err(ModelInvocationError::RetryNotAuthorized);
1595    };
1596    let not_before_micros = i128::from(invocation.journal_head.recorded_at().unix_micros())
1597        + i128::from(delay.as_i64()) * 1_000;
1598    if not_before_micros > i128::from(Timestamp::MAX.unix_micros()) {
1599        return Err(ModelInvocationError::RetryDelayOutOfRange);
1600    }
1601    let not_before = Timestamp::from_unix_micros(
1602        i64::try_from(not_before_micros).map_err(|_| ModelInvocationError::RetryDelayOutOfRange)?,
1603    )
1604    .map_err(|_| ModelInvocationError::RetryDelayOutOfRange)?;
1605    if recorded_at < not_before {
1606        return Err(ModelInvocationError::RetryDelayNotElapsed {
1607            not_before,
1608            actual: recorded_at,
1609        });
1610    }
1611    Ok(())
1612}
1613
1614#[cfg(test)]
1615mod tests {
1616    use schemars::schema_for;
1617    use serde_json::{Value, from_value, json, to_value};
1618
1619    use super::*;
1620    use crate::{
1621        Checkpoint, DurationMillis, EventId, Failure, FailureCategory, FailureCode, FailureId,
1622        FailureMessage, FailureOrigin, GraphNamespace, ModelErrorProvenance, ModelUsage, NodeId,
1623        RetryAdvice,
1624    };
1625
1626    fn fixture(path: &[&str], source: &str) -> Value {
1627        let mut value: Value = serde_json::from_str(source).unwrap();
1628        for component in path {
1629            value = match component.parse::<usize>() {
1630                Ok(index) => value[index].clone(),
1631                Err(_) => value[*component].clone(),
1632            };
1633        }
1634        value
1635    }
1636
1637    fn checkpoint() -> Checkpoint {
1638        from_value(fixture(
1639            &["checkpoints", "0"],
1640            include_str!("../tests/fixtures/core-checkpoint-v1.json"),
1641        ))
1642        .unwrap()
1643    }
1644
1645    fn descriptor() -> ModelDescriptor {
1646        from_value(fixture(
1647            &["descriptors", "valid", "0", "model"],
1648            include_str!("../tests/fixtures/core-agent-v1.json"),
1649        ))
1650        .unwrap()
1651    }
1652
1653    fn request() -> ModelRequest {
1654        from_value(fixture(
1655            &["requests", "valid", "0"],
1656            include_str!("../tests/fixtures/core-model-request-v1.json"),
1657        ))
1658        .unwrap()
1659    }
1660
1661    fn invocation_id() -> InvocationId {
1662        "01912345-6789-7abc-8def-0123456789d0".parse().unwrap()
1663    }
1664
1665    fn attempt(suffix: &str) -> AttemptId {
1666        format!("01912345-6789-7abc-8def-0123456789{suffix}")
1667            .parse()
1668            .unwrap()
1669    }
1670
1671    fn intent() -> ModelInvocationIntent {
1672        let checkpoint = checkpoint();
1673        ModelInvocationIntent::new(
1674            NodeActivation::new(
1675                checkpoint.head(),
1676                GraphNamespace::root(),
1677                NodeId::new("reason").unwrap(),
1678                Digest::sha256(b"model-node-input"),
1679            ),
1680            invocation_id(),
1681            descriptor(),
1682            request(),
1683        )
1684        .unwrap()
1685    }
1686
1687    fn journal(intent: &ModelInvocationIntent, sequence: u64) -> JournalHead {
1688        let base = intent
1689            .activation()
1690            .base_checkpoint()
1691            .journal_head()
1692            .recorded_at();
1693        let offset = i64::try_from(sequence - 1).unwrap() * 1_000_000;
1694        journal_at(
1695            intent,
1696            sequence,
1697            Timestamp::from_unix_micros(base.unix_micros() + offset).unwrap(),
1698        )
1699    }
1700
1701    fn journal_at(
1702        intent: &ModelInvocationIntent,
1703        sequence: u64,
1704        recorded_at: Timestamp,
1705    ) -> JournalHead {
1706        let event_id: EventId =
1707            format!("01912345-6789-7abc-8def-0123456789{:02x}", 0xd0 + sequence)
1708                .parse()
1709                .unwrap();
1710        JournalHead::new(
1711            intent.tenant_id().clone(),
1712            intent.run_id(),
1713            JournalSequence::new(sequence).unwrap(),
1714            event_id,
1715            recorded_at,
1716            Digest::sha256(sequence.to_be_bytes()),
1717        )
1718    }
1719
1720    fn response(attempt_id: AttemptId) -> ModelResponse {
1721        let descriptor = descriptor();
1722        let request = request();
1723        let mut value = fixture(
1724            &["responses", "valid", "0"],
1725            include_str!("../tests/fixtures/core-model-response-v1.json"),
1726        );
1727        value["provenance"]["attempt_id"] = json!(attempt_id);
1728        value["provenance"]["model"] = to_value(descriptor.metadata().identity()).unwrap();
1729        let response = from_value::<ModelResponse>(value).unwrap();
1730        response.validate_for(&descriptor, &request).unwrap();
1731        response
1732    }
1733
1734    fn model_error(
1735        attempt_id: AttemptId,
1736        phase: ModelErrorPhase,
1737        retry_advice: RetryAdvice,
1738        usage: Option<ModelUsage>,
1739    ) -> ModelError {
1740        let descriptor = descriptor();
1741        let failure = Failure::new(
1742            "01912345-6789-7abc-8def-0123456789b8"
1743                .parse::<FailureId>()
1744                .unwrap(),
1745            FailureCategory::DependencyUnavailable,
1746            FailureCode::new("model.dependency_unavailable").unwrap(),
1747            FailureOrigin::new("model.provider").unwrap(),
1748            FailureMessage::new("The model provider is temporarily unavailable.").unwrap(),
1749            retry_advice,
1750        )
1751        .unwrap();
1752        ModelError::new(
1753            failure,
1754            phase,
1755            ModelErrorProvenance::new(
1756                attempt_id,
1757                descriptor.metadata().identity().clone(),
1758                None,
1759                None,
1760                None,
1761            ),
1762            usage,
1763        )
1764    }
1765
1766    fn prepared() -> ModelInvocation {
1767        let intent = intent();
1768        let head = journal(&intent, 2);
1769        ModelInvocation::prepare(intent, head).unwrap()
1770    }
1771
1772    #[test]
1773    fn revision_and_intent_wires_are_canonical_negotiated_and_bound() {
1774        for value in [0, 1, i64::MAX as u64] {
1775            let revision = ModelInvocationRevision::new(value).unwrap();
1776            assert_eq!(to_value(revision).unwrap(), json!(value.to_string()));
1777            assert_eq!(
1778                from_value::<ModelInvocationRevision>(json!(value.to_string())).unwrap(),
1779                revision
1780            );
1781        }
1782        for invalid in [
1783            json!(""),
1784            json!("01"),
1785            json!("9223372036854775808"),
1786            json!(1),
1787        ] {
1788            assert!(from_value::<ModelInvocationRevision>(invalid).is_err());
1789        }
1790
1791        let intent = intent();
1792        let wire = to_value(&intent).unwrap();
1793        assert_eq!(
1794            from_value::<ModelInvocationIntent>(wire.clone()).unwrap(),
1795            intent
1796        );
1797
1798        let mut tampered = wire;
1799        tampered["request"]["instructions"][0]["content"]["content"]["text"] =
1800            json!("changed prompt");
1801        assert!(from_value::<ModelInvocationIntent>(tampered).is_err());
1802
1803        let mut excessive = to_value(request()).unwrap();
1804        excessive["limits"]["max_output_tokens"] = json!("20000");
1805        excessive["requirements"]["min_output_tokens"] = json!("20000");
1806        excessive["requirements"]["min_context_tokens"] = json!("28192");
1807        let excessive = from_value::<ModelRequest>(excessive).unwrap();
1808        assert!(matches!(
1809            ModelInvocationIntent::new(
1810                intent.activation().clone(),
1811                InvocationId::generate(),
1812                descriptor(),
1813                excessive,
1814            ),
1815            Err(ModelInvocationIntentError::CapabilityMismatch { .. })
1816        ));
1817
1818        let mut retired = to_value(descriptor()).unwrap();
1819        retired["metadata"]["lifecycle"] = json!({
1820            "status": "retired",
1821            "retired_at": "2027-02-28T00:00:00.000001Z",
1822            "notice": "This binding is retained only for durable history."
1823        });
1824        let retired = from_value::<ModelDescriptor>(retired).unwrap();
1825        assert_eq!(
1826            ModelInvocationIntent::new(
1827                intent.activation().clone(),
1828                InvocationId::generate(),
1829                retired,
1830                request(),
1831            ),
1832            Err(ModelInvocationIntentError::RetiredModel)
1833        );
1834    }
1835
1836    #[test]
1837    fn prepared_attempt_and_response_form_one_verified_terminal_history() {
1838        let prepared = prepared();
1839        let attempt_id = attempt("ab");
1840        let executing = prepared
1841            .advance(
1842                ModelInvocationTransition::StartAttempt { attempt_id },
1843                journal(prepared.intent(), 3),
1844            )
1845            .unwrap();
1846        let committed = executing
1847            .advance(
1848                ModelInvocationTransition::RecordResponse {
1849                    response: response(attempt_id),
1850                },
1851                journal(executing.intent(), 4),
1852            )
1853            .unwrap();
1854
1855        assert_eq!(prepared.status(), ModelInvocationStatus::Prepared);
1856        assert_eq!(executing.status(), ModelInvocationStatus::Executing);
1857        assert_eq!(committed.status(), ModelInvocationStatus::Committed);
1858        assert_eq!(committed.attempt_id(), Some(attempt_id));
1859        assert!(matches!(
1860            committed.advance(
1861                ModelInvocationTransition::StartAttempt {
1862                    attempt_id: attempt("ac"),
1863                },
1864                journal(committed.intent(), 5),
1865            ),
1866            Err(ModelInvocationError::InvalidTransition { .. })
1867        ));
1868
1869        let restored = from_value::<ModelInvocation>(to_value(&committed).unwrap()).unwrap();
1870        assert_eq!(to_value(restored).unwrap(), to_value(&committed).unwrap());
1871        let mut verifier = ModelInvocationHistoryVerifier::new();
1872        for record in [&prepared, &executing, &committed] {
1873            verifier.verify_next(record).unwrap();
1874        }
1875        assert_eq!(verifier.head(), Some(committed.head()));
1876    }
1877
1878    #[test]
1879    fn failed_attempt_retry_requires_new_identity_explicit_advice_and_durable_delay() {
1880        let prepared = prepared();
1881        let first_attempt = attempt("ab");
1882        let executing = prepared
1883            .advance(
1884                ModelInvocationTransition::StartAttempt {
1885                    attempt_id: first_attempt,
1886                },
1887                journal(prepared.intent(), 3),
1888            )
1889            .unwrap();
1890        let failed = executing
1891            .advance(
1892                ModelInvocationTransition::RecordError {
1893                    error: model_error(
1894                        first_attempt,
1895                        ModelErrorPhase::Dispatch,
1896                        RetryAdvice::SafeAfter {
1897                            delay: DurationMillis::new(1_000).unwrap(),
1898                        },
1899                        None,
1900                    ),
1901                },
1902                journal(executing.intent(), 4),
1903            )
1904            .unwrap();
1905
1906        assert!(matches!(
1907            failed.advance(
1908                ModelInvocationTransition::StartAttempt {
1909                    attempt_id: first_attempt,
1910                },
1911                journal(failed.intent(), 5),
1912            ),
1913            Err(ModelInvocationError::ReusedAttemptId)
1914        ));
1915
1916        let too_early = journal_at(
1917            failed.intent(),
1918            5,
1919            Timestamp::from_unix_micros(
1920                failed.journal_head().recorded_at().unix_micros() + 999_999,
1921            )
1922            .unwrap(),
1923        );
1924        assert!(matches!(
1925            failed.advance(
1926                ModelInvocationTransition::StartAttempt {
1927                    attempt_id: attempt("ac"),
1928                },
1929                too_early,
1930            ),
1931            Err(ModelInvocationError::RetryDelayNotElapsed { .. })
1932        ));
1933        let retried = failed
1934            .advance(
1935                ModelInvocationTransition::StartAttempt {
1936                    attempt_id: attempt("ac"),
1937                },
1938                journal(failed.intent(), 5),
1939            )
1940            .unwrap();
1941        assert_eq!(retried.status(), ModelInvocationStatus::Executing);
1942
1943        let never_executing = prepared
1944            .advance(
1945                ModelInvocationTransition::StartAttempt {
1946                    attempt_id: attempt("ad"),
1947                },
1948                journal(prepared.intent(), 3),
1949            )
1950            .unwrap();
1951        let never_failed = never_executing
1952            .advance(
1953                ModelInvocationTransition::RecordError {
1954                    error: model_error(
1955                        attempt("ad"),
1956                        ModelErrorPhase::Preparation,
1957                        RetryAdvice::Never,
1958                        None,
1959                    ),
1960                },
1961                journal(never_executing.intent(), 4),
1962            )
1963            .unwrap();
1964        assert!(matches!(
1965            never_failed.advance(
1966                ModelInvocationTransition::StartAttempt {
1967                    attempt_id: attempt("ae"),
1968                },
1969                journal(never_failed.intent(), 5),
1970            ),
1971            Err(ModelInvocationError::RetryNotAuthorized)
1972        ));
1973    }
1974
1975    #[test]
1976    fn attempt_result_error_and_integrity_substitution_fail_closed() {
1977        let prepared = prepared();
1978        let attempt_id = attempt("ab");
1979        let executing = prepared
1980            .advance(
1981                ModelInvocationTransition::StartAttempt { attempt_id },
1982                journal(prepared.intent(), 3),
1983            )
1984            .unwrap();
1985
1986        assert!(matches!(
1987            executing.advance(
1988                ModelInvocationTransition::RecordResponse {
1989                    response: response(attempt("ac")),
1990                },
1991                journal(executing.intent(), 4),
1992            ),
1993            Err(ModelInvocationError::ResponseAttemptMismatch)
1994        ));
1995        assert!(matches!(
1996            executing.advance(
1997                ModelInvocationTransition::RecordError {
1998                    error: model_error(
1999                        attempt("ac"),
2000                        ModelErrorPhase::Dispatch,
2001                        RetryAdvice::Never,
2002                        None,
2003                    ),
2004                },
2005                journal(executing.intent(), 4),
2006            ),
2007            Err(ModelInvocationError::ErrorBinding {
2008                source: ModelErrorValidationError::AttemptMismatch { .. }
2009            })
2010        ));
2011        assert!(matches!(
2012            executing.advance(
2013                ModelInvocationTransition::RecordError {
2014                    error: model_error(
2015                        attempt_id,
2016                        ModelErrorPhase::Preparation,
2017                        RetryAdvice::Never,
2018                        Some(response(attempt_id).usage().clone()),
2019                    ),
2020                },
2021                journal(executing.intent(), 4),
2022            ),
2023            Err(ModelInvocationError::PreparationFailureHasUsage)
2024        ));
2025
2026        let mut wire = to_value(&executing).unwrap();
2027        wire["state"]["attempt_id"] = json!(attempt("ac"));
2028        assert!(from_value::<ModelInvocation>(wire).is_err());
2029        let mut wire = to_value(&executing).unwrap();
2030        wire["transition"]["attempt_id"] = json!(attempt("ac"));
2031        assert!(from_value::<ModelInvocation>(wire).is_err());
2032
2033        let mut verifier = ModelInvocationHistoryVerifier::new();
2034        assert!(matches!(
2035            verifier.verify_next(&executing),
2036            Err(ModelInvocationHistoryError::FirstRecordNotInitial { .. })
2037        ));
2038        assert!(!verifier.has_records());
2039    }
2040
2041    #[test]
2042    fn public_model_invocation_schemas_are_closed() {
2043        for schema in [
2044            to_value(schema_for!(ModelInvocationIntent)).unwrap(),
2045            to_value(schema_for!(ModelInvocationHead)).unwrap(),
2046            to_value(schema_for!(ModelInvocation)).unwrap(),
2047        ] {
2048            assert_eq!(schema["additionalProperties"], Value::Bool(false));
2049        }
2050    }
2051}