tenferro-runtime 0.7.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
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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
use std::error::Error;
use std::fmt;
use std::sync::Arc;

use super::capability::{
    CoreCapabilityKind, PreparationKeySummary, PreparedOperationBinding, UnsupportedReason,
};
use super::identity::{EngineId, ProviderDeviceIdentity, RuntimeEpoch, RuntimeId};
use super::policy::{ProgramPlacementConstraint, StorageClass, TransferEndpoint};
use super::specialization::SpecializationProjection;
use super::{CacheOwnerId, ExtensionModuleId};
use tenferro_ops::ShapeGuardError;
use tenferro_tensor::{AllocationDomainId, Error as TensorError, Placement};

/// Classifies a malformed runtime identifier without retaining its input.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::EngineId;
///
/// let error = EngineId::new("not namespaced").unwrap_err();
/// assert_eq!(error.kind(), tenferro_runtime::IdentityKind::Engine);
/// ```
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error("malformed {kind:?} identifier")]
pub struct IdentityError {
    kind: IdentityKind,
}

impl IdentityError {
    /// Return the kind of identifier that failed validation.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::{EngineId, IdentityKind};
    ///
    /// assert_eq!(EngineId::new("engine").unwrap_err().kind(), IdentityKind::Engine);
    /// ```
    pub fn kind(&self) -> IdentityKind {
        self.kind
    }

    pub(super) const fn malformed(kind: IdentityKind) -> Self {
        Self { kind }
    }
}

/// Identifies the runtime namespace validated by an opaque identifier.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::IdentityKind;
///
/// assert_eq!(IdentityKind::CacheOwner, IdentityKind::CacheOwner);
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum IdentityKind {
    /// An execution engine identifier.
    Engine,
    /// A provider identifier.
    Provider,
    /// A provider-canonical physical target identity.
    ProviderTarget,
    /// A hardware-class identifier.
    HardwareClass,
    /// A storage-class identifier.
    StorageClass,
    /// A layout-class identifier.
    LayoutClass,
    /// A runtime cache-owner identifier.
    CacheOwner,
    /// An extension module identifier.
    ExtensionModule,
}

/// Reports invalid placement constraints.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{EngineId, PlacementConstraintError, ProgramPlacementConstraint};
///
/// let engine = EngineId::new("tenferro.cpu").unwrap();
/// let error = ProgramPlacementConstraint::new(vec![engine.clone(), engine], None).unwrap_err();
/// assert!(matches!(error, PlacementConstraintError::DuplicateEngine { .. }));
/// ```
#[derive(Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PlacementConstraintError {
    /// The same engine appears more than once in a preference list.
    #[error(
        "engine {engine_id:?} is duplicated at positions \
         {first_index} and {duplicate_index}"
    )]
    DuplicateEngine {
        /// The duplicated engine identifier.
        engine_id: EngineId,
        /// The first position where the engine appeared.
        first_index: usize,
        /// The duplicate position that failed validation.
        duplicate_index: usize,
    },
}

/// Identifies a runtime registration slot involved in a configuration conflict.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use tenferro_runtime::{EngineId, RegistrationKey};
///
/// let key = RegistrationKey::Engine(EngineId::new("tenferro.cpu")?);
/// assert!(format!("{key:?}").contains("tenferro.cpu"));
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RegistrationKey {
    /// A direct engine registration.
    Engine(EngineId),
    /// An extension engine registration.
    ExtensionEngine {
        /// Extension family.
        family: &'static str,
        /// Runtime engine.
        engine: EngineId,
    },
    /// An extension planning config registration.
    ExtensionPlanning {
        /// Extension module.
        module: ExtensionModuleId,
        /// Runtime engine.
        engine: EngineId,
    },
    /// An extension cache-owner registration.
    ExtensionCacheOwner {
        /// Extension module.
        module: ExtensionModuleId,
        /// Local cache owner.
        owner: CacheOwnerId,
    },
    /// A transfer provider keyed by source and destination endpoints.
    TransferProvider {
        /// Source endpoint.
        source: TransferEndpoint,
        /// Destination endpoint.
        destination: TransferEndpoint,
    },
}

