Skip to main content

stateknot_core/
child_join.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Dedicated child Join identity and terminal evidence, independent of timers.
5
6use crate::{ChildRunBudgetSettlement, ChildRunKey, Digest, JournalHead, NodeActivation};
7use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
8use serde::{Deserialize, Deserializer, Serialize, de};
9use std::{collections::BTreeSet, fmt};
10use thiserror::Error;
11
12/// One sealed, nonempty set of owned children for one logical parent activation.
13/// The store must prove ownership and require the complete admitted set before
14/// registering it. Construction alone grants no authority and performs no I/O.
15#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
16#[serde(deny_unknown_fields)]
17pub struct ChildRunJoinRequest {
18    #[schemars(schema_with = "version_schema")]
19    version: u8,
20    #[schemars(schema_with = "keys_schema")]
21    keys: Vec<ChildRunKey>,
22    activation_digest: Digest,
23    digest: Digest,
24}
25
26impl ChildRunJoinRequest {
27    /// Same bound as the maximum number of declared slots on one node.
28    pub const MAX_CHILDREN: usize = 64;
29    /// Hard canonical wire ceiling; child inputs and outputs are not included.
30    pub const MAX_BYTES: usize = 4 * 1024 * 1024;
31
32    /// Seals keys in case-sensitive slot order, independent of completion order.
33    pub fn new(keys: impl IntoIterator<Item = ChildRunKey>) -> Result<Self, ChildRunJoinError> {
34        let mut values = Vec::new();
35        for key in keys {
36            if values.len() == Self::MAX_CHILDREN {
37                return Err(ChildRunJoinError::Bounds);
38            }
39            values.push(key);
40        }
41        let first = values.first().ok_or(ChildRunJoinError::Bounds)?;
42        if values.iter().any(|key| key.parent() != first.parent()) {
43            return Err(ChildRunJoinError::Scope);
44        }
45        let activation_digest = crate::node_attempt::compute_activation_digest(first.parent())
46            .map_err(|_| ChildRunJoinError::Encoding)?;
47        values.sort_by(|left, right| left.slot().cmp(right.slot()));
48        if values
49            .windows(2)
50            .any(|pair| pair[0].slot() == pair[1].slot())
51        {
52            return Err(ChildRunJoinError::Duplicate);
53        }
54        let digest = checksum(
55            "stateknot.child-join-request.v1",
56            &(1_u8, &values, activation_digest),
57        )?;
58        let result = Self {
59            version: 1,
60            keys: values,
61            activation_digest,
62            digest,
63        };
64        result.canonical_bytes()?;
65        Ok(result)
66    }
67    /// Returns canonical slot order. Identity is physical-attempt independent.
68    #[must_use]
69    pub fn keys(&self) -> &[ChildRunKey] {
70        &self.keys
71    }
72    /// Returns the common exact parent activation.
73    #[must_use]
74    pub fn activation(&self) -> &NodeActivation {
75        self.keys[0].parent()
76    }
77    /// Returns the existing canonical node activation digest.
78    #[must_use]
79    pub const fn activation_digest(&self) -> Digest {
80        self.activation_digest
81    }
82    /// Returns the sealed request identity.
83    #[must_use]
84    pub const fn digest(&self) -> Digest {
85        self.digest
86    }
87    /// Encodes the bounded versioned request without storage coordinates.
88    pub fn canonical_bytes(&self) -> Result<Vec<u8>, ChildRunJoinError> {
89        canonical(self)
90    }
91}
92
93impl<'de> Deserialize<'de> for ChildRunJoinRequest {
94    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
95        #[derive(Deserialize)]
96        #[serde(deny_unknown_fields)]
97        struct Wire {
98            version: u8,
99            #[serde(deserialize_with = "bounded_values")]
100            keys: Vec<ChildRunKey>,
101            activation_digest: Digest,
102            digest: Digest,
103        }
104        let wire = Wire::deserialize(deserializer)?;
105        if wire.version != 1
106            || wire
107                .keys
108                .windows(2)
109                .any(|pair| pair[0].slot() >= pair[1].slot())
110        {
111            return Err(de::Error::custom(ChildRunJoinError::Noncanonical));
112        }
113        let result = Self::new(wire.keys).map_err(de::Error::custom)?;
114        if result.digest != wire.digest || result.activation_digest != wire.activation_digest {
115            return Err(de::Error::custom(ChildRunJoinError::DigestMismatch));
116        }
117        Ok(result)
118    }
119}
120
121/// Immutable complete, priced terminal evidence in the request's declared order.
122/// Each position corresponds to the same-position ownership key. A store must
123/// revalidate the actual owned admission and exact terminal journal for every
124/// position; a matching checksum is not authentication or proof of execution.
125#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
126#[serde(deny_unknown_fields)]
127pub struct ChildRunJoinBinding {
128    request: ChildRunJoinRequest,
129    #[schemars(schema_with = "terminals_schema")]
130    terminals: Vec<ChildRunBudgetSettlement>,
131    digest: Digest,
132}
133impl ChildRunJoinBinding {
134    /// Constructs a complete binding, rejecting duplicates, crossed tenants or missing children.
135    pub fn new(
136        request: ChildRunJoinRequest,
137        terminals: impl IntoIterator<Item = ChildRunBudgetSettlement>,
138    ) -> Result<Self, ChildRunJoinError> {
139        let mut values = Vec::new();
140        let mut children = BTreeSet::new();
141        for value in terminals {
142            if values.len() == ChildRunJoinRequest::MAX_CHILDREN {
143                return Err(ChildRunJoinError::Bounds);
144            }
145            if value.terminal().tenant_id() != request.activation().tenant_id()
146                || value.terminal().run_id() == request.activation().run_id()
147            {
148                return Err(ChildRunJoinError::Scope);
149            }
150            if !children.insert(value.terminal().run_id()) {
151                return Err(ChildRunJoinError::Duplicate);
152            }
153            values.push(value);
154        }
155        if values.len() != request.keys.len() {
156            return Err(ChildRunJoinError::Bounds);
157        }
158        let digest = checksum(
159            "stateknot.child-join-binding.v1",
160            &(request.digest(), &values),
161        )?;
162        let result = Self {
163            request,
164            terminals: values,
165            digest,
166        };
167        result.canonical_bytes()?;
168        Ok(result)
169    }
170    /// Returns the original sealed request.
171    #[must_use]
172    pub const fn request(&self) -> &ChildRunJoinRequest {
173        &self.request
174    }
175    /// Returns one complete terminal observation per request key, in slot order.
176    #[must_use]
177    pub fn terminals(&self) -> &[ChildRunBudgetSettlement] {
178        &self.terminals
179    }
180    /// Returns the version-domain-separated evidence digest.
181    #[must_use]
182    pub const fn digest(&self) -> Digest {
183        self.digest
184    }
185    /// Returns bounded canonical evidence without copying child output payloads.
186    pub fn canonical_bytes(&self) -> Result<Vec<u8>, ChildRunJoinError> {
187        canonical(self)
188    }
189    /// Anchors the immutable binding to a parent publication event.
190    pub fn head(&self, journal: JournalHead) -> Result<ChildRunJoinHead, ChildRunJoinError> {
191        if self
192            .terminals
193            .iter()
194            .any(|value| value.terminal().recorded_at() > journal.recorded_at())
195        {
196            return Err(ChildRunJoinError::Clock);
197        }
198        ChildRunJoinHead::restore(
199            self.request.activation().clone(),
200            self.request.digest(),
201            self.digest,
202            journal,
203        )
204    }
205}
206impl<'de> Deserialize<'de> for ChildRunJoinBinding {
207    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
208        #[derive(Deserialize)]
209        #[serde(deny_unknown_fields)]
210        struct Wire {
211            request: ChildRunJoinRequest,
212            #[serde(deserialize_with = "bounded_values")]
213            terminals: Vec<ChildRunBudgetSettlement>,
214            digest: Digest,
215        }
216        let wire = Wire::deserialize(deserializer)?;
217        let result = Self::new(wire.request, wire.terminals).map_err(de::Error::custom)?;
218        if result.digest != wire.digest {
219            return Err(de::Error::custom(ChildRunJoinError::DigestMismatch));
220        }
221        Ok(result)
222    }
223}
224
225/// Compact Join evidence consumed by a parent pending result. The parent event
226/// is not a child terminal event: cross-Run journal sequences are never compared.
227#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
228#[serde(deny_unknown_fields)]
229pub struct ChildRunJoinHead {
230    activation: NodeActivation,
231    request_digest: Digest,
232    binding_digest: Digest,
233    journal_head: JournalHead,
234}
235impl ChildRunJoinHead {
236    fn restore(
237        activation: NodeActivation,
238        request_digest: Digest,
239        binding_digest: Digest,
240        journal_head: JournalHead,
241    ) -> Result<Self, ChildRunJoinError> {
242        if journal_head.tenant_id() != activation.tenant_id()
243            || journal_head.run_id() != activation.run_id()
244        {
245            return Err(ChildRunJoinError::Scope);
246        }
247        let base = activation.base_checkpoint().journal_head();
248        if journal_head.sequence() <= base.sequence()
249            || journal_head.recorded_at() < base.recorded_at()
250        {
251            return Err(ChildRunJoinError::Clock);
252        }
253        Ok(Self {
254            activation,
255            request_digest,
256            binding_digest,
257            journal_head,
258        })
259    }
260    /// Returns the consuming parent activation.
261    #[must_use]
262    pub const fn activation(&self) -> &NodeActivation {
263        &self.activation
264    }
265    /// Returns the original sealed request identity.
266    #[must_use]
267    pub const fn request_digest(&self) -> Digest {
268        self.request_digest
269    }
270    /// Returns the complete terminal binding digest.
271    #[must_use]
272    pub const fn binding_digest(&self) -> Digest {
273        self.binding_digest
274    }
275    /// Returns the exact parent publication event.
276    #[must_use]
277    pub const fn journal_head(&self) -> &JournalHead {
278        &self.journal_head
279    }
280}
281impl<'de> Deserialize<'de> for ChildRunJoinHead {
282    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
283        #[derive(Deserialize)]
284        #[serde(deny_unknown_fields)]
285        struct Wire {
286            activation: NodeActivation,
287            request_digest: Digest,
288            binding_digest: Digest,
289            journal_head: JournalHead,
290        }
291        let wire = Wire::deserialize(deserializer)?;
292        Self::restore(
293            wire.activation,
294            wire.request_digest,
295            wire.binding_digest,
296            wire.journal_head,
297        )
298        .map_err(de::Error::custom)
299    }
300}
301
302fn canonical<T: Serialize>(value: &T) -> Result<Vec<u8>, ChildRunJoinError> {
303    let bytes = serde_json_canonicalizer::to_vec(value).map_err(|_| ChildRunJoinError::Encoding)?;
304    if bytes.len() > ChildRunJoinRequest::MAX_BYTES {
305        return Err(ChildRunJoinError::Bounds);
306    }
307    Ok(bytes)
308}
309
310fn version_schema(_: &mut SchemaGenerator) -> Schema {
311    json_schema!({"type":"integer","const":1})
312}
313fn keys_schema(generator: &mut SchemaGenerator) -> Schema {
314    json_schema!({"type":"array","minItems":1,"maxItems":64,
315        "items":generator.subschema_for::<ChildRunKey>()})
316}
317fn terminals_schema(generator: &mut SchemaGenerator) -> Schema {
318    json_schema!({"type":"array","minItems":1,"maxItems":64,
319        "items":generator.subschema_for::<ChildRunBudgetSettlement>()})
320}
321fn checksum<T: Serialize>(domain: &str, value: &T) -> Result<Digest, ChildRunJoinError> {
322    let mut bytes = domain.as_bytes().to_vec();
323    bytes.push(0);
324    bytes.extend(canonical(value)?);
325    Ok(Digest::sha256(bytes))
326}
327fn bounded_values<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
328    deserializer: D,
329) -> Result<Vec<T>, D::Error> {
330    struct Visitor<T>(std::marker::PhantomData<T>);
331    impl<'de, T: Deserialize<'de>> de::Visitor<'de> for Visitor<T> {
332        type Value = Vec<T>;
333        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334            f.write_str("at most 64 child Join values")
335        }
336        fn visit_seq<A: de::SeqAccess<'de>>(
337            self,
338            mut sequence: A,
339        ) -> Result<Self::Value, A::Error> {
340            let mut values = Vec::new();
341            while let Some(value) = sequence.next_element()? {
342                if values.len() == ChildRunJoinRequest::MAX_CHILDREN {
343                    return Err(de::Error::custom(ChildRunJoinError::Bounds));
344                }
345                values.push(value);
346            }
347            Ok(values)
348        }
349    }
350    deserializer.deserialize_seq(Visitor(std::marker::PhantomData))
351}
352
353/// Closed validation failures, without child inputs, outputs or diagnostics.
354#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
355#[non_exhaustive]
356pub enum ChildRunJoinError {
357    /// Empty, oversized or incomplete set.
358    #[error("child Join bounds exceeded or incomplete")]
359    Bounds,
360    /// Crossed activation, Run or tenant.
361    #[error("child Join scope mismatch")]
362    Scope,
363    /// A child or declared slot occurred more than once.
364    #[error("duplicate child Join member")]
365    Duplicate,
366    /// Unsupported version or noncanonical ordering.
367    #[error("noncanonical child Join encoding")]
368    Noncanonical,
369    /// Restored integrity evidence changed.
370    #[error("child Join digest mismatch")]
371    DigestMismatch,
372    /// Publication precedes its required evidence.
373    #[error("child Join publication ordering mismatch")]
374    Clock,
375    /// Canonical serialization failed.
376    #[error("child Join encoding failed")]
377    Encoding,
378}