stateknot-runtime 0.1.0-alpha.1

Executable registries and durable graph driving for StateKnot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
// Copyright 2026 StateKnot contributors
// SPDX-License-Identifier: Apache-2.0

//! Frozen graph, reducer, and node-executor bindings.

use std::{collections::HashMap, fmt, sync::Arc};

use stateknot_core::{
    BoxFuture, BudgetUsage, CancellationSignal, Checkpoint, ChildRunPolicyError, CompiledGraph,
    Failure, GraphReducer, GraphReducerReference, GraphReference, NodeAttemptStartHead,
    NodeControl, NodeId, NodeInvocationBindings, NodeStateChange, RetryAdvice,
};
use thiserror::Error;

use crate::{GraphChildJoin, JsonSchemaRegistry};

/// Exact, already-started execution context passed to one graph node.
///
/// Construction proves that the durable attempt and immutable state snapshot
/// describe the same logical activation. The runtime creates this only after a
/// node-attempt start has committed. Node code receives no storage transaction
/// or mutable checkpoint handle.
#[derive(Clone)]
pub struct GraphNodeContext {
    attempt: NodeAttemptStartHead,
    checkpoint: Arc<Checkpoint>,
    cancellation: CancellationSignal,
    child_join: Option<Arc<GraphChildJoin>>,
}

impl GraphNodeContext {
    /// Binds one committed attempt to its exact immutable checkpoint snapshot.
    ///
    /// # Errors
    ///
    /// Returns [`GraphNodeContextError`] if the attempt names another base
    /// checkpoint, tenant, or run.
    pub fn new(
        attempt: NodeAttemptStartHead,
        checkpoint: Arc<Checkpoint>,
        cancellation: CancellationSignal,
    ) -> Result<Self, GraphNodeContextError> {
        let activation = attempt.activation();
        if activation.tenant_id() != checkpoint.tenant_id() {
            return Err(GraphNodeContextError::TenantMismatch);
        }
        if activation.run_id() != checkpoint.run_id() {
            return Err(GraphNodeContextError::RunMismatch);
        }
        if activation.base_checkpoint() != &checkpoint.head() {
            return Err(GraphNodeContextError::CheckpointMismatch);
        }
        Ok(Self {
            attempt,
            checkpoint,
            cancellation,
            child_join: None,
        })
    }

    /// Returns the durable physical attempt proof.
    #[must_use]
    pub const fn attempt(&self) -> &NodeAttemptStartHead {
        &self.attempt
    }

    /// Returns the exact immutable state and ready-set snapshot.
    #[must_use]
    pub fn checkpoint(&self) -> &Checkpoint {
        &self.checkpoint
    }

    /// Returns the cooperative stop signal owned by the driver.
    #[must_use]
    pub const fn cancellation(&self) -> &CancellationSignal {
        &self.cancellation
    }

    /// Published, verified children on a resumed activation. Reading does not
    /// consume the Join; the driver binds it to the eventual successful result.
    #[must_use]
    pub fn child_join(&self) -> Option<&GraphChildJoin> {
        self.child_join.as_deref()
    }

    pub(crate) fn with_child_join(mut self, join: Arc<GraphChildJoin>) -> Self {
        self.child_join = Some(join);
        self
    }
}

impl fmt::Debug for GraphNodeContext {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GraphNodeContext")
            .field("attempt", &self.attempt)
            .field("checkpoint", &self.checkpoint.head())
            .field("cancellation", &self.cancellation)
            .finish_non_exhaustive()
    }
}

/// Invalid durable attempt/checkpoint binding for node execution.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum GraphNodeContextError {
    /// Attempt and checkpoint crossed tenant isolation.
    #[error("node execution context crosses a tenant boundary")]
    TenantMismatch,
    /// Attempt and checkpoint named different runs.
    #[error("node execution context crosses a run boundary")]
    RunMismatch,
    /// Attempt activation did not derive from the supplied checkpoint.
    #[error("node execution attempt does not belong to the supplied checkpoint")]
    CheckpointMismatch,
}