/// Reports invalid execution-policy configuration.
///
/// Phase 4 currently has no invalid public execution policy state, but the
/// error type is part of the accepted runtime configuration contract.
///
/// # Examples
///
/// ```
/// use std::fmt::Debug;
/// use tenferro_runtime::ExecutionPolicyError;
///
/// fn requires_debug<T: Debug>() {}
/// requires_debug::<ExecutionPolicyError>();
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ExecutionPolicyError {}

impl fmt::Display for ExecutionPolicyError {
    fn fmt(&self, _formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {}
    }
}

impl std::error::Error for ExecutionPolicyError {}

/// Reports invalid runtime configuration.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{EngineId, RuntimeConfigError};
///
/// let error = RuntimeConfigError::DuplicateEngine {
///     engine_id: EngineId::new("tenferro.cpu").unwrap(),
/// };
/// assert!(error.to_string().contains("already registered"));
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RuntimeConfigError {
    /// Runtime identity or registration identity allocation exhausted.
    #[error("runtime identity space exhausted")]
    IdentityExhausted,
    /// A namespaced runtime identifier was malformed.
    #[error("malformed {kind:?} identifier")]
    MalformedIdentity {
        /// Identifier class that failed validation.
        kind: IdentityKind,
    },
    /// An engine registration tried to insert a different value for an
    /// already-registered engine ID.
    #[error("engine {engine_id:?} is already registered")]
    DuplicateEngine {
        /// Duplicated engine identifier.
        engine_id: EngineId,
    },
    /// Two direct engines selected the same provider/device target.
    #[error(
        "provider/device target {provider_device_identity:?} is already bound to engine \
         {first_engine_id:?}; cannot bind engine {duplicate_engine_id:?}"
    )]
    DuplicateProviderDeviceTarget {
        /// Physical provider/device binding that was selected twice.
        provider_device_identity: ProviderDeviceIdentity,
        /// First logical engine using the binding.
        first_engine_id: EngineId,
        /// Later logical engine that attempted to reuse the binding.
        duplicate_engine_id: EngineId,
    },
    /// A replacement attempted to change the physical target of an engine ID.
    #[error(
        "engine {engine_id:?} cannot rebind from provider/device target {current:?} \
         to {replacement:?}; remove affected transfer routes, remove the old engine, \
         register the replacement under the engine ID, and re-register the routes"
    )]
    EngineTargetRebind {
        /// Logical engine whose physical binding was changed.
        engine_id: EngineId,
        /// Binding currently attached to the engine.
        current: ProviderDeviceIdentity,
        /// Binding requested by the replacement.
        replacement: ProviderDeviceIdentity,
    },
    /// A direct capability slot was registered twice where replacement is not
    /// accepted.
    #[error("duplicate {capability:?} capability")]
    DuplicateCapability {
        /// Duplicated capability kind.
        capability: CoreCapabilityKind,
    },
    /// A registration key conflicted across transactional registration input.
    #[error("conflicting registration {key:?}")]
    ConflictingRegistration {
        /// Conflicting registration key.
        key: RegistrationKey,
    },
    /// A requested engine replacement or removal had no existing record.
    #[error("engine {engine_id:?} is not registered")]
    MissingEngine {
        /// Missing engine identifier.
        engine_id: EngineId,
    },
    /// An extension module does not register a requested family for an engine.
    #[error(
        "extension module {module_id:?} family {family_id:?} has no engine registration for runtime engine {engine_id:?}"
    )]
    MissingExtensionEngine {
        /// Extension module whose engine registration is missing.
        module_id: ExtensionModuleId,
        /// Extension family whose engine registration is missing.
        family_id: &'static str,
        /// Runtime engine selected by the owner.
        engine_id: EngineId,
    },
    /// Engine registration provided no supported storage classes.
    #[error("engine {engine_id:?} has no storage classes")]
    EmptyStorageClasses {
        /// Engine being registered.
        engine_id: EngineId,
    },
    /// Engine registration repeated a storage class.
    #[error(
        "engine {engine_id:?} storage class {storage_class:?} is duplicated at \
         positions {first_index} and {duplicate_index}"
    )]
    DuplicateStorageClass {
        /// Engine being registered.
        engine_id: EngineId,
        /// Duplicated storage class.
        storage_class: StorageClass,
        /// First position where the storage class appeared.
        first_index: usize,
        /// Duplicate position that failed validation.
        duplicate_index: usize,
    },
    /// Engine registration selected a default storage class that is not in its
    /// supported list.
    #[error("engine {engine_id:?} default storage class {default_storage_class:?} is not listed")]
    DefaultStorageClassNotListed {
        /// Engine being registered.
        engine_id: EngineId,
        /// Missing default storage class.
        default_storage_class: StorageClass,
    },
    /// A transfer endpoint references an engine that is absent from the
    /// candidate configuration.
    #[error("transfer endpoint {endpoint:?} references an unregistered engine")]
    UnknownTransferEndpointEngine {
        /// Endpoint that references the missing engine.
        endpoint: TransferEndpoint,
    },
    /// A transfer endpoint names a storage class unsupported by its engine.
    #[error("transfer endpoint {endpoint:?} uses storage unsupported by its engine")]
    UnsupportedTransferEndpointStorage {
        /// Endpoint whose storage class is unsupported by its engine.
        endpoint: TransferEndpoint,
    },
    /// A transfer route removal named an endpoint pair that is not registered.
    #[error(
        "no transfer provider is registered from source endpoint {source_endpoint:?} to destination \
         endpoint {destination:?}"
    )]
    MissingTransferProvider {
        /// Source endpoint of the absent route.
        source_endpoint: TransferEndpoint,
        /// Destination endpoint of the absent route.
        destination: TransferEndpoint,
    },
    /// A route retains a physical binding that no longer matches its engine.
    #[error(
        "stale transfer route from source endpoint {source_endpoint:?} to destination endpoint \
         {destination:?}: endpoint {endpoint:?} was registered for {registered:?} but \
         now resolves to {current:?}"
    )]
    StaleTransferRoute {
        /// Source endpoint of the stale route.
        source_endpoint: TransferEndpoint,
        /// Destination endpoint of the stale route.
        destination: TransferEndpoint,
        /// Route endpoint whose physical binding changed.
        endpoint: TransferEndpoint,
        /// Binding captured when this route was registered/frozen.
        registered: Box<ProviderDeviceIdentity>,
        /// Binding currently attached to the endpoint's engine.
        current: Box<ProviderDeviceIdentity>,
    },
    /// A route reached freezing without a physical binding after validation.
    #[error(
        "transfer route from source endpoint {source_endpoint:?} to destination endpoint {destination:?} \
         has no resolved provider/device binding"
    )]
    UnboundTransferRoute {
        /// Source endpoint of the unbound route.
        source_endpoint: TransferEndpoint,
        /// Destination endpoint of the unbound route.
        destination: TransferEndpoint,
    },
    /// A bound candidate referenced an engine that disappeared before freeze;
    /// this indicates runtime corruption rather than candidate validation.
    #[error("bound candidate invariant failed for transfer endpoint {endpoint:?}")]
    BoundCandidateInvariant {
        /// Endpoint whose already-bound engine lookup failed.
        endpoint: TransferEndpoint,
    },
    /// An execution bridge omitted the validators required for explicit input
    /// ingress and destination-buffer residency.
    #[error("engine {engine_id:?} execution bridge has no complete input ingress validator")]
    MissingInputIngressValidator {
        /// Engine with the incomplete execution contract.
        engine_id: EngineId,
    },
    /// A replacement attempted to reuse an engine ID with a different execution
    /// context identity in a context where that is invalid.
    #[error("engine {engine_id:?} context identity mismatch")]
    ContextIdentityMismatch {
        /// Engine with the mismatched context identity.
        engine_id: EngineId,
    },
    /// Execution policy failed validation.
    #[error("invalid execution policy: {reason}")]
    InvalidExecutionPolicy {
        /// Typed policy validation reason.
        reason: ExecutionPolicyError,
    },
    /// Extension module transaction failed.
    #[error("extension module registration failed")]
    ExtensionModule {
        /// Typed extension module source.
        #[source]
        source: ExtensionModuleError,
    },
}

