tenferro-runtime 0.9.0

Concrete tensor helpers, traced tensors, graph execution, and extension runtime support for tenferro.
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
use std::fmt;
use std::sync::Arc;

use super::{
    CoreCapabilityBundle, EngineId, ExecutionContextIdentity, HardwareClassId, InputSignatureEntry,
    ProviderDeviceIdentity, RuntimeConfigError, StorageClass,
};
use tenferro_tensor::{AllocationDomainId, Placement, TensorRead};

#[derive(Debug)]
pub(super) struct CandidateRegistrationToken;

type InputPlacementPredicate = dyn Fn(&Placement, &StorageClass) -> bool + Send + Sync + 'static;
type InputSignaturePredicate = dyn Fn(&Placement, Option<&'static str>, Option<AllocationDomainId>, &StorageClass) -> bool
    + Send
    + Sync
    + 'static;
type InputTensorPredicate =
    dyn for<'a> Fn(&TensorRead<'a>, &StorageClass) -> bool + Send + Sync + 'static;

/// Named placement admission contract for one provider ingress.
#[derive(Clone)]
pub struct InputPlacementContract(Arc<InputPlacementPredicate>);

impl InputPlacementContract {
    /// Construct a named placement admission contract.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use tenferro_runtime::{InputPlacementContract, StorageClass};
    /// use tenferro_tensor::Placement;
    ///
    /// let storage = StorageClass::new("example.storage.host")?;
    /// let contract = InputPlacementContract::new(move |placement: &Placement, candidate| {
    ///     placement == &Placement::default() && candidate == &storage
    /// });
    /// let _ = contract;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(
        predicate: impl Fn(&Placement, &StorageClass) -> bool + Send + Sync + 'static,
    ) -> Self {
        Self(Arc::new(predicate))
    }

    fn accepts(&self, placement: &Placement, storage_class: &StorageClass) -> bool {
        (self.0)(placement, storage_class)
    }
}

impl fmt::Debug for InputPlacementContract {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("InputPlacementContract(..)")
    }
}

/// Named value-free physical input signature contract.
#[derive(Clone)]
pub struct InputSignatureContract(Arc<InputSignaturePredicate>);

impl InputSignatureContract {
    /// Construct a named value-free physical input signature contract.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use tenferro_runtime::{InputSignatureContract, StorageClass};
    /// use tenferro_tensor::Placement;
    ///
    /// let storage = StorageClass::new("example.storage.host")?;
    /// let contract = InputSignatureContract::new(move |
    ///     placement: &Placement, family, domain, candidate| {
    ///         placement == &Placement::default()
    ///             && family.is_none()
    ///             && domain.is_none()
    ///             && candidate == &storage
    ///     });
    /// let _ = contract;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(
        predicate: impl Fn(&Placement, Option<&'static str>, Option<AllocationDomainId>, &StorageClass) -> bool
            + Send
            + Sync
            + 'static,
    ) -> Self {
        Self(Arc::new(predicate))
    }

    fn accepts(&self, input: &InputSignatureEntry, storage_class: &StorageClass) -> bool {
        (self.0)(
            input.placement(),
            input.backend_family(),
            input.allocation_domain(),
            storage_class,
        )
    }
}

impl fmt::Debug for InputSignatureContract {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("InputSignatureContract(..)")
    }
}

/// Named runtime-input residency contract.
#[derive(Clone)]
pub struct RuntimeInputContract(Arc<InputTensorPredicate>);

impl RuntimeInputContract {
    /// Construct a named runtime-input residency contract.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::RuntimeInputContract;
    ///
    /// let contract = RuntimeInputContract::new(|_, _| true);
    /// let _ = contract;
    /// ```
    pub fn new(
        predicate: impl for<'a> Fn(&TensorRead<'a>, &StorageClass) -> bool + Send + Sync + 'static,
    ) -> Self {
        Self(Arc::new(predicate))
    }

    fn accepts(&self, input: &TensorRead<'_>, storage_class: &StorageClass) -> bool {
        (self.0)(input, storage_class)
    }
}