/// A completed semantic result or a dedicated durable child suspension.
///
/// The durable driver rebinds these fields to the exact context activation by
/// constructing [`stateknot_core::PendingNodeResultIntent`]. Invocation
/// bindings are therefore revalidated before any success can commit.
#[derive(Clone, Debug)]
// Keep the pre-existing completion payload inline on the ordinary hot path;
// the less frequent suspension request is boxed instead.
#[allow(clippy::large_enum_variant)]
pub enum GraphNodeExecution {
    /// Complete this physical attempt; normal control and accounting apply.
    Completed {
        /// Typed state contribution.
        state_change: NodeStateChange,
        /// Closed graph control outcome.
        control: NodeControl,
        /// Exact committed external invocation references.
        bindings: NodeInvocationBindings,
        /// Normalized usage for this physical attempt.
        usage: BudgetUsage,
    },
    /// Seal all admitted children and release the lease without completing the
    /// node. This carries no invented control, result, failure, or usage.
    ChildJoin(Box<stateknot_core::ChildRunJoinRequest>),
}

impl GraphNodeExecution {
    /// Constructs one bounded semantic node result and its attempt usage.
    #[must_use]
    pub const fn new(
        state_change: NodeStateChange,
        control: NodeControl,
        bindings: NodeInvocationBindings,
        usage: BudgetUsage,
    ) -> Self {
        Self::Completed {
            state_change,
            control,
            bindings,
            usage,
        }
    }

    /// Requests suspension before node completion. On recovery, inspect
    /// `context.child_join()` and complete instead of registering again.
    #[must_use]
    pub fn child_join(request: stateknot_core::ChildRunJoinRequest) -> Self {
        Self::ChildJoin(Box::new(request))
    }
}

/// Public-safe failure of one graph-node attempt before journal causation.
///
/// Node code cannot know the completion event ID chosen by the durable driver,
/// so it must return an uncaused failure. The driver attaches the exact event
/// immediately before the atomic completion append. `ReconcileFirst` is also
/// rejected because node side effects must live in the separate invocation
/// ledgers, whose reconciliation is not a node-attempt retry decision.
#[derive(Clone, Debug)]
pub struct GraphNodeExecutionError {
    failure: Failure,
    usage: BudgetUsage,
}

impl GraphNodeExecutionError {
    /// Constructs a persistence-safe node failure.
    ///
    /// # Errors
    ///
    /// Returns [`GraphNodeExecutionErrorBuildError`] for pre-attached durable
    /// causation or reconcile-first retry advice.
    pub fn new(
        failure: Failure,
        usage: BudgetUsage,
    ) -> Result<Self, GraphNodeExecutionErrorBuildError> {
        if failure.caused_by_event_id().is_some() {
            return Err(GraphNodeExecutionErrorBuildError::CausationAlreadyAttached);
        }
        if failure.retry_advice() == RetryAdvice::ReconcileFirst {
            return Err(GraphNodeExecutionErrorBuildError::ReconciliationNotAllowed);
        }
        Ok(Self { failure, usage })
    }

    /// Returns public-safe failure evidence.
    #[must_use]
    pub const fn failure(&self) -> &Failure {
        &self.failure
    }

    /// Returns normalized usage observed before failure.
    #[must_use]
    pub const fn usage(&self) -> &BudgetUsage {
        &self.usage
    }

    /// Consumes the error into failure and usage components.
    #[must_use]
    pub fn into_parts(self) -> (Failure, BudgetUsage) {
        (self.failure, self.usage)
    }
}

/// Invalid node-execution failure returned before durable completion.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum GraphNodeExecutionErrorBuildError {
    /// Only the driver may attach the exact completion event.
    #[error("node failure already contains durable event causation")]
    CausationAlreadyAttached,
    /// Invocation ledgers, not node attempts, reconcile uncertain side effects.
    #[error("node failure cannot request reconcile-first recovery")]
    ReconciliationNotAllowed,
}

/// Trusted scheduling contract for one executable graph node.
///
/// The durable driver cannot inspect arbitrary node code, so concurrent
/// eligibility is an explicit startup-time assertion made by the executable
/// binding. The conservative default preserves exclusive execution.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum GraphNodeScheduling {
    /// Run this node alone within its run.
    #[default]
    Exclusive,
    /// The node may overlap journal-isolated siblings from the same checkpoint.
    ///
    /// A journal-isolated executor must not append run-scoped journal or
    /// invocation-ledger records from `execute`, and its semantic result must
    /// not depend on sibling start/completion timing. External work that needs
    /// durable invocation evidence must use a purpose-built ordered batch
    /// coordinator instead of selecting this mode.
    JournalIsolated,
}