/// Reports a runtime execution bridge that violated its output contract.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{EngineExecutionContractError, EngineId, StorageClass};
///
/// let error = EngineExecutionContractError::OutputResidencyMismatch {
///     instruction_index: 3,
///     output_slot: 7,
///     engine_id: EngineId::new("tenferro.cpu")?,
///     storage_class: StorageClass::new("tenferro.storage.host")?,
///     backend_family: Some("foreign-backend"),
///     allocation_domain: None,
/// };
/// assert!(error.to_string().contains("output slot 7"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum EngineExecutionContractError {
    /// An executor returned a tensor not owned by its scheduled engine/storage.
    #[error(
        "instruction {instruction_index} output slot {output_slot} is not resident in \
         engine {engine_id:?} storage {storage_class:?} \
         (backend family {backend_family:?}, allocation domain {allocation_domain:?})"
    )]
    OutputResidencyMismatch {
        /// Execution-program instruction that produced the invalid tensor.
        instruction_index: usize,
        /// Execution slot containing the invalid tensor.
        output_slot: usize,
        /// Engine selected by the prepared schedule.
        engine_id: EngineId,
        /// Storage class selected by the prepared schedule.
        storage_class: StorageClass,
        /// Physical backend family reported by the tensor.
        backend_family: Option<&'static str>,
        /// Physical allocation domain reported by the tensor.
        allocation_domain: Option<AllocationDomainId>,
    },
}