impl fmt::Debug for RuntimeInputContract {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("RuntimeInputContract(..)")
    }
}

/// Named resident-output ownership contract.
#[derive(Clone)]
pub struct ResidentOutputContract(Arc<InputTensorPredicate>);

impl ResidentOutputContract {
    /// Construct a named resident-output ownership contract.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::ResidentOutputContract;
    ///
    /// let contract = ResidentOutputContract::new(|_, _| true);
    /// let _ = contract;
    /// ```
    pub fn new(
        predicate: impl for<'a> Fn(&TensorRead<'a>, &StorageClass) -> bool + Send + Sync + 'static,
    ) -> Self {
        Self(Arc::new(predicate))
    }

    fn accepts(&self, input: &TensorRead<'_>, storage_class: &StorageClass) -> bool {
        (self.0)(input, storage_class)
    }
}

impl fmt::Debug for ResidentOutputContract {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("ResidentOutputContract(..)")
    }
}

/// Complete named ingress contract for an executable provider binding.
#[derive(Clone, Debug)]
pub struct InputIngressContract {
    placement: InputPlacementContract,
    signature: InputSignatureContract,
    runtime_input: RuntimeInputContract,
    resident_output: ResidentOutputContract,
}

impl InputIngressContract {
    /// Assemble the four distinct ingress contracts atomically.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::{
    ///     InputIngressContract, InputPlacementContract, InputSignatureContract,
    ///     ResidentOutputContract, RuntimeInputContract,
    /// };
    ///
    /// let ingress = InputIngressContract::new(
    ///     InputPlacementContract::new(|_, _| true),
    ///     InputSignatureContract::new(|_, _, _, _| true),
    ///     RuntimeInputContract::new(|_, _| true),
    ///     ResidentOutputContract::new(|_, _| true),
    /// );
    /// let _ = ingress;
    /// ```
    pub fn new(
        placement: InputPlacementContract,
        signature: InputSignatureContract,
        runtime_input: RuntimeInputContract,
        resident_output: ResidentOutputContract,
    ) -> Self {
        Self {
            placement,
            signature,
            runtime_input,
            resident_output,
        }
    }

    fn accepts_placement(&self, placement: &Placement, storage_class: &StorageClass) -> bool {
        self.placement.accepts(placement, storage_class)
    }

    fn accepts_signature(&self, input: &InputSignatureEntry, storage_class: &StorageClass) -> bool {
        self.signature.accepts(input, storage_class)
    }

    fn accepts_runtime_input(&self, input: &TensorRead<'_>, storage_class: &StorageClass) -> bool {
        self.runtime_input.accepts(input, storage_class)
    }

    fn owns_resident_output(&self, input: &TensorRead<'_>, storage_class: &StorageClass) -> bool {
        self.resident_output.accepts(input, storage_class)
    }
}

/// Shared provider metadata for one runtime engine registration.
///
/// The caller supplies the engine and provider/device identities explicitly.
/// Storage metadata is validated when the metadata is assembled into either an
/// executable or preparation-only registration.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
///
/// use tenferro_runtime::{
///     CoreCapabilityBundle, EngineId, EngineRegistrationMetadata, HardwareClassId,
///     ProviderDeviceIdentity, ProviderId, StorageClass,
/// };
///
/// let engine_id = EngineId::new("example.engine.v1")?;
/// let provider = ProviderDeviceIdentity::new(
///     ProviderId::new("example.provider")?,
///     "device:0",
/// )?;
/// let hardware = HardwareClassId::new("example.hardware.v1")?;
/// let storage = StorageClass::new("example.storage.v1")?;
/// let metadata = EngineRegistrationMetadata::new(
///     engine_id,
///     provider,
///     hardware,
///     Arc::from([storage.clone()]),
///     storage,
///     CoreCapabilityBundle::default(),
/// );
/// let _ = metadata;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct EngineRegistrationMetadata {
    engine_id: EngineId,
    provider_device_identity: ProviderDeviceIdentity,
    hardware_class: HardwareClassId,
    storage_classes: Arc<[StorageClass]>,
    default_storage_class: StorageClass,
    capabilities: CoreCapabilityBundle,
}