/// Object-safe executable implementation of one exact graph node.
pub trait GraphNodeExecutor: Send + Sync + 'static {
    /// Returns the whole immutable graph definition this code was built for.
    fn graph(&self) -> &GraphReference;

    /// Returns the stable compiled node identity implemented by this code.
    fn node_id(&self) -> &NodeId;

    /// Declares whether this trusted binding may overlap ready siblings.
    ///
    /// Existing implementations remain exclusive. Returning
    /// [`GraphNodeScheduling::JournalIsolated`] is a trusted production
    /// contract, not a performance hint.
    fn scheduling(&self) -> GraphNodeScheduling {
        GraphNodeScheduling::Exclusive
    }

    /// Opts into child suspension/resumption. The registry requires declared
    /// child slots, exclusive scheduling and the embedded child Join schema.
    fn supports_child_join(&self) -> bool {
        false
    }

    /// Executes exactly one already-durably-started physical attempt.
    fn execute(
        &self,
        context: GraphNodeContext,
    ) -> BoxFuture<'_, Result<GraphNodeExecution, GraphNodeExecutionError>>;
}

/// One declarative graph with all executable bindings frozen and verified.
#[derive(Clone)]
pub struct ExecutableGraph {
    graph: Arc<CompiledGraph>,
    schemas: JsonSchemaRegistry,
    reducer: Arc<dyn GraphReducer>,
    nodes: Arc<HashMap<NodeId, Arc<dyn GraphNodeExecutor>>>,
}

impl ExecutableGraph {
    /// Returns the exact immutable declarative graph.
    #[must_use]
    pub fn graph(&self) -> &CompiledGraph {
        &self.graph
    }

    /// Returns the frozen offline schema registry.
    #[must_use]
    pub const fn schemas(&self) -> &JsonSchemaRegistry {
        &self.schemas
    }

    /// Returns the exactly pinned pure reducer.
    #[must_use]
    pub fn reducer(&self) -> &(dyn GraphReducer + 'static) {
        self.reducer.as_ref()
    }

    /// Resolves one exact compiled node implementation.
    #[must_use]
    pub fn node(&self, node_id: &NodeId) -> Option<&(dyn GraphNodeExecutor + 'static)> {
        self.nodes.get(node_id).map(Arc::as_ref)
    }

    /// Resolves a shared executor handle suitable for an owned async task.
    #[must_use]
    pub fn node_executor(&self, node_id: &NodeId) -> Option<Arc<dyn GraphNodeExecutor>> {
        self.nodes.get(node_id).cloned()
    }

    /// Returns the number of executable node bindings.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }
}

impl fmt::Debug for ExecutableGraph {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExecutableGraph")
            .field("graph", &self.graph.reference())
            .field("reducer", self.reducer.reference())
            .field("nodes", &self.nodes.len())
            .finish_non_exhaustive()
    }
}

/// Startup-only builder for a closed executable deployment snapshot.
pub struct ExecutableGraphRegistryBuilder {
    schemas: JsonSchemaRegistry,
    graphs: HashMap<GraphReference, Arc<CompiledGraph>>,
    graph_identities: HashMap<stateknot_core::CapabilityIdentity, GraphReference>,
    reducers: HashMap<GraphReducerReference, Arc<dyn GraphReducer>>,
    reducer_identities: HashMap<stateknot_core::CapabilityIdentity, GraphReducerReference>,
    nodes: HashMap<(GraphReference, NodeId), Arc<dyn GraphNodeExecutor>>,
}

impl ExecutableGraphRegistryBuilder {
    /// Maximum graph definitions in one process snapshot.
    pub const MAX_GRAPHS: usize = 1024;
    /// Maximum reducer revisions in one process snapshot.
    pub const MAX_REDUCERS: usize = 1024;
    /// Maximum graph-node implementations in one process snapshot.
    pub const MAX_NODE_EXECUTORS: usize = 65_536;