/// Reports a runtime input that violates a prepared ingress contract.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{EngineId, InputIngressContractError, StorageClass};
/// use tenferro_tensor::Placement;
///
/// let error = InputIngressContractError::ResidencyMismatch {
///     input_slot: 0,
///     ingress_engine_id: EngineId::new("tenferro.cpu")?,
///     ingress_storage_class: StorageClass::new("tenferro.storage.host")?,
///     placement: Placement::default(),
///     backend_family: Some("foreign-backend"),
///     allocation_domain: None,
/// };
/// assert!(error.to_string().contains("input slot 0"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum InputIngressContractError {
    /// A runtime input's physical residency is incompatible with its prepared ingress.
    #[error(
        "input slot {input_slot} at placement {placement:?} with backend family \
         {backend_family:?} and allocation domain {allocation_domain:?} is not accepted by \
         ingress engine {ingress_engine_id:?} storage {ingress_storage_class:?}"
    )]
    ResidencyMismatch {
        /// Execution slot containing the rejected runtime input.
        input_slot: usize,
        /// Engine selected as the prepared input ingress.
        ingress_engine_id: EngineId,
        /// Storage class selected as the prepared input ingress.
        ingress_storage_class: StorageClass,
        /// Logical placement reported by the input.
        placement: Placement,
        /// Physical backend family reported by the input.
        backend_family: Option<&'static str>,
        /// Physical allocation domain reported by the input.
        allocation_domain: Option<AllocationDomainId>,
    },
}

/// Reports failure to admit an asynchronous runtime submission.
///
/// # Examples
///
/// ```
/// use std::io;
/// use tenferro_runtime::SubmissionError;
///
/// let error = SubmissionError::WorkerSpawn {
///     source: io::Error::other("worker unavailable"),
/// };
/// assert!(error.to_string().contains("spawn"));
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SubmissionError {
    /// The runtime could not create the worker after synchronous preparation.
    #[error("failed to spawn runtime submission worker")]
    WorkerSpawn {
        /// Operating-system thread creation failure.
        #[source]
        source: std::io::Error,
    },
}

impl From<IdentityError> for RuntimeConfigError {
    fn from(source: IdentityError) -> Self {
        Self::MalformedIdentity {
            kind: source.kind(),
        }
    }
}

/// Reports failure to publish a runtime reconfiguration.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{RuntimeConfigError, RuntimeReconfigureError};
///
/// let error = RuntimeReconfigureError::Edit {
///     source: RuntimeConfigError::IdentityExhausted,
/// };
/// assert!(std::error::Error::source(&error).is_some());
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RuntimeReconfigureError {
    /// Runtime state could not be read or published.
    #[error("runtime state failed")]
    State {
        /// Typed state source.
        #[source]
        source: super::RuntimeStateError,
    },
    /// The edit closure or publication validation rejected the candidate.
    #[error("runtime reconfiguration edit failed")]
    Edit {
        /// Typed configuration source.
        #[source]
        source: RuntimeConfigError,
    },
    /// Another writer published over the snapshot this edit was based on.
    #[error("runtime was concurrently reconfigured from {base:?} to {current:?}")]
    ConcurrentReconfiguration {
        /// Epoch captured before the edit closure ran.
        base: RuntimeEpoch,
        /// Epoch observed at publication time.
        current: RuntimeEpoch,
    },
    /// Runtime epoch cannot advance without wrapping.
    #[error("runtime epoch exhausted at {current:?}")]
    EpochExhausted {
        /// Current maximum epoch.
        current: RuntimeEpoch,
    },
}