impl EngineRegistrationMetadata {
    /// Construct the metadata shared by executable and preparation-only
    /// registration descriptors.
    pub fn new(
        engine_id: EngineId,
        provider_device_identity: ProviderDeviceIdentity,
        hardware_class: HardwareClassId,
        storage_classes: Arc<[StorageClass]>,
        default_storage_class: StorageClass,
        capabilities: CoreCapabilityBundle,
    ) -> Self {
        Self {
            engine_id,
            provider_device_identity,
            hardware_class,
            storage_classes,
            default_storage_class,
            capabilities,
        }
    }
}

/// Typed configuration for assembling an executable engine registration.
///
/// A registration describes one engine kind: its provider metadata, the
/// context identity of the engine type, and its ingress contract. It holds no
/// engine instance; engines are passed to [`crate::Runtime::run`] per call and
/// must report a matching [`crate::EngineTarget`].
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
///
/// use tenferro_runtime::{
///     CoreCapabilityBundle, EngineId, EngineRegistrationMetadata,
///     ExecutableEngineRegistrationConfig, ExecutionContextIdentity, HardwareClassId,
///     InputIngressContract, InputPlacementContract, InputSignatureContract,
///     ProviderDeviceIdentity, ProviderId, ResidentOutputContract, RuntimeInputContract,
///     StorageClass,
/// };
///
/// struct ExampleEngine;
///
/// let engine_id = EngineId::new("example.engine.v1").unwrap();
/// let provider = ProviderDeviceIdentity::new(
///     ProviderId::new("example.provider").unwrap(),
///     "device:0",
/// )
/// .unwrap();
/// let hardware = HardwareClassId::new("example.hardware.v1").unwrap();
/// let storage = StorageClass::new("example.storage.v1").unwrap();
/// let metadata = EngineRegistrationMetadata::new(
///     engine_id,
///     provider,
///     hardware,
///     Arc::from([storage.clone()]),
///     storage,
///     CoreCapabilityBundle::default(),
/// );
/// let ingress = InputIngressContract::new(
///     InputPlacementContract::new(|_, _| true),
///     InputSignatureContract::new(|_, _, _, _| true),
///     RuntimeInputContract::new(|_, _| true),
///     ResidentOutputContract::new(|_, _| true),
/// );
/// let _config = ExecutableEngineRegistrationConfig::new(
///     metadata,
///     ExecutionContextIdentity::of::<ExampleEngine>(),
///     ingress,
/// );
/// ```
pub struct ExecutableEngineRegistrationConfig {
    metadata: EngineRegistrationMetadata,
    context_identity: ExecutionContextIdentity,
    ingress: InputIngressContract,
}

impl fmt::Debug for ExecutableEngineRegistrationConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExecutableEngineRegistrationConfig")
            .field("metadata", &self.metadata)
            .field("context_identity", &self.context_identity)
            .field("ingress_present", &true)
            .finish_non_exhaustive()
    }
}

impl ExecutableEngineRegistrationConfig {
    /// Build the immutable registration of one executable engine kind.
    pub fn new(
        metadata: EngineRegistrationMetadata,
        context_identity: ExecutionContextIdentity,
        ingress: InputIngressContract,
    ) -> Self {
        Self {
            metadata,
            context_identity,
            ingress,
        }
    }
}

#[derive(Debug)]
pub struct PreparationOnlyEngineRegistrationConfig {
    metadata: EngineRegistrationMetadata,
    context_identity: ExecutionContextIdentity,
}

impl PreparationOnlyEngineRegistrationConfig {
    /// Construct a preparation-only registration descriptor.
    pub fn new(
        metadata: EngineRegistrationMetadata,
        context_identity: ExecutionContextIdentity,
    ) -> Self {
        Self {
            metadata,
            context_identity,
        }
    }
}