    /// Creates an empty executable binding builder over a frozen schema set.
    #[must_use]
    pub fn new(schemas: JsonSchemaRegistry) -> Self {
        Self {
            schemas,
            graphs: HashMap::new(),
            graph_identities: HashMap::new(),
            reducers: HashMap::new(),
            reducer_identities: HashMap::new(),
            nodes: HashMap::new(),
        }
    }

    /// Registers one canonical declarative graph revision.
    ///
    /// # Errors
    ///
    /// Rejects ceiling exhaustion, an exact duplicate, or reuse of the same
    /// owner/name/version identity with different immutable bytes.
    pub fn register_graph(
        &mut self,
        graph: CompiledGraph,
    ) -> Result<(), ExecutableGraphRegistryError> {
        if self.graphs.len() == Self::MAX_GRAPHS {
            return Err(ExecutableGraphRegistryError::TooManyGraphs {
                maximum: Self::MAX_GRAPHS,
                actual: Self::MAX_GRAPHS + 1,
            });
        }
        let reference = graph.reference();
        if self.graphs.contains_key(&reference) {
            return Err(ExecutableGraphRegistryError::DuplicateGraph {
                reference: Box::new(reference),
            });
        }
        if let Some(existing) = self.graph_identities.get(graph.identity()) {
            return Err(ExecutableGraphRegistryError::GraphIdentityConflict {
                existing: Box::new(existing.clone()),
                rejected: Box::new(reference),
            });
        }
        self.graph_identities
            .insert(graph.identity().clone(), reference.clone());
        self.graphs.insert(reference, Arc::new(graph));
        Ok(())
    }

    /// Registers one exactly referenced pure reducer implementation.
    ///
    /// # Errors
    ///
    /// Rejects ceiling exhaustion, duplicate references, or identity reuse
    /// with another digest.
    pub fn register_reducer(
        &mut self,
        reducer: Arc<dyn GraphReducer>,
    ) -> Result<(), ExecutableGraphRegistryError> {
        if self.reducers.len() == Self::MAX_REDUCERS {
            return Err(ExecutableGraphRegistryError::TooManyReducers {
                maximum: Self::MAX_REDUCERS,
                actual: Self::MAX_REDUCERS + 1,
            });
        }
        let reference = reducer.reference().clone();
        if self.reducers.contains_key(&reference) {
            return Err(ExecutableGraphRegistryError::DuplicateReducer {
                reference: Box::new(reference),
            });
        }
        if let Some(existing) = self.reducer_identities.get(reference.identity()) {
            return Err(ExecutableGraphRegistryError::ReducerIdentityConflict {
                existing: Box::new(existing.clone()),
                rejected: Box::new(reference),
            });
        }
        self.reducer_identities
            .insert(reference.identity().clone(), reference.clone());
        self.reducers.insert(reference, reducer);
        Ok(())
    }

    /// Registers one node implementation bound to a whole graph digest.
    ///
    /// # Errors
    ///
    /// Rejects ceiling exhaustion or a repeated `(graph, node)` binding.
    pub fn register_node(
        &mut self,
        executor: Arc<dyn GraphNodeExecutor>,
    ) -> Result<(), ExecutableGraphRegistryError> {
        if self.nodes.len() == Self::MAX_NODE_EXECUTORS {
            return Err(ExecutableGraphRegistryError::TooManyNodeExecutors {
                maximum: Self::MAX_NODE_EXECUTORS,
                actual: Self::MAX_NODE_EXECUTORS + 1,
            });
        }
        let key = (executor.graph().clone(), executor.node_id().clone());
        if self.nodes.contains_key(&key) {
            return Err(ExecutableGraphRegistryError::DuplicateNodeExecutor {
                graph: Box::new(key.0),
                node_id: key.1,
            });
        }
        self.nodes.insert(key, executor);
        Ok(())
    }