/// Reports invalid extension module registration transactions.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use tenferro_runtime::{EngineId, ExtensionModuleError, ExtensionModuleId};
///
/// let error = ExtensionModuleError::MissingPlanningConfig {
///     module_id: ExtensionModuleId::new("tenferro.module.test")?,
///     engine_id: EngineId::new("tenferro.engine.test")?,
/// };
/// assert!(error.to_string().contains("planning config"));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ExtensionModuleError {
    /// A distinct module is already installed at the same module ID.
    #[error("extension module {module_id:?} is already installed")]
    ConflictingModule {
        /// Conflicting module ID.
        module_id: ExtensionModuleId,
    },
    /// A distinct extension engine is already registered for the same
    /// `(family, engine)` key.
    #[error("extension module {module_id:?} has conflicting engine {family_id:?}/{engine_id:?}")]
    ConflictingEngine {
        /// Extension module ID.
        module_id: ExtensionModuleId,
        /// Extension family ID.
        family_id: &'static str,
        /// Runtime engine ID.
        engine_id: EngineId,
    },
    /// A planning config was registered without exactly one matching engine.
    #[error(
        "extension module {module_id:?} registered planning config without engine {engine_id:?}"
    )]
    PlanningConfigWithoutEngine {
        /// Extension module ID.
        module_id: ExtensionModuleId,
        /// Runtime engine ID.
        engine_id: EngineId,
    },
    /// Planning config family did not match the registered engine family.
    #[error(
        "extension module {module_id:?} config for engine {engine_id:?} has family \
         {actual:?}, expected {expected:?}"
    )]
    PlanningConfigFamilyMismatch {
        /// Extension module ID.
        module_id: ExtensionModuleId,
        /// Runtime engine ID.
        engine_id: EngineId,
        /// Expected extension family ID.
        expected: &'static str,
        /// Actual extension family ID.
        actual: &'static str,
    },
    /// An engine was registered without its required planning config.
    #[error("extension module {module_id:?} engine {engine_id:?} has no planning config")]
    MissingPlanningConfig {
        /// Extension module ID.
        module_id: ExtensionModuleId,
        /// Runtime engine ID.
        engine_id: EngineId,
    },
    /// A distinct planning config is already registered for the same engine.
    #[error("extension module {module_id:?} has conflicting planning config for {engine_id:?}")]
    ConflictingPlanningConfig {
        /// Extension module ID.
        module_id: ExtensionModuleId,
        /// Runtime engine ID.
        engine_id: EngineId,
    },
    /// A distinct cache owner is already registered for the same local owner ID.
    #[error("extension module {module_id:?} has conflicting cache owner {owner:?}")]
    ConflictingCacheOwner {
        /// Extension module ID.
        module_id: ExtensionModuleId,
        /// Local cache owner ID.
        owner: CacheOwnerId,
    },
}

/// Reports failures while building value-free input signatures.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{DType, InputSignatureEntry, LayoutClass};
/// use tenferro_tensor::Placement;
///
/// let error = InputSignatureEntry::new(
///     DType::F64,
///     [2_usize].into_iter().collect(),
///     Placement::default(),
///     LayoutClass::new("tenferro.layout.strided").unwrap(),
///     [1_isize, 2].into_iter().collect(),
///     None,
/// )
/// .unwrap_err();
/// assert!(matches!(error, tenferro_runtime::InputSignatureError::ShapeStrideRankMismatch { .. }));
/// ```
#[derive(Debug, thiserror::Error)]
pub enum InputSignatureError {
    /// Shape rank and stride rank disagree.
    #[error("shape rank {rank} does not match stride count {stride_count}")]
    ShapeStrideRankMismatch {
        /// Number of shape axes.
        rank: usize,
        /// Number of stride axes.
        stride_count: usize,
    },
    /// The alignment class is outside the finite `usize` alignment lattice.
    #[error("alignment class {alignment_log2} is outside the usize alignment lattice")]
    InvalidAlignmentClass {
        /// Base-2 logarithm of the requested alignment.
        alignment_log2: u8,
    },
    /// Tensor metadata could not be read for an input.
    #[error("input {input} metadata is unavailable")]
    TensorMetadata {
        /// Input position in the prepare request.
        input: usize,
        /// Original typed tensor error.
        source: TensorError,
    },
}