/// The complete execution witness stored by an executable provider binding.
#[derive(Clone)]
pub(crate) struct ExecutableEngineContract {
    provider_device_identity: ProviderDeviceIdentity,
    context_identity: ExecutionContextIdentity,
    capabilities: CoreCapabilityBundle,
    ingress: InputIngressContract,
}

impl ExecutableEngineContract {
    // This constructor is intentionally limited to the runtime assembly
    // boundary. Providers use assemble_executable_engine_registration instead
    // of manufacturing a partial contract and binding independently.
    pub(super) fn new(
        provider_device_identity: ProviderDeviceIdentity,
        context_identity: ExecutionContextIdentity,
        capabilities: CoreCapabilityBundle,
        ingress: InputIngressContract,
    ) -> Self {
        Self {
            provider_device_identity,
            context_identity,
            capabilities,
            ingress,
        }
    }

    pub(super) fn capabilities(&self) -> &CoreCapabilityBundle {
        &self.capabilities
    }

    pub(super) fn provider_device_identity(&self) -> &ProviderDeviceIdentity {
        &self.provider_device_identity
    }

    pub(super) fn context_identity(&self) -> ExecutionContextIdentity {
        self.context_identity
    }

    pub(super) fn accepts_input_placement(
        &self,
        placement: &Placement,
        storage_class: &StorageClass,
    ) -> bool {
        self.ingress.accepts_placement(placement, storage_class)
    }

    pub(super) fn accepts_input_signature(
        &self,
        input: &InputSignatureEntry,
        storage_class: &StorageClass,
    ) -> bool {
        self.ingress.accepts_signature(input, storage_class)
    }

    pub(super) fn accepts_runtime_input(
        &self,
        input: &TensorRead<'_>,
        storage_class: &StorageClass,
    ) -> bool {
        self.ingress.accepts_runtime_input(input, storage_class)
    }

    pub(super) fn owns_resident_tensor(
        &self,
        input: &TensorRead<'_>,
        storage_class: &StorageClass,
    ) -> bool {
        self.ingress.owns_resident_output(input, storage_class)
    }
}

impl fmt::Debug for ExecutableEngineContract {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExecutableEngineContract")
            .field("provider_device_identity", &self.provider_device_identity)
            .field("context_identity", &self.context_identity)
            .field("capabilities", &self.capabilities)
            .field("ingress", &self.ingress)
            .finish_non_exhaustive()
    }
}

/// Provider-owned metadata plus one complete executable witness.
pub(crate) struct ProviderExecutableBinding {
    engine_id: EngineId,
    hardware_class: HardwareClassId,
    storage_classes: Arc<[StorageClass]>,
    default_storage_class: StorageClass,
    contract: ExecutableEngineContract,
}

impl ProviderExecutableBinding {
    // Storage metadata is validated as part of the runtime-owned executable
    // assembly; this partial constructor is not a public provider API.
    pub(super) fn new(
        engine_id: EngineId,
        hardware_class: HardwareClassId,
        storage_classes: Arc<[StorageClass]>,
        default_storage_class: StorageClass,
        contract: ExecutableEngineContract,
    ) -> Result<Self, RuntimeConfigError> {
        validate_storage_classes(&engine_id, &storage_classes, &default_storage_class)?;
        Ok(Self {
            engine_id,
            hardware_class,
            storage_classes,
            default_storage_class,
            contract,
        })
    }

    pub(super) fn engine_id(&self) -> &EngineId {
        &self.engine_id
    }

    pub(super) fn hardware_class(&self) -> &HardwareClassId {
        &self.hardware_class
    }

    pub(super) fn storage_classes(&self) -> &[StorageClass] {
        &self.storage_classes
    }

    pub(super) fn default_storage_class(&self) -> &StorageClass {
        &self.default_storage_class
    }

    pub(super) fn contract(&self) -> &ExecutableEngineContract {
        &self.contract
    }
}

impl fmt::Debug for ProviderExecutableBinding {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProviderExecutableBinding")
            .field("engine_id", &self.engine_id)
            .field("hardware_class", &self.hardware_class)
            .field("storage_class_count", &self.storage_classes.len())
            .field("contract", &self.contract)
            .finish_non_exhaustive()
    }
}