    /// Verifies complete graph/schema/reducer/node closure and freezes lookup.
    ///
    /// # Errors
    ///
    /// Rejects an empty deployment; absent graph schemas, reducers, or nodes;
    /// node code not declared by its graph; and orphan executable code that no
    /// registered graph can ever resolve.
    pub fn build(self) -> Result<ExecutableGraphRegistry, ExecutableGraphRegistryError> {
        if self.graphs.is_empty() {
            return Err(ExecutableGraphRegistryError::EmptyGraphs);
        }

        for (reference, graph) in &self.graphs {
            if let Some(policy) = graph.child_runs() {
                for declaration in policy.declarations() {
                    let target = self.graphs.get(declaration.graph()).ok_or_else(|| {
                        ExecutableGraphRegistryError::MissingChildGraph {
                            parent: Box::new(reference.clone()),
                            child: Box::new(declaration.graph().clone()),
                        }
                    })?;
                    declaration
                        .validate_target(target, policy.limits())
                        .map_err(|source| ExecutableGraphRegistryError::ChildPolicy {
                            graph: Box::new(reference.clone()),
                            source,
                        })?;
                }
            }
        }

        let mut executable = HashMap::with_capacity(self.graphs.len());
        let mut used_reducers = std::collections::HashSet::new();
        let mut used_nodes = std::collections::HashSet::new();
        for (reference, graph) in &self.graphs {
            for schema in [
                graph.input_schema(),
                graph.state_schema(),
                graph.update_schema(),
                graph.output_schema(),
            ] {
                if !self.schemas.contains(schema) {
                    return Err(ExecutableGraphRegistryError::MissingSchema {
                        graph: Box::new(reference.clone()),
                        schema: Box::new(schema.clone()),
                    });
                }
            }
            let reducer = self.reducers.get(graph.reducer()).cloned().ok_or_else(|| {
                ExecutableGraphRegistryError::MissingReducer {
                    graph: Box::new(reference.clone()),
                    reducer: Box::new(graph.reducer().clone()),
                }
            })?;
            used_reducers.insert(graph.reducer().clone());

            let mut graph_nodes = HashMap::with_capacity(graph.nodes().len());
            for node in graph.nodes() {
                let key = (reference.clone(), node.node_id().clone());
                let executor = self.nodes.get(&key).cloned().ok_or_else(|| {
                    ExecutableGraphRegistryError::MissingNodeExecutor {
                        graph: Box::new(reference.clone()),
                        node_id: node.node_id().clone(),
                    }
                })?;
                let declares_children = graph.child_runs().is_some_and(|policy| {
                    policy
                        .declarations()
                        .iter()
                        .any(|d| d.node_id() == node.node_id())
                });
                if (declares_children && executor.scheduling() != GraphNodeScheduling::Exclusive)
                    || (executor.supports_child_join()
                        && (!declares_children
                            || !crate::child_join::schema_available(&self.schemas)))
                {
                    return Err(ExecutableGraphRegistryError::InvalidChildJoinExecutor);
                }
                used_nodes.insert(key);
                graph_nodes.insert(node.node_id().clone(), executor);
            }
            executable.insert(
                reference.clone(),
                ExecutableGraph {
                    graph: Arc::clone(graph),
                    schemas: self.schemas.clone(),
                    reducer,
                    nodes: Arc::new(graph_nodes),
                },
            );
        }

        if let Some(reference) = self
            .reducers
            .keys()
            .find(|reference| !used_reducers.contains(*reference))
        {
            return Err(ExecutableGraphRegistryError::OrphanReducer {
                reducer: Box::new(reference.clone()),
            });
        }
        if let Some((graph, node_id)) = self.nodes.keys().find(|key| !used_nodes.contains(*key)) {
            return Err(ExecutableGraphRegistryError::OrphanNodeExecutor {
                graph: Box::new(graph.clone()),
                node_id: node_id.clone(),
            });
        }

        Ok(ExecutableGraphRegistry {
            schemas: self.schemas,
            graphs: Arc::new(executable),
        })
    }
}

impl fmt::Debug for ExecutableGraphRegistryBuilder {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExecutableGraphRegistryBuilder")
            .field("schemas", &self.schemas)
            .field("graphs", &self.graphs.len())
            .field("reducers", &self.reducers.len())
            .field("nodes", &self.nodes.len())
            .finish_non_exhaustive()
    }
}

