Skip to main content

stateknot_core/
child_run_admission.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Closed child-admission preparation. No durable spawn or authorization grant.
5
6use std::fmt;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, de};
10use thiserror::Error;
11
12use crate::{
13    AgentAdmission, AgentAdmissionIntent, AgentAdmissionIntentError, BudgetNarrowingError,
14    Checkpoint, CheckpointState, ChildRunKey, CompiledGraph, Digest, GraphSchemaValidationError,
15    GraphSchemaValidator, NodeActivation, Timestamp,
16};
17
18const SPAWN_DOMAIN: &[u8] = b"stateknot.child-run-admission-intent.v1\0";
19
20/// A bounded, immutable child admission candidate and its stable retry digest.
21///
22/// Binds one parent admission and logical child key to the full child Agent,
23/// graph, request, initial state, authority, and resolved budget. Candidate
24/// child Run/thread/invocation IDs deliberately do not enter `spawn_digest`;
25/// they are retained in `child` and checked by its own integrity encoding.
26/// The first atomic commit must choose the durable IDs for all later retries.
27///
28/// This is preparation, not permission to spawn. Neither construction nor
29/// deserialization proves live authority, declaration membership, lease,
30/// remaining budget, depth, or concurrency. A future store must call
31/// [`Self::validate_for`] and [`Self::validate_declaration`] against authoritative snapshots and perform those
32/// additional checks in its ownership/admission transaction. No existing root
33/// admission API may be used as a substitute for that transaction.
34#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
35#[serde(deny_unknown_fields)]
36pub struct ChildRunAdmissionIntent {
37    key: ChildRunKey,
38    parent_admission_digest: Digest,
39    child: AgentAdmissionIntent,
40    child_graph: CompiledGraph,
41    initial_state: CheckpointState,
42    spawn_digest: Digest,
43}
44
45impl ChildRunAdmissionIntent {
46    /// Maximum complete canonical preparation envelope size, in bytes.
47    pub const MAX_SNAPSHOT_BYTES: usize = 16 * 1024 * 1024;
48
49    /// Constructs an intent and checks parent scope, principal, and narrowing.
50    ///
51    /// `parent` must be restored by trusted storage before use. Its checksum
52    /// alone is not authentication. Current readiness and schema validation
53    /// are deliberately repeated by [`Self::validate_for`].
54    pub fn new(
55        parent: &AgentAdmission,
56        key: ChildRunKey,
57        child: AgentAdmissionIntent,
58        child_graph: CompiledGraph,
59        initial_state: CheckpointState,
60    ) -> Result<Self, ChildRunAdmissionIntentError> {
61        let intent = Self::build(key, parent.digest(), child, child_graph, initial_state)?;
62        intent.validate_parent(parent)?;
63        Ok(intent)
64    }
65
66    fn build(
67        key: ChildRunKey,
68        parent_admission_digest: Digest,
69        child: AgentAdmissionIntent,
70        child_graph: CompiledGraph,
71        initial_state: CheckpointState,
72    ) -> Result<Self, ChildRunAdmissionIntentError> {
73        if key.tenant_id() != child.provenance().tenant_id()
74            || key.parent_run_id() == child.provenance().run_id()
75        {
76            return Err(ChildRunAdmissionIntentError::ChildScopeMismatch);
77        }
78        if !key.parent().graph_namespace().is_root() {
79            return Err(ChildRunAdmissionIntentError::UnsupportedParentNamespace);
80        }
81        if child.graph() != &child_graph.reference()
82            || child.descriptor().input_schema() != child_graph.input_schema()
83            || child.descriptor().output_schema() != child_graph.output_schema()
84            || initial_state.schema() != child_graph.state_schema()
85        {
86            return Err(ChildRunAdmissionIntentError::ChildGraphMismatch);
87        }
88        let mut intent = Self {
89            key,
90            parent_admission_digest,
91            child,
92            child_graph,
93            initial_state,
94            spawn_digest: Digest::sha256([]),
95        };
96        intent.spawn_digest = intent.compute_spawn_digest()?;
97        intent.canonical_bytes()?;
98        Ok(intent)
99    }
100
101    fn validate_parent(&self, parent: &AgentAdmission) -> Result<(), ChildRunAdmissionIntentError> {
102        let admitted = parent.intent();
103        if self.parent_admission_digest != parent.digest()
104            || self.key.tenant_id() != admitted.provenance().tenant_id()
105            || self.key.parent_run_id() != admitted.provenance().run_id()
106            || self.key.parent().base_checkpoint().graph() != admitted.graph()
107            || self
108                .key
109                .parent()
110                .base_checkpoint()
111                .journal_head()
112                .recorded_at()
113                < parent.admitted_at()
114        {
115            return Err(ChildRunAdmissionIntentError::ParentMismatch);
116        }
117        // The first local delegation profile is same-principal only. A future
118        // identity-exchange profile needs an explicit authenticated contract.
119        if self.child.authority().principal() != admitted.authority().principal() {
120            return Err(ChildRunAdmissionIntentError::PrincipalMismatch);
121        }
122        if !self
123            .child
124            .authority()
125            .granted_scopes()
126            .is_subset(admitted.authority().granted_scopes())
127        {
128            return Err(ChildRunAdmissionIntentError::ScopeWidening);
129        }
130        self.child.budget().validate_narrowing(admitted.budget())?;
131        Ok(())
132    }
133
134    /// Revalidates against a trusted parent admission, current checkpoint,
135    /// offline schemas, and an authoritative fresh-admission clock observation.
136    ///
137    /// Deserialization alone cannot perform these external checks. The supplied
138    /// parent graph policy must additionally pass [`Self::validate_declaration`].
139    /// The supplied
140    /// checkpoint must be the locked current head for actual admission; an
141    /// unlocked preview does not authorize a later commit. Lost-ACK recovery
142    /// must first look up exact committed spawn
143    /// evidence; do not use this fresh check to invalidate a historical commit.
144    pub fn validate_for<V: GraphSchemaValidator + ?Sized>(
145        &self,
146        parent: &AgentAdmission,
147        checkpoint: &Checkpoint,
148        schemas: &V,
149        observed_at: Timestamp,
150    ) -> Result<(), ChildRunAdmissionIntentError> {
151        self.validate_parent(parent)?;
152        if self.key.parent().base_checkpoint() != &checkpoint.head() {
153            return Err(ChildRunAdmissionIntentError::ParentCheckpointMismatch);
154        }
155        let activation =
156            NodeActivation::for_ready_root(checkpoint, self.key.parent().node_id().clone())
157                .map_err(|_| ChildRunAdmissionIntentError::ParentNotReady)?;
158        if &activation != self.key.parent() {
159            return Err(ChildRunAdmissionIntentError::ParentActivationMismatch);
160        }
161        if observed_at < checkpoint.journal_head().recorded_at() {
162            return Err(ChildRunAdmissionIntentError::ClockBeforeCheckpoint);
163        }
164        if observed_at >= self.child.budget().deadline()
165            || observed_at >= parent.intent().budget().deadline()
166        {
167            return Err(ChildRunAdmissionIntentError::DeadlineExpired);
168        }
169        for (schema, data) in [
170            (
171                self.child.request().input_schema(),
172                self.child.request().input(),
173            ),
174            (self.initial_state.schema(), self.initial_state.data()),
175            (
176                self.child.authority().evidence().schema(),
177                self.child.authority().evidence().data(),
178            ),
179        ] {
180            schemas.validate(schema, data)?;
181        }
182        Ok(())
183    }
184
185    fn compute_spawn_digest(&self) -> Result<Digest, ChildRunAdmissionIntentError> {
186        // Use named closed fields, never the entire admission intent: that
187        // would accidentally bind generated candidate provenance to retries.
188        let wire = serde_json::json!({
189            "key": self.key.digest(),
190            "parent_admission_digest": self.parent_admission_digest,
191            "tenant_id": self.child.provenance().tenant_id(),
192            "descriptor": self.child.descriptor(),
193            "request": self.child.request(),
194            "budget_layers": self.child.budget_layers(),
195            "budget": self.child.budget(),
196            "graph": self.child.graph(),
197            "authority": self.child.authority(),
198            "initial_state": self.initial_state,
199            "initial_ready_nodes": self.child_graph.entry_nodes(),
200            "parent_close_policy": "cancel_and_join"
201        });
202        let canonical = canonical(&wire)?;
203        let mut bytes = Vec::with_capacity(SPAWN_DOMAIN.len() + canonical.len());
204        bytes.extend_from_slice(SPAWN_DOMAIN);
205        bytes.extend_from_slice(&canonical);
206        Ok(Digest::sha256(bytes))
207    }
208
209    /// Returns the complete bounded canonical envelope, including candidate IDs.
210    pub fn canonical_bytes(&self) -> Result<Vec<u8>, ChildRunAdmissionIntentError> {
211        let bytes = canonical(self)?;
212        if bytes.len() > Self::MAX_SNAPSHOT_BYTES {
213            return Err(ChildRunAdmissionIntentError::SnapshotTooLarge);
214        }
215        Ok(bytes)
216    }
217
218    /// Returns the exact parent activation and slot.
219    #[must_use]
220    pub const fn key(&self) -> &ChildRunKey {
221        &self.key
222    }
223    /// Returns the pinned committed parent admission digest.
224    #[must_use]
225    pub const fn parent_admission_digest(&self) -> Digest {
226        self.parent_admission_digest
227    }
228    /// Returns the candidate child admission with its generated provenance.
229    #[must_use]
230    pub const fn child(&self) -> &AgentAdmissionIntent {
231        &self.child
232    }
233    /// Returns the complete pinned child graph, including its initial ready set.
234    #[must_use]
235    pub const fn child_graph(&self) -> &CompiledGraph {
236        &self.child_graph
237    }
238    /// Returns the explicitly supplied private child initial state.
239    #[must_use]
240    pub const fn initial_state(&self) -> &CheckpointState {
241        &self.initial_state
242    }
243    /// Returns stable spawn comparison material, not an authorization signature.
244    #[must_use]
245    pub const fn spawn_digest(&self) -> Digest {
246        self.spawn_digest
247    }
248}
249
250fn canonical<T: Serialize>(value: &T) -> Result<Vec<u8>, ChildRunAdmissionIntentError> {
251    crate::agent_admission::canonical_bytes(value).map_err(|error| match error {
252        AgentAdmissionIntentError::NonInteroperableNumber => {
253            ChildRunAdmissionIntentError::NonInteroperableNumber
254        }
255        _ => ChildRunAdmissionIntentError::IntegritySerialization,
256    })
257}
258
259impl fmt::Debug for ChildRunAdmissionIntent {
260    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
261        formatter
262            .debug_struct("ChildRunAdmissionIntent")
263            .field("key_digest", &self.key.digest())
264            .field("parent_admission_digest", &self.parent_admission_digest)
265            .field("spawn_digest", &self.spawn_digest)
266            .finish_non_exhaustive()
267    }
268}
269
270impl<'de> Deserialize<'de> for ChildRunAdmissionIntent {
271    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
272        #[derive(Deserialize)]
273        #[serde(deny_unknown_fields)]
274        struct Wire {
275            key: ChildRunKey,
276            parent_admission_digest: Digest,
277            child: AgentAdmissionIntent,
278            child_graph: CompiledGraph,
279            initial_state: CheckpointState,
280            spawn_digest: Digest,
281        }
282        let wire = Wire::deserialize(deserializer)?;
283        let intent = Self::build(
284            wire.key,
285            wire.parent_admission_digest,
286            wire.child,
287            wire.child_graph,
288            wire.initial_state,
289        )
290        .map_err(de::Error::custom)?;
291        if intent.spawn_digest != wire.spawn_digest {
292            return Err(de::Error::custom(
293                ChildRunAdmissionIntentError::DigestMismatch,
294            ));
295        }
296        Ok(intent)
297    }
298}
299
300/// Closed public-safe child preparation or fresh-admission validation failure.
301#[derive(Clone, Debug, Eq, Error, PartialEq)]
302#[non_exhaustive]
303pub enum ChildRunAdmissionIntentError {
304    /// Child tenant differs or the child reuses the parent Run ID.
305    #[error("child admission crosses scope or reuses its parent run")]
306    ChildScopeMismatch,
307    /// Same-run nested namespaces do not yet have a readiness contract.
308    #[error("child admission requires a root-namespace parent activation")]
309    UnsupportedParentNamespace,
310    /// Child definition, graph, or schema pins differ.
311    #[error("child admission graph or schema mismatch")]
312    ChildGraphMismatch,
313    /// The supplied parent does not match the pinned admission and graph scope.
314    #[error("child admission parent mismatch")]
315    ParentMismatch,
316    /// Cross-principal identity exchange is not supported by this profile.
317    #[error("child admission principal differs from parent")]
318    PrincipalMismatch,
319    /// Child scopes are not a subset of the parent grant.
320    #[error("child admission widens granted scopes")]
321    ScopeWidening,
322    /// A child budget limit exceeds its immutable parent limit.
323    #[error(transparent)]
324    Budget(#[from] BudgetNarrowingError),
325    /// Locked parent checkpoint differs from the candidate's base head.
326    #[error("child admission parent checkpoint mismatch")]
327    ParentCheckpointMismatch,
328    /// The requested parent node is not ready.
329    #[error("child admission parent node is not ready")]
330    ParentNotReady,
331    /// Logical activation input differs from deterministic readiness derivation.
332    #[error("child admission parent activation mismatch")]
333    ParentActivationMismatch,
334    /// The fresh clock observation predates the committed parent checkpoint.
335    #[error("child admission clock predates parent checkpoint")]
336    ClockBeforeCheckpoint,
337    /// The child or parent deadline has expired, including equality.
338    #[error("child admission deadline expired")]
339    DeadlineExpired,
340    /// A pinned offline schema could not validate input, state, or authority evidence.
341    #[error(transparent)]
342    Schema(#[from] GraphSchemaValidationError),
343    /// Complete canonical envelope exceeded its fixed bound.
344    #[error("child admission snapshot exceeds its byte limit")]
345    SnapshotTooLarge,
346    /// Integrity material could not be serialized.
347    #[error("child admission canonical serialization failed")]
348    IntegritySerialization,
349    /// JSON numbers could not be represented interoperably without rounding.
350    #[error("child admission contains a non-interoperable JSON integer")]
351    NonInteroperableNumber,
352    /// Persisted retry digest no longer matches the intent.
353    #[error("child admission spawn digest mismatch")]
354    DigestMismatch,
355}
356
357#[cfg(test)]
358#[path = "child_run_admission_tests.rs"]
359mod tests;