impl Clone for ProviderExecutableBinding {
    fn clone(&self) -> Self {
        Self {
            engine_id: self.engine_id.clone(),
            hardware_class: self.hardware_class.clone(),
            storage_classes: Arc::clone(&self.storage_classes),
            default_storage_class: self.default_storage_class.clone(),
            contract: self.contract.clone(),
        }
    }
}

/// Provider-owned metadata plus preparation capabilities without execution.
pub(crate) struct ProviderPreparationBinding {
    engine_id: EngineId,
    provider_device_identity: ProviderDeviceIdentity,
    context_identity: ExecutionContextIdentity,
    hardware_class: HardwareClassId,
    storage_classes: Arc<[StorageClass]>,
    default_storage_class: StorageClass,
    capabilities: CoreCapabilityBundle,
}

impl ProviderPreparationBinding {
    // Preparation-only metadata follows the same runtime-owned assembly
    // boundary and cannot be promoted to an executable binding.
    pub(super) fn new(
        engine_id: EngineId,
        provider_device_identity: ProviderDeviceIdentity,
        context_identity: ExecutionContextIdentity,
        hardware_class: HardwareClassId,
        storage_classes: Arc<[StorageClass]>,
        default_storage_class: StorageClass,
        capabilities: CoreCapabilityBundle,
    ) -> Result<Self, RuntimeConfigError> {
        validate_storage_classes(&engine_id, &storage_classes, &default_storage_class)?;
        Ok(Self {
            engine_id,
            provider_device_identity,
            context_identity,
            hardware_class,
            storage_classes,
            default_storage_class,
            capabilities,
        })
    }

    pub(super) fn engine_id(&self) -> &EngineId {
        &self.engine_id
    }

    pub(super) fn provider_device_identity(&self) -> &ProviderDeviceIdentity {
        &self.provider_device_identity
    }

    pub(super) fn context_identity(&self) -> ExecutionContextIdentity {
        self.context_identity
    }

    pub(super) fn hardware_class(&self) -> &HardwareClassId {
        &self.hardware_class
    }

    pub(super) fn storage_classes(&self) -> &[StorageClass] {
        &self.storage_classes
    }

    pub(super) fn default_storage_class(&self) -> &StorageClass {
        &self.default_storage_class
    }

    pub(super) fn capabilities(&self) -> &CoreCapabilityBundle {
        &self.capabilities
    }
}

impl Clone for ProviderPreparationBinding {
    fn clone(&self) -> Self {
        Self {
            engine_id: self.engine_id.clone(),
            provider_device_identity: self.provider_device_identity.clone(),
            context_identity: self.context_identity,
            hardware_class: self.hardware_class.clone(),
            storage_classes: Arc::clone(&self.storage_classes),
            default_storage_class: self.default_storage_class.clone(),
            capabilities: self.capabilities.clone(),
        }
    }
}

impl fmt::Debug for ProviderPreparationBinding {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProviderPreparationBinding")
            .field("engine_id", &self.engine_id)
            .field("provider_device_identity", &self.provider_device_identity)
            .field("context_identity", &self.context_identity)
            .field("hardware_class", &self.hardware_class)
            .field("storage_class_count", &self.storage_classes.len())
            .field("capabilities", &self.capabilities)
            .finish_non_exhaustive()
    }
}

/// Mutually exclusive preparation-only or executable registration state.
#[derive(Clone, Debug)]
pub(crate) enum EngineRegistrationState {
    /// Capabilities are available to planning, but this registration cannot
    /// admit runtime inputs or execute a schedule.
    PreparationOnly { binding: ProviderPreparationBinding },
    /// A complete provider execution witness.
    Executable(ProviderExecutableBinding),
}

impl EngineRegistrationState {
    pub(super) fn capabilities(&self) -> &CoreCapabilityBundle {
        match self {
            Self::PreparationOnly { binding } => binding.capabilities(),
            Self::Executable(binding) => binding.contract().capabilities(),
        }
    }