/// Immutable deployment snapshot resolved only by complete graph reference.
#[derive(Clone)]
pub struct ExecutableGraphRegistry {
    schemas: JsonSchemaRegistry,
    graphs: Arc<HashMap<GraphReference, ExecutableGraph>>,
}

impl ExecutableGraphRegistry {
    pub(crate) fn has_child_graphs(&self) -> bool {
        self.graphs
            .values()
            .any(|entry| entry.graph().child_runs().is_some())
    }
    /// Resolves an exact graph descriptor and all local executable bindings.
    #[must_use]
    pub fn resolve(&self, reference: &GraphReference) -> Option<&ExecutableGraph> {
        self.graphs.get(reference)
    }

    /// Returns the shared frozen schema registry.
    #[must_use]
    pub const fn schemas(&self) -> &JsonSchemaRegistry {
        &self.schemas
    }

    /// Returns the number of executable graph revisions.
    #[must_use]
    pub fn len(&self) -> usize {
        self.graphs.len()
    }

    /// Returns whether no executable graph was installed.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.graphs.is_empty()
    }
}

impl fmt::Debug for ExecutableGraphRegistry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExecutableGraphRegistry")
            .field("schemas", &self.schemas.len())
            .field("graphs", &self.graphs.len())
            .finish_non_exhaustive()
    }
}

/// Startup-time failure while freezing executable graph bindings.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ExecutableGraphRegistryError {
    /// Child executors require exclusive scheduling; Join additionally requires
    /// declared slots and the exact embedded audit schema before any dispatch.
    #[error(
        "child Join executor requires declared slots, exclusive scheduling and its audit schema"
    )]
    InvalidChildJoinExecutor,
    /// A declared child target has no exact graph in this frozen deployment.
    #[error("executable registry lacks a declared child graph")]
    MissingChildGraph {
        /// Declaring parent graph.
        parent: Box<GraphReference>,
        /// Missing exact child graph.
        child: Box<GraphReference>,
    },
    /// A declared target has incompatible schema pins or remaining depth.
    #[error("executable registry child policy validation failed: {source}")]
    ChildPolicy {
        /// Declaring parent graph.
        graph: Box<GraphReference>,
        /// Closed, public-safe reason.
        #[source]
        source: ChildRunPolicyError,
    },
    /// No executable graph could be resolved.
    #[error("executable graph registry must contain at least one graph")]
    EmptyGraphs,
    /// Graph count exceeded the immutable deployment ceiling.
    #[error("executable registry contains {actual} graphs; maximum is {maximum}")]
    TooManyGraphs {
        /// Immutable maximum.
        maximum: usize,
        /// First rejected count.
        actual: usize,
    },
    /// Reducer count exceeded the immutable deployment ceiling.
    #[error("executable registry contains {actual} reducers; maximum is {maximum}")]
    TooManyReducers {
        /// Immutable maximum.
        maximum: usize,
        /// First rejected count.
        actual: usize,
    },
    /// Node implementation count exceeded the deployment ceiling.
    #[error("executable registry contains {actual} nodes; maximum is {maximum}")]
    TooManyNodeExecutors {
        /// Immutable maximum.
        maximum: usize,
        /// First rejected count.
        actual: usize,
    },
    /// The exact canonical graph was registered twice.
    #[error("compiled graph reference was registered more than once")]
    DuplicateGraph {
        /// Repeated graph reference.
        reference: Box<GraphReference>,
    },
    /// One graph identity attempted to carry different canonical bytes.
    #[error("graph owner/name/version identity was reused with another definition")]
    GraphIdentityConflict {
        /// First graph reference.
        existing: Box<GraphReference>,
        /// Rejected graph reference.
        rejected: Box<GraphReference>,
    },
    /// The exact reducer revision was registered twice.
    #[error("graph reducer reference was registered more than once")]
    DuplicateReducer {
        /// Repeated reducer reference.
        reference: Box<GraphReducerReference>,
    },
    /// One reducer identity attempted to carry different implementation bytes.
    #[error("reducer owner/name/version identity was reused with another definition")]
    ReducerIdentityConflict {
        /// First reducer reference.
        existing: Box<GraphReducerReference>,
        /// Rejected reducer reference.
        rejected: Box<GraphReducerReference>,
    },
    /// One whole-graph node binding was registered twice.
    #[error("graph node executor was registered more than once")]
    DuplicateNodeExecutor {
        /// Exact graph definition.
        graph: Box<GraphReference>,
        /// Repeated node identity.
        node_id: NodeId,
    },
    /// A graph referenced a schema absent from the frozen offline set.
    #[error("compiled graph references an unavailable schema")]
    MissingSchema {
        /// Graph with the incomplete dependency closure.
        graph: Box<GraphReference>,
        /// Missing schema reference.
        schema: Box<stateknot_core::SchemaReference>,
    },
    /// A graph's exactly pinned reducer was absent.
    #[error("compiled graph references an unavailable reducer")]
    MissingReducer {
        /// Graph with the incomplete dependency closure.
        graph: Box<GraphReference>,
        /// Missing reducer reference.
        reducer: Box<GraphReducerReference>,
    },
    /// One compiled node had no exact implementation.
    #[error("compiled graph node has no executable implementation")]
    MissingNodeExecutor {
        /// Graph with the incomplete dependency closure.
        graph: Box<GraphReference>,
        /// Missing node implementation.
        node_id: NodeId,
    },
    /// Installed reducer code was unreachable from every registered graph.
    #[error("registered reducer is not referenced by any installed graph")]
    OrphanReducer {
        /// Unused reducer implementation.
        reducer: Box<GraphReducerReference>,
    },
    /// Installed node code did not belong to a declared graph node.
    #[error("registered node executor is not declared by an installed graph")]
    OrphanNodeExecutor {
        /// Claimed graph definition.
        graph: Box<GraphReference>,
        /// Undeclared or unavailable node.
        node_id: NodeId,
    },
}