/// Explains why rank specialization is required by a requested field.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::RankRequirement;
///
/// assert_eq!(RankRequirement::ExactStrides.to_string(), "exact strides");
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum RankRequirement {
    /// A concrete axis dimension was requested.
    ConcreteAxis {
        /// Axis that requires rank specialization.
        axis: u32,
    },
    /// Exact strides were requested.
    ExactStrides,
}

impl std::fmt::Display for RankRequirement {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ConcreteAxis { axis } => write!(formatter, "concrete axis {axis}"),
            Self::ExactStrides => formatter.write_str("exact strides"),
        }
    }
}

/// Reports invalid input-specialization requirements.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{
///     InputSpecializationRequirements, InputSpecializationRequirementsError, RankRequirement,
/// };
///
/// let mut builder = InputSpecializationRequirements::builder();
/// builder.rank(false).concrete_dimensions(vec![2]);
/// assert_eq!(
///     builder.build().unwrap_err(),
///     InputSpecializationRequirementsError::RankRequired {
///         reason: RankRequirement::ConcreteAxis { axis: 2 },
///     }
/// );
/// ```
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum InputSpecializationRequirementsError {
    /// The same concrete axis appears more than once.
    #[error("axis {axis} is duplicated at positions {first_index} and {duplicate_index}")]
    DuplicateAxis {
        /// Duplicated concrete axis.
        axis: u32,
        /// First position carrying the axis.
        first_index: usize,
        /// Duplicate position that failed validation.
        duplicate_index: usize,
    },
    /// A requested specialization field requires rank specialization.
    #[error("{reason} requires rank specialization")]
    RankRequired {
        /// Requirement that needs rank specialization.
        reason: RankRequirement,
    },
    /// The alignment class is outside the finite `usize` alignment lattice.
    #[error("alignment class {alignment_log2} is outside the usize alignment lattice")]
    InvalidAlignmentClass {
        /// Base-2 logarithm of the requested alignment.
        alignment_log2: u8,
    },
}

/// Reports failures while projecting signatures through specialization requirements.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{InputSignature, SpecializationRequirements};
///
/// let error = SpecializationRequirements::polymorphic(1)
///     .project(&InputSignature::new(Vec::new()))
///     .unwrap_err();
/// assert!(matches!(error, tenferro_runtime::PrepareError::Specialization { .. }));
/// ```
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum SpecializationError {
    /// The signature does not have the required input arity.
    #[error("expected {expected} inputs but got {actual}")]
    WrongInputCount {
        /// Required input count.
        expected: usize,
        /// Actual input count.
        actual: usize,
    },
    /// A concrete-axis request names an axis outside the actual rank.
    #[error("input {input} axis {axis} is outside rank {rank}")]
    AxisOutOfRange {
        /// Input position in the signature.
        input: usize,
        /// Requested axis.
        axis: u32,
        /// Actual rank.
        rank: usize,
    },
    /// A required host-pointer alignment class is unavailable.
    #[error("input {input} has unknown alignment; required class {required_alignment_log2}")]
    AlignmentUnavailable {
        /// Input position in the signature.
        input: usize,
        /// Required base-2 logarithm alignment class.
        required_alignment_log2: u8,
    },
    /// A specialization projection could not encode every requested axis in
    /// the finite public axis type.
    #[error("input {input} rank {rank} is too large to project into u32 axes")]
    ProjectionOverflow {
        /// Input position in the signature.
        input: usize,
        /// Rank that could not be encoded.
        rank: usize,
    },
}

