Skip to main content

stateknot_runtime/
registry.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Frozen graph, reducer, and node-executor bindings.
5
6use std::{collections::HashMap, fmt, sync::Arc};
7
8use stateknot_core::{
9    BoxFuture, BudgetUsage, CancellationSignal, Checkpoint, ChildRunPolicyError, CompiledGraph,
10    Failure, GraphReducer, GraphReducerReference, GraphReference, NodeAttemptStartHead,
11    NodeControl, NodeId, NodeInvocationBindings, NodeStateChange, RetryAdvice,
12};
13use thiserror::Error;
14
15use crate::{GraphChildJoin, JsonSchemaRegistry};
16
17/// Exact, already-started execution context passed to one graph node.
18///
19/// Construction proves that the durable attempt and immutable state snapshot
20/// describe the same logical activation. The runtime creates this only after a
21/// node-attempt start has committed. Node code receives no storage transaction
22/// or mutable checkpoint handle.
23#[derive(Clone)]
24pub struct GraphNodeContext {
25    attempt: NodeAttemptStartHead,
26    checkpoint: Arc<Checkpoint>,
27    cancellation: CancellationSignal,
28    child_join: Option<Arc<GraphChildJoin>>,
29}
30
31impl GraphNodeContext {
32    /// Binds one committed attempt to its exact immutable checkpoint snapshot.
33    ///
34    /// # Errors
35    ///
36    /// Returns [`GraphNodeContextError`] if the attempt names another base
37    /// checkpoint, tenant, or run.
38    pub fn new(
39        attempt: NodeAttemptStartHead,
40        checkpoint: Arc<Checkpoint>,
41        cancellation: CancellationSignal,
42    ) -> Result<Self, GraphNodeContextError> {
43        let activation = attempt.activation();
44        if activation.tenant_id() != checkpoint.tenant_id() {
45            return Err(GraphNodeContextError::TenantMismatch);
46        }
47        if activation.run_id() != checkpoint.run_id() {
48            return Err(GraphNodeContextError::RunMismatch);
49        }
50        if activation.base_checkpoint() != &checkpoint.head() {
51            return Err(GraphNodeContextError::CheckpointMismatch);
52        }
53        Ok(Self {
54            attempt,
55            checkpoint,
56            cancellation,
57            child_join: None,
58        })
59    }
60
61    /// Returns the durable physical attempt proof.
62    #[must_use]
63    pub const fn attempt(&self) -> &NodeAttemptStartHead {
64        &self.attempt
65    }
66
67    /// Returns the exact immutable state and ready-set snapshot.
68    #[must_use]
69    pub fn checkpoint(&self) -> &Checkpoint {
70        &self.checkpoint
71    }
72
73    /// Returns the cooperative stop signal owned by the driver.
74    #[must_use]
75    pub const fn cancellation(&self) -> &CancellationSignal {
76        &self.cancellation
77    }
78
79    /// Published, verified children on a resumed activation. Reading does not
80    /// consume the Join; the driver binds it to the eventual successful result.
81    #[must_use]
82    pub fn child_join(&self) -> Option<&GraphChildJoin> {
83        self.child_join.as_deref()
84    }
85
86    pub(crate) fn with_child_join(mut self, join: Arc<GraphChildJoin>) -> Self {
87        self.child_join = Some(join);
88        self
89    }
90}
91
92impl fmt::Debug for GraphNodeContext {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        formatter
95            .debug_struct("GraphNodeContext")
96            .field("attempt", &self.attempt)
97            .field("checkpoint", &self.checkpoint.head())
98            .field("cancellation", &self.cancellation)
99            .finish_non_exhaustive()
100    }
101}
102
103/// Invalid durable attempt/checkpoint binding for node execution.
104#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
105#[non_exhaustive]
106pub enum GraphNodeContextError {
107    /// Attempt and checkpoint crossed tenant isolation.
108    #[error("node execution context crosses a tenant boundary")]
109    TenantMismatch,
110    /// Attempt and checkpoint named different runs.
111    #[error("node execution context crosses a run boundary")]
112    RunMismatch,
113    /// Attempt activation did not derive from the supplied checkpoint.
114    #[error("node execution attempt does not belong to the supplied checkpoint")]
115    CheckpointMismatch,
116}
117
118/// A completed semantic result or a dedicated durable child suspension.
119///
120/// The durable driver rebinds these fields to the exact context activation by
121/// constructing [`stateknot_core::PendingNodeResultIntent`]. Invocation
122/// bindings are therefore revalidated before any success can commit.
123#[derive(Clone, Debug)]
124// Keep the pre-existing completion payload inline on the ordinary hot path;
125// the less frequent suspension request is boxed instead.
126#[allow(clippy::large_enum_variant)]
127pub enum GraphNodeExecution {
128    /// Complete this physical attempt; normal control and accounting apply.
129    Completed {
130        /// Typed state contribution.
131        state_change: NodeStateChange,
132        /// Closed graph control outcome.
133        control: NodeControl,
134        /// Exact committed external invocation references.
135        bindings: NodeInvocationBindings,
136        /// Normalized usage for this physical attempt.
137        usage: BudgetUsage,
138    },
139    /// Seal all admitted children and release the lease without completing the
140    /// node. This carries no invented control, result, failure, or usage.
141    ChildJoin(Box<stateknot_core::ChildRunJoinRequest>),
142}
143
144impl GraphNodeExecution {
145    /// Constructs one bounded semantic node result and its attempt usage.
146    #[must_use]
147    pub const fn new(
148        state_change: NodeStateChange,
149        control: NodeControl,
150        bindings: NodeInvocationBindings,
151        usage: BudgetUsage,
152    ) -> Self {
153        Self::Completed {
154            state_change,
155            control,
156            bindings,
157            usage,
158        }
159    }
160
161    /// Requests suspension before node completion. On recovery, inspect
162    /// `context.child_join()` and complete instead of registering again.
163    #[must_use]
164    pub fn child_join(request: stateknot_core::ChildRunJoinRequest) -> Self {
165        Self::ChildJoin(Box::new(request))
166    }
167}
168
169/// Public-safe failure of one graph-node attempt before journal causation.
170///
171/// Node code cannot know the completion event ID chosen by the durable driver,
172/// so it must return an uncaused failure. The driver attaches the exact event
173/// immediately before the atomic completion append. `ReconcileFirst` is also
174/// rejected because node side effects must live in the separate invocation
175/// ledgers, whose reconciliation is not a node-attempt retry decision.
176#[derive(Clone, Debug)]
177pub struct GraphNodeExecutionError {
178    failure: Failure,
179    usage: BudgetUsage,
180}
181
182impl GraphNodeExecutionError {
183    /// Constructs a persistence-safe node failure.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`GraphNodeExecutionErrorBuildError`] for pre-attached durable
188    /// causation or reconcile-first retry advice.
189    pub fn new(
190        failure: Failure,
191        usage: BudgetUsage,
192    ) -> Result<Self, GraphNodeExecutionErrorBuildError> {
193        if failure.caused_by_event_id().is_some() {
194            return Err(GraphNodeExecutionErrorBuildError::CausationAlreadyAttached);
195        }
196        if failure.retry_advice() == RetryAdvice::ReconcileFirst {
197            return Err(GraphNodeExecutionErrorBuildError::ReconciliationNotAllowed);
198        }
199        Ok(Self { failure, usage })
200    }
201
202    /// Returns public-safe failure evidence.
203    #[must_use]
204    pub const fn failure(&self) -> &Failure {
205        &self.failure
206    }
207
208    /// Returns normalized usage observed before failure.
209    #[must_use]
210    pub const fn usage(&self) -> &BudgetUsage {
211        &self.usage
212    }
213
214    /// Consumes the error into failure and usage components.
215    #[must_use]
216    pub fn into_parts(self) -> (Failure, BudgetUsage) {
217        (self.failure, self.usage)
218    }
219}
220
221/// Invalid node-execution failure returned before durable completion.
222#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
223#[non_exhaustive]
224pub enum GraphNodeExecutionErrorBuildError {
225    /// Only the driver may attach the exact completion event.
226    #[error("node failure already contains durable event causation")]
227    CausationAlreadyAttached,
228    /// Invocation ledgers, not node attempts, reconcile uncertain side effects.
229    #[error("node failure cannot request reconcile-first recovery")]
230    ReconciliationNotAllowed,
231}
232
233/// Trusted scheduling contract for one executable graph node.
234///
235/// The durable driver cannot inspect arbitrary node code, so concurrent
236/// eligibility is an explicit startup-time assertion made by the executable
237/// binding. The conservative default preserves exclusive execution.
238#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
239#[non_exhaustive]
240pub enum GraphNodeScheduling {
241    /// Run this node alone within its run.
242    #[default]
243    Exclusive,
244    /// The node may overlap journal-isolated siblings from the same checkpoint.
245    ///
246    /// A journal-isolated executor must not append run-scoped journal or
247    /// invocation-ledger records from `execute`, and its semantic result must
248    /// not depend on sibling start/completion timing. External work that needs
249    /// durable invocation evidence must use a purpose-built ordered batch
250    /// coordinator instead of selecting this mode.
251    JournalIsolated,
252}
253
254/// Object-safe executable implementation of one exact graph node.
255pub trait GraphNodeExecutor: Send + Sync + 'static {
256    /// Returns the whole immutable graph definition this code was built for.
257    fn graph(&self) -> &GraphReference;
258
259    /// Returns the stable compiled node identity implemented by this code.
260    fn node_id(&self) -> &NodeId;
261
262    /// Declares whether this trusted binding may overlap ready siblings.
263    ///
264    /// Existing implementations remain exclusive. Returning
265    /// [`GraphNodeScheduling::JournalIsolated`] is a trusted production
266    /// contract, not a performance hint.
267    fn scheduling(&self) -> GraphNodeScheduling {
268        GraphNodeScheduling::Exclusive
269    }
270
271    /// Opts into child suspension/resumption. The registry requires declared
272    /// child slots, exclusive scheduling and the embedded child Join schema.
273    fn supports_child_join(&self) -> bool {
274        false
275    }
276
277    /// Executes exactly one already-durably-started physical attempt.
278    fn execute(
279        &self,
280        context: GraphNodeContext,
281    ) -> BoxFuture<'_, Result<GraphNodeExecution, GraphNodeExecutionError>>;
282}
283
284/// One declarative graph with all executable bindings frozen and verified.
285#[derive(Clone)]
286pub struct ExecutableGraph {
287    graph: Arc<CompiledGraph>,
288    schemas: JsonSchemaRegistry,
289    reducer: Arc<dyn GraphReducer>,
290    nodes: Arc<HashMap<NodeId, Arc<dyn GraphNodeExecutor>>>,
291}
292
293impl ExecutableGraph {
294    /// Returns the exact immutable declarative graph.
295    #[must_use]
296    pub fn graph(&self) -> &CompiledGraph {
297        &self.graph
298    }
299
300    /// Returns the frozen offline schema registry.
301    #[must_use]
302    pub const fn schemas(&self) -> &JsonSchemaRegistry {
303        &self.schemas
304    }
305
306    /// Returns the exactly pinned pure reducer.
307    #[must_use]
308    pub fn reducer(&self) -> &(dyn GraphReducer + 'static) {
309        self.reducer.as_ref()
310    }
311
312    /// Resolves one exact compiled node implementation.
313    #[must_use]
314    pub fn node(&self, node_id: &NodeId) -> Option<&(dyn GraphNodeExecutor + 'static)> {
315        self.nodes.get(node_id).map(Arc::as_ref)
316    }
317
318    /// Resolves a shared executor handle suitable for an owned async task.
319    #[must_use]
320    pub fn node_executor(&self, node_id: &NodeId) -> Option<Arc<dyn GraphNodeExecutor>> {
321        self.nodes.get(node_id).cloned()
322    }
323
324    /// Returns the number of executable node bindings.
325    #[must_use]
326    pub fn node_count(&self) -> usize {
327        self.nodes.len()
328    }
329}
330
331impl fmt::Debug for ExecutableGraph {
332    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
333        formatter
334            .debug_struct("ExecutableGraph")
335            .field("graph", &self.graph.reference())
336            .field("reducer", self.reducer.reference())
337            .field("nodes", &self.nodes.len())
338            .finish_non_exhaustive()
339    }
340}
341
342/// Startup-only builder for a closed executable deployment snapshot.
343pub struct ExecutableGraphRegistryBuilder {
344    schemas: JsonSchemaRegistry,
345    graphs: HashMap<GraphReference, Arc<CompiledGraph>>,
346    graph_identities: HashMap<stateknot_core::CapabilityIdentity, GraphReference>,
347    reducers: HashMap<GraphReducerReference, Arc<dyn GraphReducer>>,
348    reducer_identities: HashMap<stateknot_core::CapabilityIdentity, GraphReducerReference>,
349    nodes: HashMap<(GraphReference, NodeId), Arc<dyn GraphNodeExecutor>>,
350}
351
352impl ExecutableGraphRegistryBuilder {
353    /// Maximum graph definitions in one process snapshot.
354    pub const MAX_GRAPHS: usize = 1024;
355    /// Maximum reducer revisions in one process snapshot.
356    pub const MAX_REDUCERS: usize = 1024;
357    /// Maximum graph-node implementations in one process snapshot.
358    pub const MAX_NODE_EXECUTORS: usize = 65_536;
359
360    /// Creates an empty executable binding builder over a frozen schema set.
361    #[must_use]
362    pub fn new(schemas: JsonSchemaRegistry) -> Self {
363        Self {
364            schemas,
365            graphs: HashMap::new(),
366            graph_identities: HashMap::new(),
367            reducers: HashMap::new(),
368            reducer_identities: HashMap::new(),
369            nodes: HashMap::new(),
370        }
371    }
372
373    /// Registers one canonical declarative graph revision.
374    ///
375    /// # Errors
376    ///
377    /// Rejects ceiling exhaustion, an exact duplicate, or reuse of the same
378    /// owner/name/version identity with different immutable bytes.
379    pub fn register_graph(
380        &mut self,
381        graph: CompiledGraph,
382    ) -> Result<(), ExecutableGraphRegistryError> {
383        if self.graphs.len() == Self::MAX_GRAPHS {
384            return Err(ExecutableGraphRegistryError::TooManyGraphs {
385                maximum: Self::MAX_GRAPHS,
386                actual: Self::MAX_GRAPHS + 1,
387            });
388        }
389        let reference = graph.reference();
390        if self.graphs.contains_key(&reference) {
391            return Err(ExecutableGraphRegistryError::DuplicateGraph {
392                reference: Box::new(reference),
393            });
394        }
395        if let Some(existing) = self.graph_identities.get(graph.identity()) {
396            return Err(ExecutableGraphRegistryError::GraphIdentityConflict {
397                existing: Box::new(existing.clone()),
398                rejected: Box::new(reference),
399            });
400        }
401        self.graph_identities
402            .insert(graph.identity().clone(), reference.clone());
403        self.graphs.insert(reference, Arc::new(graph));
404        Ok(())
405    }
406
407    /// Registers one exactly referenced pure reducer implementation.
408    ///
409    /// # Errors
410    ///
411    /// Rejects ceiling exhaustion, duplicate references, or identity reuse
412    /// with another digest.
413    pub fn register_reducer(
414        &mut self,
415        reducer: Arc<dyn GraphReducer>,
416    ) -> Result<(), ExecutableGraphRegistryError> {
417        if self.reducers.len() == Self::MAX_REDUCERS {
418            return Err(ExecutableGraphRegistryError::TooManyReducers {
419                maximum: Self::MAX_REDUCERS,
420                actual: Self::MAX_REDUCERS + 1,
421            });
422        }
423        let reference = reducer.reference().clone();
424        if self.reducers.contains_key(&reference) {
425            return Err(ExecutableGraphRegistryError::DuplicateReducer {
426                reference: Box::new(reference),
427            });
428        }
429        if let Some(existing) = self.reducer_identities.get(reference.identity()) {
430            return Err(ExecutableGraphRegistryError::ReducerIdentityConflict {
431                existing: Box::new(existing.clone()),
432                rejected: Box::new(reference),
433            });
434        }
435        self.reducer_identities
436            .insert(reference.identity().clone(), reference.clone());
437        self.reducers.insert(reference, reducer);
438        Ok(())
439    }
440
441    /// Registers one node implementation bound to a whole graph digest.
442    ///
443    /// # Errors
444    ///
445    /// Rejects ceiling exhaustion or a repeated `(graph, node)` binding.
446    pub fn register_node(
447        &mut self,
448        executor: Arc<dyn GraphNodeExecutor>,
449    ) -> Result<(), ExecutableGraphRegistryError> {
450        if self.nodes.len() == Self::MAX_NODE_EXECUTORS {
451            return Err(ExecutableGraphRegistryError::TooManyNodeExecutors {
452                maximum: Self::MAX_NODE_EXECUTORS,
453                actual: Self::MAX_NODE_EXECUTORS + 1,
454            });
455        }
456        let key = (executor.graph().clone(), executor.node_id().clone());
457        if self.nodes.contains_key(&key) {
458            return Err(ExecutableGraphRegistryError::DuplicateNodeExecutor {
459                graph: Box::new(key.0),
460                node_id: key.1,
461            });
462        }
463        self.nodes.insert(key, executor);
464        Ok(())
465    }
466
467    /// Verifies complete graph/schema/reducer/node closure and freezes lookup.
468    ///
469    /// # Errors
470    ///
471    /// Rejects an empty deployment; absent graph schemas, reducers, or nodes;
472    /// node code not declared by its graph; and orphan executable code that no
473    /// registered graph can ever resolve.
474    pub fn build(self) -> Result<ExecutableGraphRegistry, ExecutableGraphRegistryError> {
475        if self.graphs.is_empty() {
476            return Err(ExecutableGraphRegistryError::EmptyGraphs);
477        }
478
479        for (reference, graph) in &self.graphs {
480            if let Some(policy) = graph.child_runs() {
481                for declaration in policy.declarations() {
482                    let target = self.graphs.get(declaration.graph()).ok_or_else(|| {
483                        ExecutableGraphRegistryError::MissingChildGraph {
484                            parent: Box::new(reference.clone()),
485                            child: Box::new(declaration.graph().clone()),
486                        }
487                    })?;
488                    declaration
489                        .validate_target(target, policy.limits())
490                        .map_err(|source| ExecutableGraphRegistryError::ChildPolicy {
491                            graph: Box::new(reference.clone()),
492                            source,
493                        })?;
494                }
495            }
496        }
497
498        let mut executable = HashMap::with_capacity(self.graphs.len());
499        let mut used_reducers = std::collections::HashSet::new();
500        let mut used_nodes = std::collections::HashSet::new();
501        for (reference, graph) in &self.graphs {
502            for schema in [
503                graph.input_schema(),
504                graph.state_schema(),
505                graph.update_schema(),
506                graph.output_schema(),
507            ] {
508                if !self.schemas.contains(schema) {
509                    return Err(ExecutableGraphRegistryError::MissingSchema {
510                        graph: Box::new(reference.clone()),
511                        schema: Box::new(schema.clone()),
512                    });
513                }
514            }
515            let reducer = self.reducers.get(graph.reducer()).cloned().ok_or_else(|| {
516                ExecutableGraphRegistryError::MissingReducer {
517                    graph: Box::new(reference.clone()),
518                    reducer: Box::new(graph.reducer().clone()),
519                }
520            })?;
521            used_reducers.insert(graph.reducer().clone());
522
523            let mut graph_nodes = HashMap::with_capacity(graph.nodes().len());
524            for node in graph.nodes() {
525                let key = (reference.clone(), node.node_id().clone());
526                let executor = self.nodes.get(&key).cloned().ok_or_else(|| {
527                    ExecutableGraphRegistryError::MissingNodeExecutor {
528                        graph: Box::new(reference.clone()),
529                        node_id: node.node_id().clone(),
530                    }
531                })?;
532                let declares_children = graph.child_runs().is_some_and(|policy| {
533                    policy
534                        .declarations()
535                        .iter()
536                        .any(|d| d.node_id() == node.node_id())
537                });
538                if (declares_children && executor.scheduling() != GraphNodeScheduling::Exclusive)
539                    || (executor.supports_child_join()
540                        && (!declares_children
541                            || !crate::child_join::schema_available(&self.schemas)))
542                {
543                    return Err(ExecutableGraphRegistryError::InvalidChildJoinExecutor);
544                }
545                used_nodes.insert(key);
546                graph_nodes.insert(node.node_id().clone(), executor);
547            }
548            executable.insert(
549                reference.clone(),
550                ExecutableGraph {
551                    graph: Arc::clone(graph),
552                    schemas: self.schemas.clone(),
553                    reducer,
554                    nodes: Arc::new(graph_nodes),
555                },
556            );
557        }
558
559        if let Some(reference) = self
560            .reducers
561            .keys()
562            .find(|reference| !used_reducers.contains(*reference))
563        {
564            return Err(ExecutableGraphRegistryError::OrphanReducer {
565                reducer: Box::new(reference.clone()),
566            });
567        }
568        if let Some((graph, node_id)) = self.nodes.keys().find(|key| !used_nodes.contains(*key)) {
569            return Err(ExecutableGraphRegistryError::OrphanNodeExecutor {
570                graph: Box::new(graph.clone()),
571                node_id: node_id.clone(),
572            });
573        }
574
575        Ok(ExecutableGraphRegistry {
576            schemas: self.schemas,
577            graphs: Arc::new(executable),
578        })
579    }
580}
581
582impl fmt::Debug for ExecutableGraphRegistryBuilder {
583    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
584        formatter
585            .debug_struct("ExecutableGraphRegistryBuilder")
586            .field("schemas", &self.schemas)
587            .field("graphs", &self.graphs.len())
588            .field("reducers", &self.reducers.len())
589            .field("nodes", &self.nodes.len())
590            .finish_non_exhaustive()
591    }
592}
593
594/// Immutable deployment snapshot resolved only by complete graph reference.
595#[derive(Clone)]
596pub struct ExecutableGraphRegistry {
597    schemas: JsonSchemaRegistry,
598    graphs: Arc<HashMap<GraphReference, ExecutableGraph>>,
599}
600
601impl ExecutableGraphRegistry {
602    pub(crate) fn has_child_graphs(&self) -> bool {
603        self.graphs
604            .values()
605            .any(|entry| entry.graph().child_runs().is_some())
606    }
607    /// Resolves an exact graph descriptor and all local executable bindings.
608    #[must_use]
609    pub fn resolve(&self, reference: &GraphReference) -> Option<&ExecutableGraph> {
610        self.graphs.get(reference)
611    }
612
613    /// Returns the shared frozen schema registry.
614    #[must_use]
615    pub const fn schemas(&self) -> &JsonSchemaRegistry {
616        &self.schemas
617    }
618
619    /// Returns the number of executable graph revisions.
620    #[must_use]
621    pub fn len(&self) -> usize {
622        self.graphs.len()
623    }
624
625    /// Returns whether no executable graph was installed.
626    #[must_use]
627    pub fn is_empty(&self) -> bool {
628        self.graphs.is_empty()
629    }
630}
631
632impl fmt::Debug for ExecutableGraphRegistry {
633    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
634        formatter
635            .debug_struct("ExecutableGraphRegistry")
636            .field("schemas", &self.schemas.len())
637            .field("graphs", &self.graphs.len())
638            .finish_non_exhaustive()
639    }
640}
641
642/// Startup-time failure while freezing executable graph bindings.
643#[derive(Clone, Debug, Eq, Error, PartialEq)]
644#[non_exhaustive]
645pub enum ExecutableGraphRegistryError {
646    /// Child executors require exclusive scheduling; Join additionally requires
647    /// declared slots and the exact embedded audit schema before any dispatch.
648    #[error(
649        "child Join executor requires declared slots, exclusive scheduling and its audit schema"
650    )]
651    InvalidChildJoinExecutor,
652    /// A declared child target has no exact graph in this frozen deployment.
653    #[error("executable registry lacks a declared child graph")]
654    MissingChildGraph {
655        /// Declaring parent graph.
656        parent: Box<GraphReference>,
657        /// Missing exact child graph.
658        child: Box<GraphReference>,
659    },
660    /// A declared target has incompatible schema pins or remaining depth.
661    #[error("executable registry child policy validation failed: {source}")]
662    ChildPolicy {
663        /// Declaring parent graph.
664        graph: Box<GraphReference>,
665        /// Closed, public-safe reason.
666        #[source]
667        source: ChildRunPolicyError,
668    },
669    /// No executable graph could be resolved.
670    #[error("executable graph registry must contain at least one graph")]
671    EmptyGraphs,
672    /// Graph count exceeded the immutable deployment ceiling.
673    #[error("executable registry contains {actual} graphs; maximum is {maximum}")]
674    TooManyGraphs {
675        /// Immutable maximum.
676        maximum: usize,
677        /// First rejected count.
678        actual: usize,
679    },
680    /// Reducer count exceeded the immutable deployment ceiling.
681    #[error("executable registry contains {actual} reducers; maximum is {maximum}")]
682    TooManyReducers {
683        /// Immutable maximum.
684        maximum: usize,
685        /// First rejected count.
686        actual: usize,
687    },
688    /// Node implementation count exceeded the deployment ceiling.
689    #[error("executable registry contains {actual} nodes; maximum is {maximum}")]
690    TooManyNodeExecutors {
691        /// Immutable maximum.
692        maximum: usize,
693        /// First rejected count.
694        actual: usize,
695    },
696    /// The exact canonical graph was registered twice.
697    #[error("compiled graph reference was registered more than once")]
698    DuplicateGraph {
699        /// Repeated graph reference.
700        reference: Box<GraphReference>,
701    },
702    /// One graph identity attempted to carry different canonical bytes.
703    #[error("graph owner/name/version identity was reused with another definition")]
704    GraphIdentityConflict {
705        /// First graph reference.
706        existing: Box<GraphReference>,
707        /// Rejected graph reference.
708        rejected: Box<GraphReference>,
709    },
710    /// The exact reducer revision was registered twice.
711    #[error("graph reducer reference was registered more than once")]
712    DuplicateReducer {
713        /// Repeated reducer reference.
714        reference: Box<GraphReducerReference>,
715    },
716    /// One reducer identity attempted to carry different implementation bytes.
717    #[error("reducer owner/name/version identity was reused with another definition")]
718    ReducerIdentityConflict {
719        /// First reducer reference.
720        existing: Box<GraphReducerReference>,
721        /// Rejected reducer reference.
722        rejected: Box<GraphReducerReference>,
723    },
724    /// One whole-graph node binding was registered twice.
725    #[error("graph node executor was registered more than once")]
726    DuplicateNodeExecutor {
727        /// Exact graph definition.
728        graph: Box<GraphReference>,
729        /// Repeated node identity.
730        node_id: NodeId,
731    },
732    /// A graph referenced a schema absent from the frozen offline set.
733    #[error("compiled graph references an unavailable schema")]
734    MissingSchema {
735        /// Graph with the incomplete dependency closure.
736        graph: Box<GraphReference>,
737        /// Missing schema reference.
738        schema: Box<stateknot_core::SchemaReference>,
739    },
740    /// A graph's exactly pinned reducer was absent.
741    #[error("compiled graph references an unavailable reducer")]
742    MissingReducer {
743        /// Graph with the incomplete dependency closure.
744        graph: Box<GraphReference>,
745        /// Missing reducer reference.
746        reducer: Box<GraphReducerReference>,
747    },
748    /// One compiled node had no exact implementation.
749    #[error("compiled graph node has no executable implementation")]
750    MissingNodeExecutor {
751        /// Graph with the incomplete dependency closure.
752        graph: Box<GraphReference>,
753        /// Missing node implementation.
754        node_id: NodeId,
755    },
756    /// Installed reducer code was unreachable from every registered graph.
757    #[error("registered reducer is not referenced by any installed graph")]
758    OrphanReducer {
759        /// Unused reducer implementation.
760        reducer: Box<GraphReducerReference>,
761    },
762    /// Installed node code did not belong to a declared graph node.
763    #[error("registered node executor is not declared by an installed graph")]
764    OrphanNodeExecutor {
765        /// Claimed graph definition.
766        graph: Box<GraphReference>,
767        /// Undeclared or unavailable node.
768        node_id: NodeId,
769    },
770}
771
772#[cfg(test)]
773#[path = "registry_child_tests.rs"]
774mod child_tests;
775
776#[cfg(test)]
777mod tests {
778    use serde_json::{Value, json};
779    use stateknot_core::{
780        BoundedJson, CapabilityIdentity, CapabilityName, CapabilityReference, GraphExecutionLimits,
781        GraphNode, GraphReducerError, GraphReducerInput, GraphRoutes, IssuerId, PrincipalIdentity,
782        ReadyNodes, SchemaId, SchemaReference, SubjectId, Superstep, Version,
783    };
784
785    use super::*;
786    use crate::JsonSchemaRegistryBuilder;
787
788    const DRAFT: &str = "https://json-schema.org/draft/2020-12/schema";
789
790    fn identity(name: &str) -> CapabilityIdentity {
791        CapabilityIdentity::new(
792            PrincipalIdentity::new(
793                IssuerId::new("https://issuer.example.com").unwrap(),
794                SubjectId::new("runtime-tests").unwrap(),
795            ),
796            CapabilityReference::new(CapabilityName::new(name).unwrap(), Version::new(1, 0, 0)),
797        )
798    }
799
800    fn schema_reference(id: &str, document: &Value) -> SchemaReference {
801        SchemaReference::new(
802            id.parse::<SchemaId>().unwrap(),
803            Version::new(1, 0, 0),
804            stateknot_core::Digest::sha256(serde_json_canonicalizer::to_vec(document).unwrap()),
805        )
806    }
807
808    fn schemas() -> (JsonSchemaRegistry, SchemaReference) {
809        let id = "https://schemas.example.com/graph-value/1.0.0";
810        let document = json!({
811            "$schema": DRAFT,
812            "$id": id,
813            "type": "object",
814            "additionalProperties": true
815        });
816        let reference = schema_reference(id, &document);
817        let mut builder = JsonSchemaRegistryBuilder::default();
818        builder.register(reference.clone(), document).unwrap();
819        (builder.build().unwrap(), reference)
820    }
821
822    fn graph(schema: &SchemaReference, reducer: GraphReducerReference) -> (CompiledGraph, NodeId) {
823        let node_id = NodeId::new("finish").unwrap();
824        let node = GraphNode::new(node_id.clone(), None, GraphRoutes::empty(), None, true).unwrap();
825        let graph = CompiledGraph::compile(
826            identity("graph"),
827            schema.clone(),
828            schema.clone(),
829            schema.clone(),
830            schema.clone(),
831            reducer,
832            ReadyNodes::try_new([node_id.clone()]).unwrap(),
833            [node],
834            GraphExecutionLimits::new(Superstep::new(32).unwrap(), 4).unwrap(),
835        )
836        .unwrap();
837        (graph, node_id)
838    }
839
840    struct Reducer {
841        reference: GraphReducerReference,
842    }
843
844    impl GraphReducer for Reducer {
845        fn reference(&self) -> &GraphReducerReference {
846            &self.reference
847        }
848
849        fn reduce(
850            &self,
851            state: &BoundedJson,
852            _: &[GraphReducerInput<'_>],
853        ) -> Result<BoundedJson, GraphReducerError> {
854            Ok(state.clone())
855        }
856    }
857
858    struct Executor {
859        graph: GraphReference,
860        node_id: NodeId,
861    }
862
863    impl GraphNodeExecutor for Executor {
864        fn graph(&self) -> &GraphReference {
865            &self.graph
866        }
867
868        fn node_id(&self) -> &NodeId {
869            &self.node_id
870        }
871
872        fn execute(
873            &self,
874            _: GraphNodeContext,
875        ) -> BoxFuture<'_, Result<GraphNodeExecution, GraphNodeExecutionError>> {
876            Box::pin(async { panic!("registry tests do not execute node code") })
877        }
878    }
879
880    #[test]
881    fn complete_registry_freezes_exact_graph_dependencies() {
882        let (schemas, schema) = schemas();
883        let reducer_reference =
884            GraphReducerReference::new(identity("reducer"), stateknot_core::Digest::sha256(b"v1"));
885        let reducer = Arc::new(Reducer {
886            reference: reducer_reference.clone(),
887        });
888        let (graph, node_id) = graph(&schema, reducer_reference.clone());
889        let graph_reference = graph.reference();
890        let executor: Arc<dyn GraphNodeExecutor> = Arc::new(Executor {
891            graph: graph_reference.clone(),
892            node_id: node_id.clone(),
893        });
894        let mut builder = ExecutableGraphRegistryBuilder::new(schemas);
895        builder.register_node(Arc::clone(&executor)).unwrap();
896        assert!(matches!(
897            builder.register_node(Arc::new(Executor {
898                graph: graph_reference.clone(),
899                node_id: node_id.clone(),
900            })),
901            Err(ExecutableGraphRegistryError::DuplicateNodeExecutor { .. })
902        ));
903        builder.register_reducer(reducer).unwrap();
904        builder.register_graph(graph).unwrap();
905
906        let registry = builder.build().unwrap();
907        let executable = registry.resolve(&graph_reference).unwrap();
908        assert_eq!(registry.len(), 1);
909        assert_eq!(executable.graph().reference(), graph_reference);
910        assert_eq!(executable.reducer().reference(), &reducer_reference);
911        assert_eq!(executable.node(&node_id).unwrap().node_id(), &node_id);
912        assert!(Arc::ptr_eq(
913            &executable.node_executor(&node_id).unwrap(),
914            &executor
915        ));
916    }
917
918    #[test]
919    fn build_rejects_missing_and_orphan_node_code() {
920        let (schemas, schema) = schemas();
921        let reducer_reference = GraphReducerReference::new(
922            identity("reducer"),
923            stateknot_core::Digest::sha256(b"reducer"),
924        );
925        let reducer = Arc::new(Reducer {
926            reference: reducer_reference.clone(),
927        });
928        let (graph, node_id) = graph(&schema, reducer_reference);
929        let graph_reference = graph.reference();
930        let mut missing = ExecutableGraphRegistryBuilder::new(schemas.clone());
931        missing.register_reducer(reducer.clone()).unwrap();
932        missing.register_graph(graph.clone()).unwrap();
933        assert!(matches!(
934            missing.build(),
935            Err(ExecutableGraphRegistryError::MissingNodeExecutor { .. })
936        ));
937
938        let mut orphan = ExecutableGraphRegistryBuilder::new(schemas);
939        orphan.register_reducer(reducer).unwrap();
940        orphan.register_graph(graph).unwrap();
941        orphan
942            .register_node(Arc::new(Executor {
943                graph: graph_reference.clone(),
944                node_id,
945            }))
946            .unwrap();
947        orphan
948            .register_node(Arc::new(Executor {
949                graph: graph_reference,
950                node_id: NodeId::new("undeclared").unwrap(),
951            }))
952            .unwrap();
953        assert!(matches!(
954            orphan.build(),
955            Err(ExecutableGraphRegistryError::OrphanNodeExecutor { .. })
956        ));
957    }
958}