#[cfg(test)]
#[path = "registry_child_tests.rs"]
mod child_tests;

#[cfg(test)]
mod tests {
    use serde_json::{Value, json};
    use stateknot_core::{
        BoundedJson, CapabilityIdentity, CapabilityName, CapabilityReference, GraphExecutionLimits,
        GraphNode, GraphReducerError, GraphReducerInput, GraphRoutes, IssuerId, PrincipalIdentity,
        ReadyNodes, SchemaId, SchemaReference, SubjectId, Superstep, Version,
    };

    use super::*;
    use crate::JsonSchemaRegistryBuilder;

    const DRAFT: &str = "https://json-schema.org/draft/2020-12/schema";

    fn identity(name: &str) -> CapabilityIdentity {
        CapabilityIdentity::new(
            PrincipalIdentity::new(
                IssuerId::new("https://issuer.example.com").unwrap(),
                SubjectId::new("runtime-tests").unwrap(),
            ),
            CapabilityReference::new(CapabilityName::new(name).unwrap(), Version::new(1, 0, 0)),
        )
    }

    fn schema_reference(id: &str, document: &Value) -> SchemaReference {
        SchemaReference::new(
            id.parse::<SchemaId>().unwrap(),
            Version::new(1, 0, 0),
            stateknot_core::Digest::sha256(serde_json_canonicalizer::to_vec(document).unwrap()),
        )
    }

    fn schemas() -> (JsonSchemaRegistry, SchemaReference) {
        let id = "https://schemas.example.com/graph-value/1.0.0";
        let document = json!({
            "$schema": DRAFT,
            "$id": id,
            "type": "object",
            "additionalProperties": true
        });
        let reference = schema_reference(id, &document);
        let mut builder = JsonSchemaRegistryBuilder::default();
        builder.register(reference.clone(), document).unwrap();
        (builder.build().unwrap(), reference)
    }

    fn graph(schema: &SchemaReference, reducer: GraphReducerReference) -> (CompiledGraph, NodeId) {
        let node_id = NodeId::new("finish").unwrap();
        let node = GraphNode::new(node_id.clone(), None, GraphRoutes::empty(), None, true).unwrap();
        let graph = CompiledGraph::compile(
            identity("graph"),
            schema.clone(),
            schema.clone(),
            schema.clone(),
            schema.clone(),
            reducer,
            ReadyNodes::try_new([node_id.clone()]).unwrap(),
            [node],
            GraphExecutionLimits::new(Superstep::new(32).unwrap(), 4).unwrap(),
        )
        .unwrap();
        (graph, node_id)
    }