/// A typed execution-context mismatch from erased runtime dispatch.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{ExecutionContextIdentity, ExecutionContextMismatch};
///
/// let error = ExecutionContextMismatch {
///     expected: ExecutionContextIdentity::of::<u64>(),
///     actual: ExecutionContextIdentity::of::<u32>(),
/// };
/// assert_eq!(error.expected, ExecutionContextIdentity::of::<u64>());
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("execution context mismatch: expected {expected:?}, actual {actual:?}")]
pub struct ExecutionContextMismatch {
    /// Expected execution-context type identity.
    pub expected: super::ExecutionContextIdentity,
    /// Actual stored execution-context type identity.
    pub actual: super::ExecutionContextIdentity,
}

/// Reports provider violations of runtime preparation contracts.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{CoreCapabilityKind, ProviderContractError};
///
/// let error = ProviderContractError::WrongOperationFamily {
///     expected: CoreCapabilityKind::Elementwise,
///     operation: "dot_general",
/// };
/// assert!(error.to_string().contains("dot_general"));
/// ```
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum ProviderContractError {
    /// A provider accepted a request from the wrong core operation family.
    #[error("operation {operation:?} is not in {expected:?}")]
    WrongOperationFamily {
        /// Expected core capability family.
        expected: CoreCapabilityKind,
        /// Operation diagnostic name.
        operation: &'static str,
    },
    /// A prepared operation returned a different binding than requested.
    #[error("prepared binding mismatch")]
    BindingMismatch {
        /// Runtime-created binding requested from the provider.
        expected: Box<PreparedOperationBinding>,
        /// Binding returned by the provider.
        actual: Box<PreparedOperationBinding>,
    },
    /// A prepared operation returned a different specialization projection.
    #[error("prepared specialization projection mismatch")]
    ProjectionMismatch {
        /// Runtime-created projection requested from the provider.
        expected: Box<SpecializationProjection>,
        /// Projection returned by the provider.
        actual: Box<SpecializationProjection>,
    },
    /// A provider returned an invalid specialization.
    #[error("invalid provider specialization: {source}")]
    InvalidSpecialization {
        /// Original specialization failure.
        #[source]
        source: SpecializationError,
    },
    /// A provider requested specialization that did not strictly widen the
    /// current requirements.
    #[error("specialization did not strictly widen the current requirements")]
    NonWideningSpecialization {
        /// Previous specialization requirements.
        previous: Box<super::SpecializationRequirements>,
        /// Provider-requested specialization requirements.
        next: Box<super::SpecializationRequirements>,
    },
    /// A provider exceeded the finite specialization retry bound.
    #[error("specialization retry limit exceeded after {attempts} attempts; limit was {limit}")]
    SpecializationRetryLimitExceeded {
        /// Number of redirect attempts observed.
        attempts: usize,
        /// Computed finite retry bound.
        limit: usize,
    },
}