    pub(super) fn engine_id(&self) -> &EngineId {
        match self {
            Self::PreparationOnly { binding } => binding.engine_id(),
            Self::Executable(binding) => binding.engine_id(),
        }
    }

    pub(super) fn provider_device_identity(&self) -> &ProviderDeviceIdentity {
        match self {
            Self::PreparationOnly { binding } => binding.provider_device_identity(),
            Self::Executable(binding) => binding.contract().provider_device_identity(),
        }
    }

    pub(super) fn context_identity(&self) -> ExecutionContextIdentity {
        match self {
            Self::PreparationOnly { binding } => binding.context_identity(),
            Self::Executable(binding) => binding.contract().context_identity(),
        }
    }

    pub(super) fn hardware_class(&self) -> &HardwareClassId {
        match self {
            Self::PreparationOnly { binding } => binding.hardware_class(),
            Self::Executable(binding) => binding.hardware_class(),
        }
    }

    pub(super) fn storage_classes(&self) -> &[StorageClass] {
        match self {
            Self::PreparationOnly { binding } => binding.storage_classes(),
            Self::Executable(binding) => binding.storage_classes(),
        }
    }

    pub(super) fn default_storage_class(&self) -> &StorageClass {
        match self {
            Self::PreparationOnly { binding } => binding.default_storage_class(),
            Self::Executable(binding) => binding.default_storage_class(),
        }
    }
}

/// Immutable direct engine registration candidate.
#[derive(Clone)]
pub struct EngineRegistration {
    state: EngineRegistrationState,
    candidate_token: Arc<CandidateRegistrationToken>,
}

impl EngineRegistration {
    /// Consume one provider-owned preparation binding.
    pub(super) fn preparation_only(binding: ProviderPreparationBinding) -> Self {
        Self {
            state: EngineRegistrationState::PreparationOnly { binding },
            candidate_token: Arc::new(CandidateRegistrationToken),
        }
    }

    /// Consume one provider-owned complete executable binding.
    pub(super) fn executable(binding: ProviderExecutableBinding) -> Self {
        Self {
            state: EngineRegistrationState::Executable(binding),
            candidate_token: Arc::new(CandidateRegistrationToken),
        }
    }

    pub(super) fn from_state(state: EngineRegistrationState) -> Self {
        Self {
            state,
            candidate_token: Arc::new(CandidateRegistrationToken),
        }
    }

    /// Return the immutable registration state witness.
    #[cfg(test)]
    pub(crate) fn execution_state(&self) -> &EngineRegistrationState {
        &self.state
    }

    /// Return the engine identifier.
    pub fn engine_id(&self) -> &EngineId {
        self.state.engine_id()
    }

    /// Return the immutable provider/device binding for this engine.
    pub fn provider_device_identity(&self) -> &ProviderDeviceIdentity {
        self.state.provider_device_identity()
    }

    /// Return the execution-context type identity accepted by the engine.
    pub fn context_identity(&self) -> ExecutionContextIdentity {
        self.state.context_identity()
    }

    /// Return the hardware class exposed by this engine.
    pub fn hardware_class(&self) -> &HardwareClassId {
        self.state.hardware_class()
    }

    /// Return the supported storage classes in registration order.
    pub fn storage_classes(&self) -> &[StorageClass] {
        self.state.storage_classes()
    }

    pub(super) fn with_candidate_token(
        mut self,
        candidate_token: Arc<CandidateRegistrationToken>,
    ) -> Self {
        self.candidate_token = candidate_token;
        self
    }

    pub(super) fn into_state_and_token(
        self,
    ) -> (EngineRegistrationState, Arc<CandidateRegistrationToken>) {
        (self.state, self.candidate_token)
    }

    /// Return the default storage class.
    pub fn default_storage_class(&self) -> &StorageClass {
        self.state.default_storage_class()
    }

    /// Return direct core capability slots.
    pub fn capabilities(&self) -> &CoreCapabilityBundle {
        self.state.capabilities()
    }