    struct Reducer {
        reference: GraphReducerReference,
    }

    impl GraphReducer for Reducer {
        fn reference(&self) -> &GraphReducerReference {
            &self.reference
        }

        fn reduce(
            &self,
            state: &BoundedJson,
            _: &[GraphReducerInput<'_>],
        ) -> Result<BoundedJson, GraphReducerError> {
            Ok(state.clone())
        }
    }

    struct Executor {
        graph: GraphReference,
        node_id: NodeId,
    }

    impl GraphNodeExecutor for Executor {
        fn graph(&self) -> &GraphReference {
            &self.graph
        }

        fn node_id(&self) -> &NodeId {
            &self.node_id
        }

        fn execute(
            &self,
            _: GraphNodeContext,
        ) -> BoxFuture<'_, Result<GraphNodeExecution, GraphNodeExecutionError>> {
            Box::pin(async { panic!("registry tests do not execute node code") })
        }
    }

    #[test]
    fn complete_registry_freezes_exact_graph_dependencies() {
        let (schemas, schema) = schemas();
        let reducer_reference =
            GraphReducerReference::new(identity("reducer"), stateknot_core::Digest::sha256(b"v1"));
        let reducer = Arc::new(Reducer {
            reference: reducer_reference.clone(),
        });
        let (graph, node_id) = graph(&schema, reducer_reference.clone());
        let graph_reference = graph.reference();
        let executor: Arc<dyn GraphNodeExecutor> = Arc::new(Executor {
            graph: graph_reference.clone(),
            node_id: node_id.clone(),
        });
        let mut builder = ExecutableGraphRegistryBuilder::new(schemas);
        builder.register_node(Arc::clone(&executor)).unwrap();
        assert!(matches!(
            builder.register_node(Arc::new(Executor {
                graph: graph_reference.clone(),
                node_id: node_id.clone(),
            })),
            Err(ExecutableGraphRegistryError::DuplicateNodeExecutor { .. })
        ));
        builder.register_reducer(reducer).unwrap();
        builder.register_graph(graph).unwrap();

        let registry = builder.build().unwrap();
        let executable = registry.resolve(&graph_reference).unwrap();
        assert_eq!(registry.len(), 1);
        assert_eq!(executable.graph().reference(), graph_reference);
        assert_eq!(executable.reducer().reference(), &reducer_reference);
        assert_eq!(executable.node(&node_id).unwrap().node_id(), &node_id);
        assert!(Arc::ptr_eq(
            &executable.node_executor(&node_id).unwrap(),
            &executor
        ));
    }

    #[test]
    fn build_rejects_missing_and_orphan_node_code() {
        let (schemas, schema) = schemas();
        let reducer_reference = GraphReducerReference::new(
            identity("reducer"),
            stateknot_core::Digest::sha256(b"reducer"),
        );
        let reducer = Arc::new(Reducer {
            reference: reducer_reference.clone(),
        });
        let (graph, node_id) = graph(&schema, reducer_reference);
        let graph_reference = graph.reference();
        let mut missing = ExecutableGraphRegistryBuilder::new(schemas.clone());
        missing.register_reducer(reducer.clone()).unwrap();
        missing.register_graph(graph.clone()).unwrap();
        assert!(matches!(
            missing.build(),
            Err(ExecutableGraphRegistryError::MissingNodeExecutor { .. })
        ));

        let mut orphan = ExecutableGraphRegistryBuilder::new(schemas);
        orphan.register_reducer(reducer).unwrap();
        orphan.register_graph(graph).unwrap();
        orphan
            .register_node(Arc::new(Executor {
                graph: graph_reference.clone(),
                node_id,
            }))
            .unwrap();
        orphan
            .register_node(Arc::new(Executor {
                graph: graph_reference,
                node_id: NodeId::new("undeclared").unwrap(),
            }))
            .unwrap();
        assert!(matches!(
            orphan.build(),
            Err(ExecutableGraphRegistryError::OrphanNodeExecutor { .. })
        ));
    }
}