Skip to main content

stateknot_runtime/
child_join.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bounded Join publication and read-only, slot-scoped terminal access.
5
6use std::sync::Arc;
7
8use serde_json::{Value, json};
9use stateknot_core::{
10    BoundedJson, BoxFuture, CancellationSignal, ChildRunJoinBinding, ChildRunJoinHead,
11    ChildRunJoinRequest, ChildRunSlot, Digest, EventId, JournalAppend, JournalEventIntent,
12    JournalEventKind, JournalExpectation, JournalPayload, RunLifecycle, SchemaReference, TenantId,
13    Version,
14};
15use stateknot_store_postgres::{
16    ChildJoinCommitOutcome, ChildJoinRecord, PostgresStore, StoreError,
17};
18
19use crate::{
20    ChildReconcilerBuildError, DurableChildReconcilerOptions, ExecutableGraphRegistry,
21    JsonSchemaRegistry, JsonSchemaRegistryBuilder,
22};
23
24/// Offline identity of the embedded, closed Join audit schema.
25pub const STANDARD_CHILD_JOIN_EVENT_SCHEMA_ID: &str =
26    "https://stknot.com/schemas/runtime/child-join-event/1.0.0";
27
28/// Returns the exact release schema, without fetching its identity URL.
29pub fn standard_child_join_event_schema()
30-> Result<(SchemaReference, Value), ChildReconcilerBuildError> {
31    let document: Value =
32        serde_json::from_str(include_str!("../schemas/child-join-event-1.0.0.json"))
33            .map_err(|_| ChildReconcilerBuildError::SchemaDefinition)?;
34    let canonical = serde_json_canonicalizer::to_vec(&document)
35        .map_err(|_| ChildReconcilerBuildError::SchemaDefinition)?;
36    Ok((
37        SchemaReference::new(
38            STANDARD_CHILD_JOIN_EVENT_SCHEMA_ID
39                .parse()
40                .map_err(|_| ChildReconcilerBuildError::SchemaDefinition)?,
41            Version::new(1, 0, 0),
42            Digest::sha256(canonical),
43        ),
44        document,
45    ))
46}
47
48/// Registers the Join schema before freezing a Join-enabled deployment.
49pub fn register_standard_child_join_event_schema(
50    builder: &mut JsonSchemaRegistryBuilder,
51) -> Result<SchemaReference, ChildReconcilerBuildError> {
52    let (reference, document) = standard_child_join_event_schema()?;
53    builder.register(reference.clone(), document)?;
54    Ok(reference)
55}
56
57pub(crate) fn schema_available(schemas: &JsonSchemaRegistry) -> bool {
58    standard_child_join_event_schema().is_ok_and(|(schema, _)| schemas.contains(&schema))
59}
60
61pub(crate) fn payload(
62    schemas: &JsonSchemaRegistry,
63    request: &ChildRunJoinRequest,
64    publication: bool,
65) -> Result<JournalPayload, StoreError> {
66    let (schema, _) =
67        standard_child_join_event_schema().map_err(|_| StoreError::ChildJoinRejected)?;
68    let (operation, kind) = if publication {
69        ("child_join_published", "child-join-published")
70    } else {
71        ("child_join_registered", "child-join-registered")
72    };
73    let digest = request.digest().to_string();
74    let digest = digest
75        .strip_prefix("sha256:")
76        .ok_or(StoreError::ChildJoinRejected)?;
77    let data =
78        BoundedJson::try_from_value(json!({"operation": operation, "request_digest": digest}))
79            .map_err(|_| StoreError::ChildJoinRejected)?;
80    schemas
81        .validate_bounded(&schema, &data)
82        .map_err(|_| StoreError::ChildJoinRejected)?;
83    JournalPayload::new(
84        schema,
85        JournalEventKind::new(kind).map_err(|_| StoreError::ChildJoinRejected)?,
86        data,
87    )
88    .map_err(|_| StoreError::ChildJoinRejected)
89}
90
91/// Verified publication and lazy, exact-slot terminal access for resumed node code.
92/// The context retains compact terminal proofs, never all child output bodies.
93/// Each read revalidates ownership, settlement, frozen graph and output schema.
94/// Holding or reading this handle does not consume the Join or authorize writes.
95#[derive(Clone, Debug)]
96pub struct GraphChildJoin {
97    store: PostgresStore,
98    registry: ExecutableGraphRegistry,
99    binding: ChildRunJoinBinding,
100    head: ChildRunJoinHead,
101}
102
103impl GraphChildJoin {
104    pub(crate) async fn prepare(
105        store: PostgresStore,
106        registry: ExecutableGraphRegistry,
107        record: &ChildJoinRecord,
108    ) -> Result<Arc<Self>, StoreError> {
109        if record.consumed().is_some() {
110            return Err(StoreError::ChildJoinRejected);
111        }
112        let value = Arc::new(Self {
113            store,
114            registry,
115            binding: record
116                .binding()
117                .cloned()
118                .ok_or(StoreError::ChildJoinRejected)?,
119            head: record
120                .head()
121                .cloned()
122                .ok_or(StoreError::ChildJoinRejected)?,
123        });
124        // Qualify every output before dispatch, one at a time; no 64-output buffer.
125        for key in value.binding.request().keys() {
126            value.load_child(key.slot()).await?;
127        }
128        Ok(value)
129    }
130
131    /// Returns canonical slot order and complete, priced terminal proofs.
132    #[must_use]
133    pub const fn binding(&self) -> &ChildRunJoinBinding {
134        &self.binding
135    }
136
137    /// Returns the exact publication automatically attached to node completion.
138    #[must_use]
139    pub const fn head(&self) -> &ChildRunJoinHead {
140        &self.head
141    }
142
143    /// Loads only a sealed slot. Success retains its validated Agent output;
144    /// failure/cancellation remain typed terminal lifecycle evidence. Bodies
145    /// stay subject to existing per-Run bounds; callers control retention.
146    pub async fn load_child(&self, slot: &ChildRunSlot) -> Result<RunLifecycle, StoreError> {
147        let index = self
148            .binding
149            .request()
150            .keys()
151            .iter()
152            .position(|key| key.slot() == slot)
153            .ok_or(StoreError::ChildJoinRejected)?;
154        let record = self
155            .store
156            .load_child_run(&self.binding.request().keys()[index])
157            .await?;
158        if record.child().run().is_quarantined() {
159            return Err(StoreError::RunQuarantined);
160        }
161        if record.settlement() != Some(&self.binding.terminals()[index]) {
162            return Err(StoreError::ChildJoinRejected);
163        }
164        let graph = self
165            .registry
166            .resolve(record.intent().child().graph())
167            .ok_or(StoreError::ChildJoinRejected)?;
168        if graph.graph() != record.intent().child_graph() {
169            return Err(StoreError::ChildJoinRejected);
170        }
171        let lifecycle = record.child().run().lifecycle();
172        if let Some(result) = lifecycle.result() {
173            if result.output_schema() != graph.graph().output_schema()
174                || result.output_schema() != record.intent().child().descriptor().output_schema()
175            {
176                return Err(StoreError::ChildJoinRejected);
177            }
178            self.registry
179                .schemas()
180                .validate_bounded(result.output_schema(), result.output())
181                .map_err(|_| StoreError::ChildJoinRejected)?;
182        }
183        Ok(lifecycle.clone())
184    }
185}
186
187/// Tenant-bound in-process continuation. After a restart begin a new sweep at None.
188#[derive(Clone, Debug)]
189pub struct ChildJoinPublicationCursor {
190    tenant: TenantId,
191    after: Option<ChildRunJoinRequest>,
192}
193
194/// Per-request publication result; errors never silently disappear or block later keys.
195#[derive(Debug)]
196pub struct ChildJoinPublicationItem {
197    request: ChildRunJoinRequest,
198    result: Result<ChildJoinCommitOutcome, StoreError>,
199}
200impl ChildJoinPublicationItem {
201    /// Exact request for authorized operator correlation, not metric labels.
202    #[must_use]
203    pub const fn request(&self) -> &ChildRunJoinRequest {
204        &self.request
205    }
206    /// Exact commit/recovery or public-safe error. Inspect every item.
207    pub fn result(&self) -> Result<&ChildJoinCommitOutcome, &StoreError> {
208        self.result.as_ref()
209    }
210}
211
212/// One finite publication pass, separate from cancellation and accounting lanes.
213#[derive(Debug)]
214pub struct ChildJoinPublicationTick {
215    cursor: ChildJoinPublicationCursor,
216    items: Vec<ChildJoinPublicationItem>,
217    cancelled: bool,
218}
219impl ChildJoinPublicationTick {
220    /// Retain after successes and per-item errors. Each completed sweep resets itself.
221    #[must_use]
222    pub const fn cursor(&self) -> &ChildJoinPublicationCursor {
223        &self.cursor
224    }
225    /// At most 16 results. No output bodies are aggregated.
226    #[must_use]
227    pub fn items(&self) -> &[ChildJoinPublicationItem] {
228        &self.items
229    }
230    /// Unfinished or ambiguously committed work stays recoverable in the store.
231    #[must_use]
232    pub const fn is_cancelled(&self) -> bool {
233        self.cancelled
234    }
235}
236
237/// Trusted, tenant-scoped Join publisher; no node or provider code is dispatched.
238/// Schedule alongside `DurableChildReconciler` and execution workers. The host
239/// authenticates tenants, retains cursors, applies fairness, and alerts on errors.
240/// No parent lease or transaction is retained between calls.
241///
242/// ```no_run
243/// use stateknot_core::{CancellationSignal, TenantId};
244/// use stateknot_runtime::{ChildJoinPublicationCursor, ChildJoinPublicationTick,
245///     DurableChildJoinPublisher, DurableChildReconcilerOptions, JsonSchemaRegistryBuilder,
246///     register_standard_child_join_event_schema};
247/// use stateknot_store_postgres::{PostgresStore, StoreError};
248///
249/// fn configure(store: PostgresStore, mut schemas: JsonSchemaRegistryBuilder)
250///     -> Result<DurableChildJoinPublisher, Box<dyn std::error::Error>> {
251///     register_standard_child_join_event_schema(&mut schemas)?;
252///     Ok(DurableChildJoinPublisher::new(store, schemas.build()?,
253///         DurableChildReconcilerOptions::default())?)
254/// }
255///
256/// async fn publish_step(worker: &DurableChildJoinPublisher, authorized_tenant: TenantId,
257///     cursor: &mut Option<ChildJoinPublicationCursor>, shutdown: CancellationSignal)
258///     -> Result<ChildJoinPublicationTick, StoreError> {
259///     let report = worker.tick(authorized_tenant, cursor.clone(), shutdown).await?;
260///     *cursor = Some(report.cursor().clone());
261///     // Return the entire report to the host: inspect all item errors, apply
262///     // fairness and cadence, and restart with None after process loss.
263///     Ok(report)
264/// }
265/// ```
266#[derive(Clone, Debug)]
267pub struct DurableChildJoinPublisher {
268    store: PostgresStore,
269    schemas: JsonSchemaRegistry,
270    options: DurableChildReconcilerOptions,
271}
272impl DurableChildJoinPublisher {
273    /// Requires the exact embedded schema and a finite validated retry policy.
274    pub fn new(
275        store: PostgresStore,
276        schemas: JsonSchemaRegistry,
277        options: DurableChildReconcilerOptions,
278    ) -> Result<Self, ChildReconcilerBuildError> {
279        if !schema_available(&schemas) {
280            return Err(ChildReconcilerBuildError::SchemaUnavailable);
281        }
282        Ok(Self {
283            store,
284            schemas,
285            options,
286        })
287    }
288
289    /// Processes at most 16 eligible parents, continuing past each per-item error.
290    /// Discovery failure fails the tick; retry from the last retained cursor.
291    /// Shutdown can win during an ambiguous commit; subsequent reads converge.
292    pub fn tick(
293        &self,
294        tenant: TenantId,
295        after: Option<ChildJoinPublicationCursor>,
296        shutdown: CancellationSignal,
297    ) -> BoxFuture<'_, Result<ChildJoinPublicationTick, StoreError>> {
298        Box::pin(async move {
299            if after.as_ref().is_some_and(|cursor| cursor.tenant != tenant) {
300                return Err(StoreError::ChildJoinRejected);
301            }
302            let mut tick = ChildJoinPublicationTick {
303                cursor: after.unwrap_or(ChildJoinPublicationCursor {
304                    tenant: tenant.clone(),
305                    after: None,
306                }),
307                items: Vec::with_capacity(16),
308                cancelled: false,
309            };
310            let requests = tokio::select! {
311                biased;
312                () = shutdown.cancelled() => { tick.cancelled = true; return Ok(tick); }
313                requests = self.store.pending_child_joins_after(&tenant, tick.cursor.after.as_ref()) => requests?,
314            };
315            let exhausted = requests.len() < 16;
316            for request in requests {
317                let result = tokio::select! {
318                    biased;
319                    () = shutdown.cancelled() => { tick.cancelled = true; break; }
320                    result = self.publish_with_retry(&request) => result,
321                };
322                tick.cursor.after = Some(request.clone());
323                tick.items
324                    .push(ChildJoinPublicationItem { request, result });
325            }
326            if exhausted && !tick.cancelled {
327                tick.cursor.after = None;
328            }
329            Ok(tick)
330        })
331    }
332
333    async fn publish_with_retry(
334        &self,
335        request: &ChildRunJoinRequest,
336    ) -> Result<ChildJoinCommitOutcome, StoreError> {
337        let id = EventId::generate();
338        for attempt in 1..=self.options.maximum_mutation_attempts() {
339            let result = self.publish(request, id).await;
340            match result {
341                Err(error)
342                    if attempt < self.options.maximum_mutation_attempts()
343                        && (error.is_retryable()
344                            || matches!(error, StoreError::StaleJournalHead)) =>
345                {
346                    tokio::time::sleep(self.options.retry_delay(attempt)).await;
347                }
348                other => return other,
349            }
350        }
351        unreachable!("validated positive attempt count")
352    }
353
354    async fn publish(
355        &self,
356        request: &ChildRunJoinRequest,
357        id: EventId,
358    ) -> Result<ChildJoinCommitOutcome, StoreError> {
359        let activation = request.activation();
360        let run = self
361            .store
362            .load_run(activation.tenant_id(), activation.run_id())
363            .await?;
364        let append = JournalAppend::new(
365            JournalExpectation::exact(
366                run.journal_head()
367                    .cloned()
368                    .ok_or(StoreError::ChildJoinRejected)?,
369            ),
370            JournalEventIntent::control_plane(
371                activation.tenant_id().clone(),
372                activation.run_id(),
373                id,
374                payload(&self.schemas, request, true)?,
375            )
376            .map_err(|_| StoreError::ChildJoinRejected)?,
377        )
378        .map_err(|_| StoreError::ChildJoinRejected)?;
379        self.store.publish_child_join(request, append).await
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    #[test]
388    fn join_schema_is_offline_closed_and_independent_of_reconciliation_v1() {
389        let mut builder = JsonSchemaRegistryBuilder::default();
390        let schema = register_standard_child_join_event_schema(&mut builder).unwrap();
391        assert_eq!(
392            schema.digest().to_string(),
393            "sha256:d63a62eead850debf4a4ed79aae622bed6a89e20fe60ce5e146bb93f3c86a21e"
394        );
395        crate::register_standard_child_reconciliation_event_schema(&mut builder).unwrap();
396        let registry = builder.build().unwrap();
397        assert!(schema_available(&registry));
398        for operation in ["child_join_registered", "child_join_published"] {
399            let mut data = json!({"operation": operation, "request_digest": "a".repeat(64)});
400            registry
401                .validate_bounded(&schema, &BoundedJson::try_from_value(data.clone()).unwrap())
402                .unwrap();
403            data["child_output"] = json!({"private": true});
404            assert!(
405                registry
406                    .validate_bounded(&schema, &BoundedJson::try_from_value(data).unwrap())
407                    .is_err()
408            );
409        }
410        for data in [
411            json!({"operation":"child_run_settled", "request_digest":"a".repeat(64)}),
412            json!({"operation":"child_join_published", "request_digest":"not-a-digest"}),
413        ] {
414            assert!(
415                registry
416                    .validate_bounded(&schema, &BoundedJson::try_from_value(data).unwrap())
417                    .is_err()
418            );
419        }
420    }
421}