    pub(super) fn candidate_identical(&self, other: &Self) -> bool {
        self.engine_id() == other.engine_id()
            && Arc::ptr_eq(&self.candidate_token, &other.candidate_token)
    }
}

/// Assemble one complete executable provider registration.
///
/// Provider adapters supply only provider-owned identity, capability, ingress,
/// event-driver, and cache-owner values.  The runtime owns the assembly of the
/// executable witness and its storage metadata so every executable engine
/// enters the runtime through the same invariant-preserving path.
///
/// # Errors
///
/// Returns [`RuntimeConfigError`] if the descriptor contains empty or duplicate
/// storage classes, or if its default storage class is not listed in the
/// supported storage classes.
pub fn assemble_executable_engine_registration(
    config: ExecutableEngineRegistrationConfig,
) -> Result<EngineRegistration, RuntimeConfigError> {
    let ExecutableEngineRegistrationConfig {
        metadata:
            EngineRegistrationMetadata {
                engine_id,
                provider_device_identity,
                hardware_class,
                storage_classes,
                default_storage_class,
                capabilities,
            },
        context_identity,
        ingress,
    } = config;
    let contract = ExecutableEngineContract::new(
        provider_device_identity,
        context_identity,
        capabilities,
        ingress,
    );
    let binding = ProviderExecutableBinding::new(
        engine_id,
        hardware_class,
        storage_classes,
        default_storage_class,
        contract,
    )?;
    Ok(EngineRegistration::executable(binding))
}

/// Assemble one preparation-only provider registration.
///
/// This is the preparation counterpart of
/// [`assemble_executable_engine_registration`].  It deliberately cannot
/// manufacture an execution bridge or a scheduled witness.
///
/// # Errors
///
/// Returns [`RuntimeConfigError`] if the descriptor contains empty or duplicate
/// storage classes, or if its default storage class is not listed in the
/// supported storage classes.
pub fn assemble_preparation_only_engine_registration(
    config: PreparationOnlyEngineRegistrationConfig,
) -> Result<EngineRegistration, RuntimeConfigError> {
    let PreparationOnlyEngineRegistrationConfig {
        metadata:
            EngineRegistrationMetadata {
                engine_id,
                provider_device_identity,
                hardware_class,
                storage_classes,
                default_storage_class,
                capabilities,
            },
        context_identity,
    } = config;
    let binding = ProviderPreparationBinding::new(
        engine_id,
        provider_device_identity,
        context_identity,
        hardware_class,
        storage_classes,
        default_storage_class,
        capabilities,
    )?;
    Ok(EngineRegistration::preparation_only(binding))
}

impl fmt::Debug for EngineRegistration {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("EngineRegistration")
            .field("engine_id", self.engine_id())
            .field("provider_device_identity", self.provider_device_identity())
            .field("context_identity", &self.context_identity())
            .field("hardware_class", self.hardware_class())
            .field("storage_class_count", &self.storage_classes().len())
            .field("default_storage_class", self.default_storage_class())
            .field("state", &self.state)
            .finish_non_exhaustive()
    }
}

fn validate_storage_classes(
    engine_id: &EngineId,
    storage_classes: &[StorageClass],
    default_storage_class: &StorageClass,
) -> Result<(), RuntimeConfigError> {
    if storage_classes.is_empty() {
        return Err(RuntimeConfigError::EmptyStorageClasses {
            engine_id: engine_id.clone(),
        });
    }
    for duplicate_index in 0..storage_classes.len() {
        if let Some(first_index) = (0..duplicate_index)
            .find(|&first| storage_classes[first] == storage_classes[duplicate_index])
        {
            return Err(RuntimeConfigError::DuplicateStorageClass {
                engine_id: engine_id.clone(),
                storage_class: storage_classes[duplicate_index].clone(),
                first_index,
                duplicate_index,
            });
        }
    }
    if !storage_classes
        .iter()
        .any(|storage_class| storage_class == default_storage_class)
    {
        return Err(RuntimeConfigError::DefaultStorageClassNotListed {
            engine_id: engine_id.clone(),
            default_storage_class: default_storage_class.clone(),
        });
    }
    Ok(())
}