/// Reports failures while preparing runtime execution artifacts.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{InputSignature, PrepareError, SpecializationRequirements};
///
/// let error = SpecializationRequirements::polymorphic(1)
///     .project(&InputSignature::new(Vec::new()))
///     .unwrap_err();
/// assert!(matches!(error, PrepareError::Specialization { .. }));
/// ```
#[derive(Debug, thiserror::Error)]
pub enum PrepareError {
    /// Prepared artifact belongs to a different runtime.
    #[error("runtime mismatch: expected {expected:?}, actual {actual:?}")]
    RuntimeMismatch {
        /// Runtime expected by the prepared artifact.
        expected: RuntimeId,
        /// Runtime currently executing.
        actual: RuntimeId,
    },
    /// Prepared artifact was created for a stale runtime epoch.
    #[error("stale runtime epoch: prepared {prepared:?}, current {current:?}")]
    StaleEpoch {
        /// Epoch captured by the prepared artifact.
        prepared: RuntimeEpoch,
        /// Runtime's current epoch.
        current: RuntimeEpoch,
    },
    /// Input signature construction failed.
    #[error("input signature failed")]
    InputSignature {
        /// Typed source error.
        source: InputSignatureError,
    },
    /// Semantic shape guards failed.
    #[error("shape guard failed")]
    ShapeGuard {
        /// Typed source error.
        #[source]
        source: ShapeGuardError,
    },
    /// Signature projection through specialization requirements failed.
    #[error("specialization failed")]
    Specialization {
        /// Typed source error.
        source: SpecializationError,
    },
    /// No eligible engine matched the placement and capability constraints.
    #[error("no eligible engine for {constraint:?}")]
    NoEligibleEngine {
        /// Placement constraint that could not be satisfied.
        constraint: ProgramPlacementConstraint,
    },
    /// A preparation-only engine advertised the required capability but cannot
    /// produce an executable prepared schedule.
    #[error(
        "engine {engine_id:?} has a matching preparation capability but no executable binding"
    )]
    NoExecutableEngine {
        /// Engine whose preparation capability cannot be used for execution.
        engine_id: EngineId,
    },
    /// The compiled graph uses an extension family absent from the runtime.
    #[error("missing extension family {family_id:?}")]
    MissingExtension {
        /// Stable extension family identifier.
        family_id: &'static str,
    },
    /// No eligible engine declared an ingress compatible with an input placement.
    #[error("no eligible input ingress for input {input_index} at placement {placement:?}")]
    NoInputIngress {
        /// Input position in the compiled-program signature.
        input_index: usize,
        /// Placement rejected by every eligible engine ingress.
        placement: tenferro_tensor::Placement,
    },
    /// Placement resolution exceeded its bounded combination-search budget.
    #[error(
        "placement resolution exhausted its search budget after {attempts} attempts \
         (limit {limit})"
    )]
    DispatchSearchBudgetExceeded {
        /// Number of dispatch combinations attempted.
        attempts: usize,
        /// Configured hard limit for this search.
        limit: usize,
    },
    /// No available copy of a value has a registered direct transfer provider
    /// to the storage required by its consumer.
    #[error(
        "instruction {instruction_index} has no direct transfer provider for value slot \
         {value_slot} from {available_source_endpoints:?} to {destination_endpoint:?}"
    )]
    MissingTransferProvider {
        /// Staged instruction whose input cannot be reached.
        instruction_index: usize,
        /// Value slot required by the instruction.
        value_slot: usize,
        /// Destination endpoint required by the instruction.
        destination_endpoint: TransferEndpoint,
        /// Endpoints retaining an available copy.
        available_source_endpoints: Vec<TransferEndpoint>,
    },
    /// A resolved placement references an engine absent from its preparation snapshot.
    #[error("resolved engine {engine_id:?} is unavailable in the preparation snapshot")]
    ResolvedEngineUnavailable {
        /// Engine referenced by the resolved placement.
        engine_id: EngineId,
    },
    /// No provider supports this operation under the requested constraints.
    #[error("operation is unsupported: {reason}")]
    Unsupported {
        /// Deterministic unsupported reason.
        reason: UnsupportedReason,
    },
    /// Deterministic execution was requested from an engine that cannot provide it.
    #[error("determinism unsupported by engine {engine_id:?}")]
    DeterminismUnsupported {
        /// Engine that cannot satisfy deterministic preparation.
        engine_id: EngineId,
    },
    /// Provider returned a value that violates the runtime preparation contract.
    #[error("provider contract violation: {source}")]
    ProviderContract {
        /// Typed provider-contract source.
        #[source]
        source: ProviderContractError,
    },
    /// Preparation recursion reached an unsupported cycle.
    #[error("preparation cycle at {key:?}")]
    PreparationCycle {
        /// Bounded summary of the recursive key.
        key: PreparationKeySummary,
    },
    /// Preparation recursively requested a different key.
    #[error("nested preparation unsupported: parent {parent:?}, requested {requested:?}")]
    NestedPreparationUnsupported {
        /// Parent key currently preparing on this thread.
        parent: PreparationKeySummary,
        /// Nested key requested by the producer.
        requested: PreparationKeySummary,
    },
    /// The preparation cache is full of active/queued distinct keys.
    #[error(
        "preparation cache is at capacity: {in_flight} in flight and \
         {queued_distinct_keys} queued distinct keys"
    )]
    CacheInFlightCapacityExceeded {
        /// Active distinct preparations.
        in_flight: usize,
        /// Queued distinct keys.
        queued_distinct_keys: usize,
    },
    /// Runtime cache state could not be accessed.
    #[error("preparation cache state unavailable: {source}")]
    CacheState {
        /// Runtime state source.
        #[source]
        source: super::RuntimeStateError,
    },
    /// Engine or internal preparation source failed.
    #[error("engine preparation failed: {source}")]
    Engine {
        /// Shared typed source.
        #[source]
        source: Arc<dyn Error + Send + Sync>,
    },
}