eredu-runtime 0.5.0

Backend-neutral model execution runtime for Eredu
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
//! Family-blind construction of a selected layered realtime model.

use std::{collections::BTreeMap, marker::PhantomData};

use eredu_checkpoint::recipe::{DerivedWeightRecipe, RecipeMetadata};
use eredu_nn::{NeuralBackend, Tensor};

use crate::{
    LayerWeightResidency, LayeredArchitecture, LayerwisePolicy, LayerwiseRuntime, ParameterBackend,
    ParameterGroupOwner, RealtimeWeightComponentRequirement, RealtimeWeightComponentRole,
    RealtimeWeightLoweringRequirement, RuntimeState, SelectedRealtimeRealization,
    SubmissionBackend, WeightBinding, WeightBindingPlan,
};

/// Architecture-issued identities that bind concrete modules to one selection.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct RealtimeArchitectureConstructionIdentity {
    architecture: crate::RealtimeIdentity,
    speech_schedule: crate::RealtimeIdentity,
    state_layout: crate::RealtimeIdentity,
}

impl RealtimeArchitectureConstructionIdentity {
    /// Creates one exact construction witness.
    pub fn new(
        architecture: crate::RealtimeIdentity,
        speech_schedule: crate::RealtimeIdentity,
        state_layout: crate::RealtimeIdentity,
    ) -> Self {
        Self {
            architecture,
            speech_schedule,
            state_layout,
        }
    }
}

/// Supplies stable semantic identities for a concrete neutral architecture.
pub trait RealtimeArchitectureIdentity {
    /// Returns the identities derived from the architecture's normalized policy.
    fn realtime_construction_identity(
        &self,
    ) -> Result<RealtimeArchitectureConstructionIdentity, String>;
}

/// Concrete state paired with the exact realization its mechanism implemented.
pub struct RealizedRealtimeState<S> {
    state: S,
    realization: crate::SelectedRealtimeStateRealization,
}

impl<S> RealizedRealtimeState<S> {
    /// Attaches an exact state realization report to concrete storage.
    pub fn new(state: S, realization: crate::SelectedRealtimeStateRealization) -> Self {
        Self { state, realization }
    }

    /// Consumes concrete state and its exact realization report.
    pub fn into_parts(self) -> (S, crate::SelectedRealtimeStateRealization) {
        (self.state, self.realization)
    }
}

/// Concrete layer storage paired with the exact residency it implemented.
pub struct RealizedRealtimePolicy<P> {
    policy: P,
    residency: LayerWeightResidency,
}

impl<P> RealizedRealtimePolicy<P> {
    /// Attaches the implemented residency report to a concrete policy.
    pub fn new(policy: P, residency: LayerWeightResidency) -> Self {
        Self { policy, residency }
    }

    /// Consumes concrete storage and its exact residency report.
    pub fn into_parts(self) -> (P, LayerWeightResidency) {
        (self.policy, self.residency)
    }
}

/// One selected component paired with its exact architecture recipe payload.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct RealtimeMaterializationComponent {
    requirement: RealtimeWeightComponentRequirement,
    source_provenance: Vec<eredu_checkpoint::store::TensorSourceProvenance>,
}

impl RealtimeMaterializationComponent {
    /// Pairs an exact selected component with its admission-time physical sources.
    pub fn new(
        requirement: RealtimeWeightComponentRequirement,
        source_provenance: impl IntoIterator<Item = eredu_checkpoint::store::TensorSourceProvenance>,
    ) -> Result<Self, RealtimeModelContractError> {
        let source_provenance = source_provenance.into_iter().collect::<Vec<_>>();
        if requirement.source_occurrences().len() != source_provenance.len()
            || requirement
                .source_occurrences()
                .iter()
                .zip(&source_provenance)
                .any(|(expected, actual)| expected.as_str() != actual.catalog_key)
        {
            return Err(RealtimeModelContractError::SourceProvenanceMismatch {
                target: requirement.target().as_str().to_owned(),
            });
        }
        Ok(Self {
            requirement,
            source_provenance,
        })
    }

    /// Returns the exact selected component requirement.
    pub const fn requirement(&self) -> &RealtimeWeightComponentRequirement {
        &self.requirement
    }

    /// Returns the architecture recipe for a source-backed component.
    pub const fn recipe(&self) -> Option<&DerivedWeightRecipe> {
        self.requirement.recipe()
    }

    /// Returns admission-time recipe output metadata.
    pub const fn recipe_output(&self) -> Option<&RecipeMetadata> {
        self.requirement.recipe_output()
    }

    /// Returns exact physical source provenance in recipe traversal order.
    pub fn source_provenance(&self) -> &[eredu_checkpoint::store::TensorSourceProvenance] {
        &self.source_provenance
    }
}

/// Exact materialization work for one selected logical parameter target.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct RealtimeMaterializationTask {
    lowering: RealtimeWeightLoweringRequirement,
    owner: ParameterGroupOwner,
    components: Vec<RealtimeMaterializationComponent>,
}

impl RealtimeMaterializationTask {
    /// Creates a task whose recipe payload exactly covers the selected components.
    pub fn new(
        lowering: RealtimeWeightLoweringRequirement,
        owner: ParameterGroupOwner,
        components: impl IntoIterator<Item = RealtimeMaterializationComponent>,
    ) -> Result<Self, RealtimeModelContractError> {
        let components = components.into_iter().collect::<Vec<_>>();
        let expected = lowering.components();
        if components.len() != expected.len()
            || components
                .iter()
                .zip(expected)
                .any(|(actual, expected)| actual.requirement() != expected)
        {
            return Err(RealtimeModelContractError::ComponentCoverageMismatch {
                target: lowering.target().as_str().to_owned(),
            });
        }
        let primary = components
            .iter()
            .find(|component| {
                component.requirement().role() == RealtimeWeightComponentRole::Primary
            })
            .expect("selected lowering validation guarantees one primary component");
        if primary
            .recipe_output()
            .is_some_and(|output| output.shape != lowering.descriptor().physical_shape())
        {
            return Err(RealtimeModelContractError::RecipeGeometryMismatch {
                target: lowering.target().as_str().to_owned(),
            });
        }
        if let (Some(output), eredu_checkpoint::SourceTensorEncoding::Safetensors(stored)) =
            (primary.recipe_output(), lowering.descriptor().source())
        {
            if output.dtype != eredu_checkpoint::recipe::RecipeDtype::from(stored.clone()) {
                return Err(RealtimeModelContractError::RecipeEncodingMismatch {
                    target: lowering.target().as_str().to_owned(),
                });
            }
        }
        Ok(Self {
            lowering,
            owner,
            components,
        })
    }

    /// Returns the selected lowering and target identity.
    pub const fn lowering(&self) -> &RealtimeWeightLoweringRequirement {
        &self.lowering
    }

    /// Returns the exact static or execution-unit owner.
    pub const fn owner(&self) -> &ParameterGroupOwner {
        &self.owner
    }

    /// Returns ordered primary and companion recipe payloads.
    pub fn components(&self) -> &[RealtimeMaterializationComponent] {
        &self.components
    }
}

/// Canonical owner-partitioned bindings derived from exact realtime tasks.
#[derive(Debug, Clone)]
pub struct RealtimeTaskBindingPlan {
    pinned: Vec<WeightBinding>,
    units: BTreeMap<ParameterGroupOwner, Vec<WeightBinding>>,
}

impl RealtimeTaskBindingPlan {
    /// Consumes the pinned and execution-unit binding partitions.
    pub fn into_parts(
        self,
    ) -> (
        Vec<WeightBinding>,
        BTreeMap<ParameterGroupOwner, Vec<WeightBinding>>,
    ) {
        (self.pinned, self.units)
    }
}

/// Validates every exact realtime task and backend recipe capability without payload access.
///
/// This gate is valid against the original checkpoint even when later transform
/// work publishes authoritative packed outputs.
pub fn preflight_realtime_materialization_tasks<B: ParameterBackend>(
    tasks: &[RealtimeMaterializationTask],
    source: &dyn eredu_checkpoint::store::CheckpointSource,
) -> Result<(), RealtimeModelContractError> {
    for task in tasks {
        let transformed = matches!(
            task.lowering().kind(),
            crate::WeightLoweringKind::Transform | crate::WeightLoweringKind::DerivedTransform
        );
        let targets = task
            .components()
            .iter()
            .map(|component| component.requirement().target().as_str())
            .collect::<std::collections::BTreeSet<_>>();
        for component in task.components() {
            for admitted in component.source_provenance() {
                let actual = source
                    .source_provenance(&admitted.catalog_key)
                    .map_err(|error| RealtimeModelContractError::BindingPlan {
                        detail: error.to_string(),
                    })?;
                if &actual != admitted {
                    return Err(RealtimeModelContractError::BindingPlan {
                        detail: format!(
                            "realtime component {:?} differs from admitted source provenance",
                            component.requirement().target().as_str()
                        ),
                    });
                }
            }
            if let Some(owner) = component.requirement().recipe_owner() {
                if owner != component.requirement().target() && !targets.contains(owner.as_str()) {
                    return Err(RealtimeModelContractError::BindingPlan {
                        detail: format!("realtime alias owner {:?} is absent", owner.as_str()),
                    });
                }
            }
            if let Some(recipe) = component.recipe() {
                let actual = recipe.infer(source).map_err(|error| {
                    RealtimeModelContractError::BindingPlan {
                        detail: error.to_string(),
                    }
                })?;
                if component.recipe_output() != Some(&actual) {
                    return Err(RealtimeModelContractError::BindingPlan {
                        detail: format!(
                            "realtime component {:?} recipe output drifted",
                            component.requirement().target().as_str()
                        ),
                    });
                }
                B::preflight_recipe(recipe, source).map_err(|error| {
                    RealtimeModelContractError::BindingPlan {
                        detail: error.to_string(),
                    }
                })?;
            } else if component.requirement().recipe_owner().is_none() && !transformed {
                return Err(RealtimeModelContractError::BindingPlan {
                    detail: format!(
                        "realtime component {:?} has neither recipe nor alias owner",
                        component.requirement().target().as_str()
                    ),
                });
            }
        }
    }
    Ok(())
}

/// Derives the singular canonical binding partitions from exact realtime tasks.
pub fn realtime_task_binding_plan(
    tasks: &[RealtimeMaterializationTask],
    source: &dyn eredu_checkpoint::store::CheckpointSource,
) -> Result<RealtimeTaskBindingPlan, RealtimeModelContractError> {
    let mut pinned = Vec::new();
    let mut units = BTreeMap::<ParameterGroupOwner, Vec<WeightBinding>>::new();
    for task in tasks {
        let destination = match task.owner() {
            ParameterGroupOwner::StaticRole(_) | ParameterGroupOwner::StaticAnyOf(_) => &mut pinned,
            ParameterGroupOwner::ExecutionUnit { .. } => {
                units.entry(task.owner().clone()).or_default()
            }
        };
        let transformed = matches!(
            task.lowering().kind(),
            crate::WeightLoweringKind::Transform | crate::WeightLoweringKind::DerivedTransform
        );
        for component in task.components() {
            let requirement = component.requirement();
            let target = requirement.target().as_str();
            let binding = if transformed {
                if !source.is_authoritative_materialized_key(target) {
                    return Err(RealtimeModelContractError::BindingPlan {
                        detail: format!(
                            "transformed realtime output {target:?} is not authoritative"
                        ),
                    });
                }
                let metadata = source.source_metadata(target).map_err(|error| {
                    RealtimeModelContractError::BindingPlan {
                        detail: error.to_string(),
                    }
                })?;
                WeightBinding::new(
                    target,
                    target,
                    eredu_checkpoint::store::TensorSelection::Full,
                    metadata.encoded_byte_len,
                )
            } else {
                let output = component.recipe_output().ok_or_else(|| {
                    RealtimeModelContractError::BindingPlan {
                        detail: format!("realtime recipe component {target:?} has no output"),
                    }
                })?;
                match requirement.recipe_owner() {
                    Some(owner) if owner != requirement.target() => {
                        WeightBinding::alias(target, owner.as_str(), output.byte_len())
                    }
                    _ => WeightBinding::from_recipe(
                        target,
                        component.recipe().cloned().ok_or_else(|| {
                            RealtimeModelContractError::BindingPlan {
                                detail: format!("realtime component {target:?} has no recipe"),
                            }
                        })?,
                        output.byte_len(),
                    ),
                }
            }
            .map_err(|error| RealtimeModelContractError::BindingPlan {
                detail: error.to_string(),
            })?
            .with_logical_target(task.lowering().target().as_str())
            .map_err(|error| RealtimeModelContractError::BindingPlan {
                detail: error.to_string(),
            })?;
            destination.push(binding);
        }
    }
    WeightBindingPlan::new(&pinned).map_err(|error| RealtimeModelContractError::BindingPlan {
        detail: error.to_string(),
    })?;
    for bindings in units.values() {
        WeightBindingPlan::new(bindings).map_err(|error| {
            RealtimeModelContractError::BindingPlan {
                detail: error.to_string(),
            }
        })?;
    }
    Ok(RealtimeTaskBindingPlan { pinned, units })
}

/// Selected realization paired with complete architecture recipe payloads.
#[derive(Debug)]
pub struct PreparedRealtimeModelContract {
    selected: SelectedRealtimeRealization,
    tasks: Vec<RealtimeMaterializationTask>,
}

impl PreparedRealtimeModelContract {
    /// Validates that one exact task exists for every selected target.
    pub fn new(
        selected: SelectedRealtimeRealization,
        tasks: impl IntoIterator<Item = RealtimeMaterializationTask>,
    ) -> Result<Self, RealtimeModelContractError> {
        let tasks = tasks.into_iter().collect::<Vec<_>>();
        if tasks.len() != selected.weight_lowerings().len() {
            return Err(RealtimeModelContractError::TaskCoverageMismatch);
        }
        for (task, selected_lowering) in tasks.iter().zip(selected.weight_lowerings()) {
            if selected_lowering != &task.lowering {
                return Err(RealtimeModelContractError::TaskSelectionMismatch {
                    target: task.lowering.target().as_str().to_owned(),
                });
            }
            let expected_owner = selected
                .execution_parameters()
                .groups()
                .iter()
                .find_map(|group| {
                    group
                        .group()
                        .members()
                        .iter()
                        .any(|member| member.target() == task.lowering.target().as_str())
                        .then(|| group.owner())
                })
                .ok_or_else(|| RealtimeModelContractError::TaskOwnerUnavailable {
                    target: task.lowering.target().as_str().to_owned(),
                })?;
            if expected_owner != &task.owner {
                return Err(RealtimeModelContractError::TaskOwnerMismatch {
                    target: task.lowering.target().as_str().to_owned(),
                });
            }
        }
        Ok(Self { selected, tasks })
    }

    /// Returns the authoritative selected realization.
    pub const fn selected(&self) -> &SelectedRealtimeRealization {
        &self.selected
    }

    /// Returns exact materialization work in architecture order.
    pub fn tasks(&self) -> &[RealtimeMaterializationTask] {
        &self.tasks
    }

    /// Consumes the contract into selection and exact work.
    pub fn into_parts(
        self,
    ) -> (
        SelectedRealtimeRealization,
        Vec<RealtimeMaterializationTask>,
    ) {
        (self.selected, self.tasks)
    }
}

/// Generic mechanisms used only to materialize and store a selected model.
pub trait RealtimeModelConstructionMechanisms<A, B>
where
    B: SubmissionBackend<Executor = <<B as NeuralBackend>::Tensor as Tensor>::Context>,
    A: LayeredArchitecture<B, Self::State>,
    Self::State: RuntimeState<B>,
    Self::ResidentPolicy: LayerwisePolicy<B, A::Unit, Error = Self::PolicyError>,
    Self::BoundedPolicy: LayerwisePolicy<B, A::Unit, Error = Self::PolicyError>,
{
    /// Concrete architecture state realization.
    type State: RuntimeState<B>;
    /// Shared resident/bounded policy failure.
    type PolicyError;
    /// Fully resident unit storage.
    type ResidentPolicy: LayerwisePolicy<B, A::Unit, Error = Self::PolicyError>;
    /// Host-windowed or disk-streamed unit storage.
    type BoundedPolicy: LayerwisePolicy<B, A::Unit, Error = Self::PolicyError>;
    /// Mechanism failure.
    type Error;

    /// Materializes and binds every resident static/unit component exactly once.
    #[allow(clippy::too_many_arguments)]
    fn prepare_resident_materialization(
        &mut self,
        architecture: &mut A,
        units: &mut [A::Unit],
        source_architecture: Option<&mut A>,
        source_units: Option<&mut [A::Unit]>,
        tasks: &[RealtimeMaterializationTask],
        selected: &SelectedRealtimeRealization,
        context: &<<B as NeuralBackend>::Tensor as Tensor>::Context,
    ) -> Result<(), Self::Error>;

    /// Builds fully resident storage around populated units.
    fn resident_policy(
        &mut self,
        architecture: &mut A,
        units: Vec<A::Unit>,
        selected: &SelectedRealtimeRealization,
        context: &<<B as NeuralBackend>::Tensor as Tensor>::Context,
    ) -> Result<RealizedRealtimePolicy<Self::ResidentPolicy>, Self::Error>;

    /// Builds selected bounded storage without eagerly constructing every unit.
    #[allow(clippy::too_many_arguments)]
    fn bounded_policy(
        &mut self,
        architecture: &mut A,
        source_architecture: Option<&mut A>,
        tasks: &[RealtimeMaterializationTask],
        selected: &SelectedRealtimeRealization,
        context: &<<B as NeuralBackend>::Tensor as Tensor>::Context,
    ) -> Result<RealizedRealtimePolicy<Self::BoundedPolicy>, Self::Error>;

    /// Realizes exact selected state components and placements.
    fn realize_state(
        &mut self,
        selected: &crate::SelectedRealtimeStateRealization,
        context: &<<B as NeuralBackend>::Tensor as Tensor>::Context,
    ) -> Result<RealizedRealtimeState<Self::State>, Self::Error>;
}

/// Resident or bounded runtime chosen by the authoritative realization.
pub enum RealtimeLayerwiseRuntime<A, B, S, R, P>
where
    B: SubmissionBackend<Executor = <<B as NeuralBackend>::Tensor as Tensor>::Context>,
    S: RuntimeState<B>,
    A: LayeredArchitecture<B, S>,
    R: LayerwisePolicy<B, A::Unit>,
    P: LayerwisePolicy<B, A::Unit>,
{
    /// Fully resident execution.
    Resident(LayerwiseRuntime<A, B, S, R>),
    /// Host-windowed or disk-streamed execution.
    Bounded(LayerwiseRuntime<A, B, S, P>),
}

/// Constructed static execution and mechanisms, detached from mutable model state.
pub struct ConstructedRealtimeExecution<A, B, M>
where
    B: SubmissionBackend<Executor = <<B as NeuralBackend>::Tensor as Tensor>::Context>,
    M: RealtimeModelConstructionMechanisms<A, B>,
    A: LayeredArchitecture<B, M::State>,
{
    selected: SelectedRealtimeRealization,
    execution: RealtimeLayerwiseRuntime<A, B, M::State, M::ResidentPolicy, M::BoundedPolicy>,
    mechanisms: M,
    backend: PhantomData<fn() -> B>,
}

impl<A, B, M> ConstructedRealtimeExecution<A, B, M>
where
    B: SubmissionBackend<Executor = <<B as NeuralBackend>::Tensor as Tensor>::Context>,
    M: RealtimeModelConstructionMechanisms<A, B>,
    A: LayeredArchitecture<B, M::State>,
{
    /// Returns the immutable selected realization.
    pub const fn selected(&self) -> &SelectedRealtimeRealization {
        &self.selected
    }

    /// Returns the selected resident or bounded runtime.
    pub const fn execution(
        &self,
    ) -> &RealtimeLayerwiseRuntime<A, B, M::State, M::ResidentPolicy, M::BoundedPolicy> {
        &self.execution
    }

    /// Mutably borrows the selected resident or bounded runtime.
    pub fn execution_mut(
        &mut self,
    ) -> &mut RealtimeLayerwiseRuntime<A, B, M::State, M::ResidentPolicy, M::BoundedPolicy> {
        &mut self.execution
    }

    /// Returns generic construction mechanisms for reports or later composition.
    pub const fn mechanisms(&self) -> &M {
        &self.mechanisms
    }

    /// Mutably borrows generic construction mechanisms.
    pub fn mechanisms_mut(&mut self) -> &mut M {
        &mut self.mechanisms
    }

    /// Decomposes selected construction for installation in the exact
    /// topology-specific neutral execution runtime.
    #[allow(clippy::type_complexity)]
    pub fn into_parts(
        self,
    ) -> (
        SelectedRealtimeRealization,
        RealtimeLayerwiseRuntime<A, B, M::State, M::ResidentPolicy, M::BoundedPolicy>,
        M,
    ) {
        (self.selected, self.execution, self.mechanisms)
    }
}

/// Fully constructed execution paired with its initial mutable model state.
pub struct ConstructedRealtimeModel<A, B, M>
where
    B: SubmissionBackend<Executor = <<B as NeuralBackend>::Tensor as Tensor>::Context>,
    M: RealtimeModelConstructionMechanisms<A, B>,
    A: LayeredArchitecture<B, M::State>,
{
    execution: ConstructedRealtimeExecution<A, B, M>,
    state: M::State,
}

impl<A, B, M> ConstructedRealtimeModel<A, B, M>
where
    B: SubmissionBackend<Executor = <<B as NeuralBackend>::Tensor as Tensor>::Context>,
    M: RealtimeModelConstructionMechanisms<A, B>,
    A: LayeredArchitecture<B, M::State>,
{
    /// Returns the immutable selected realization.
    pub const fn selected(&self) -> &SelectedRealtimeRealization {
        self.execution.selected()
    }

    /// Returns the selected resident or bounded runtime.
    pub const fn execution(
        &self,
    ) -> &RealtimeLayerwiseRuntime<A, B, M::State, M::ResidentPolicy, M::BoundedPolicy> {
        self.execution.execution()
    }

    /// Mutably borrows the selected resident or bounded runtime.
    pub fn execution_mut(
        &mut self,
    ) -> &mut RealtimeLayerwiseRuntime<A, B, M::State, M::ResidentPolicy, M::BoundedPolicy> {
        self.execution.execution_mut()
    }

    /// Returns realized architecture state.
    pub const fn state(&self) -> &M::State {
        &self.state
    }

    /// Mutably borrows realized architecture state.
    pub fn state_mut(&mut self) -> &mut M::State {
        &mut self.state
    }

    /// Mutably borrows execution and state together for one atomic model pass.
    #[allow(clippy::type_complexity)]
    pub fn execution_and_state_mut(
        &mut self,
    ) -> (
        &mut RealtimeLayerwiseRuntime<A, B, M::State, M::ResidentPolicy, M::BoundedPolicy>,
        &mut M::State,
    ) {
        (self.execution.execution_mut(), &mut self.state)
    }

    /// Mutably borrows detached execution and state as separate typed values.
    #[allow(clippy::type_complexity)]
    pub fn constructed_execution_and_state_mut(
        &mut self,
    ) -> (&mut ConstructedRealtimeExecution<A, B, M>, &mut M::State) {
        (&mut self.execution, &mut self.state)
    }

    /// Returns generic construction mechanisms for reports or later composition.
    pub const fn mechanisms(&self) -> &M {
        self.execution.mechanisms()
    }

    /// Mutably borrows generic mechanisms.
    pub fn mechanisms_mut(&mut self) -> &mut M {
        self.execution.mechanisms_mut()
    }

    /// Consumes the combined model into static execution and mutable state.
    pub fn into_execution_and_state(self) -> (ConstructedRealtimeExecution<A, B, M>, M::State) {
        (self.execution, self.state)
    }
}

/// Constructs static modules, selected units, storage, and exact state once.
#[allow(clippy::type_complexity)]
pub fn construct_realtime_model<A, B, M>(
    mut architecture: A,
    mut source_architecture: Option<A>,
    prepared: PreparedRealtimeModelContract,
    mut mechanisms: M,
    context: &<<B as NeuralBackend>::Tensor as Tensor>::Context,
) -> Result<
    ConstructedRealtimeModel<A, B, M>,
    RealtimeModelConstructionError<A::Error, M::PolicyError, M::Error>,
>
where
    B: SubmissionBackend<Executor = <<B as NeuralBackend>::Tensor as Tensor>::Context>,
    M: RealtimeModelConstructionMechanisms<A, B>,
    A: LayeredArchitecture<B, M::State> + RealtimeArchitectureIdentity,
    A::Error: std::fmt::Display,
    M::PolicyError: std::fmt::Display,
    M::Error: std::fmt::Display,
{
    let (selected, tasks) = prepared.into_parts();
    let requires_source_architecture = selected.weight_lowerings().iter().any(|lowering| {
        matches!(
            lowering.kind(),
            crate::WeightLoweringKind::Transform | crate::WeightLoweringKind::DerivedTransform
        )
    });
    if requires_source_architecture != source_architecture.is_some() {
        return Err(RealtimeModelConstructionError::Contract(
            "selected realtime lowering and source-format architecture presence differ".into(),
        ));
    }
    validate_architecture::<A, B, M::State>(&architecture, &selected, false, context)
        .map_err(widen_error)?;
    if let Some(source) = source_architecture.as_ref() {
        validate_architecture::<A, B, M::State>(source, &selected, true, context)
            .map_err(widen_error)?;
    }
    let (state, state_realization) = mechanisms
        .realize_state(selected.state(), context)
        .map_err(RealtimeModelConstructionError::Mechanism)?
        .into_parts();
    if &state_realization != selected.state() || state.layout() != selected.state().layout() {
        return Err(RealtimeModelConstructionError::Contract(
            "realized realtime state differs from selection".into(),
        ));
    }
    let execution = match selected.residency() {
        LayerWeightResidency::FullyResident => {
            let mut units = construct_units::<A, B, M::State>(&architecture, &selected, context)
                .map_err(widen_error)?;
            let mut source_units = source_architecture
                .as_ref()
                .map(|source| construct_units::<A, B, M::State>(source, &selected, context))
                .transpose()
                .map_err(widen_error)?;
            mechanisms
                .prepare_resident_materialization(
                    &mut architecture,
                    &mut units,
                    source_architecture.as_mut(),
                    source_units.as_deref_mut(),
                    &tasks,
                    &selected,
                    context,
                )
                .map_err(RealtimeModelConstructionError::Mechanism)?;
            let (policy, residency) = mechanisms
                .resident_policy(&mut architecture, units, &selected, context)
                .map_err(RealtimeModelConstructionError::Mechanism)?
                .into_parts();
            if residency != selected.residency() {
                return Err(RealtimeModelConstructionError::Contract(
                    "realized realtime weight residency differs from selection".into(),
                ));
            }
            RealtimeLayerwiseRuntime::Resident(LayerwiseRuntime::new(architecture, policy))
        }
        LayerWeightResidency::LayerwiseHost(_) | LayerWeightResidency::DenseDiskStream(_) => {
            let (policy, residency) = mechanisms
                .bounded_policy(
                    &mut architecture,
                    source_architecture.as_mut(),
                    &tasks,
                    &selected,
                    context,
                )
                .map_err(RealtimeModelConstructionError::Mechanism)?
                .into_parts();
            if residency != selected.residency() {
                return Err(RealtimeModelConstructionError::Contract(
                    "realized realtime weight residency differs from selection".into(),
                ));
            }
            RealtimeLayerwiseRuntime::Bounded(LayerwiseRuntime::new(architecture, policy))
        }
    };
    Ok(ConstructedRealtimeModel {
        execution: ConstructedRealtimeExecution {
            selected,
            execution,
            mechanisms,
            backend: PhantomData,
        },
        state,
    })
}

fn widen_error<A, P, M>(
    error: RealtimeModelConstructionError<A, std::convert::Infallible, std::convert::Infallible>,
) -> RealtimeModelConstructionError<A, P, M>
where
    A: std::fmt::Display,
    P: std::fmt::Display,
    M: std::fmt::Display,
{
    match error {
        RealtimeModelConstructionError::Architecture(error) => {
            RealtimeModelConstructionError::Architecture(error)
        }
        RealtimeModelConstructionError::Contract(error) => {
            RealtimeModelConstructionError::Contract(error)
        }
        RealtimeModelConstructionError::Mechanism(error) => match error {},
        RealtimeModelConstructionError::Policy(error) => match error {},
    }
}

fn construct_units<A, B, S>(
    architecture: &A,
    selected: &SelectedRealtimeRealization,
    context: &<B::Tensor as Tensor>::Context,
) -> Result<
    Vec<A::Unit>,
    RealtimeModelConstructionError<A::Error, std::convert::Infallible, std::convert::Infallible>,
>
where
    B: NeuralBackend,
    S: RuntimeState<B>,
    A: LayeredArchitecture<B, S>,
    A::Error: std::fmt::Display,
{
    (0..selected.execution_units().len())
        .map(|ordinal| {
            let address = selected
                .execution_units()
                .address(ordinal)
                .expect("selected execution ordinal has an address");
            architecture
                .build_unit(address.group(), address.index(), context)
                .map_err(RealtimeModelConstructionError::Architecture)
        })
        .collect()
}

fn validate_architecture<A, B, S>(
    architecture: &A,
    selected: &SelectedRealtimeRealization,
    source: bool,
    context: &<B::Tensor as Tensor>::Context,
) -> Result<
    (),
    RealtimeModelConstructionError<A::Error, std::convert::Infallible, std::convert::Infallible>,
>
where
    B: NeuralBackend,
    S: RuntimeState<B>,
    A: LayeredArchitecture<B, S> + RealtimeArchitectureIdentity,
    A::Error: std::fmt::Display,
{
    if !source {
        let actual = architecture
            .realtime_construction_identity()
            .map_err(RealtimeModelConstructionError::Contract)?;
        let requirements = selected.requirements();
        let expected = RealtimeArchitectureConstructionIdentity::new(
            requirements.architecture().clone(),
            requirements.speech_schedule_identity().clone(),
            requirements.state_layout_identity().clone(),
        );
        if actual != expected {
            return Err(RealtimeModelConstructionError::Contract(
                "constructed realtime architecture identities differ from selection".into(),
            ));
        }
    }
    if architecture
        .execution_graph()
        .map_err(RealtimeModelConstructionError::Architecture)?
        != *selected.execution_graph()
    {
        return Err(RealtimeModelConstructionError::Contract(
            "constructed realtime execution graph differs from selection".into(),
        ));
    }
    for group in 0..selected.execution_graph().groups().len() {
        let actual = architecture
            .group_unit_count(group)
            .map_err(RealtimeModelConstructionError::Architecture)?;
        let expected = selected
            .execution_units()
            .group_range(group)
            .expect("selected layout contains every graph group")
            .len();
        if actual != expected {
            return Err(RealtimeModelConstructionError::Contract(format!(
                "constructed realtime group {group} unit count differs from selection"
            )));
        }
    }
    let actual = architecture
        .parameter_description(context)
        .map_err(RealtimeModelConstructionError::Architecture)?;
    let expected = if source {
        selected.source_parameters()
    } else {
        selected.execution_parameters()
    };
    if &actual != expected {
        return Err(RealtimeModelConstructionError::Contract(
            "constructed realtime parameter topology differs from selection".into(),
        ));
    }
    if !source
        && architecture
            .state_layout()
            .map_err(RealtimeModelConstructionError::Architecture)?
            != *selected.state().layout()
    {
        return Err(RealtimeModelConstructionError::Contract(
            "constructed realtime state layout differs from selection".into(),
        ));
    }
    Ok(())
}

/// Invalid selected recipe or task handoff.
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum RealtimeModelContractError {
    /// A component's retained physical sources differ from its selected recipe traversal.
    #[error("realtime source provenance differs for target {target}")]
    SourceProvenanceMismatch {
        /// Affected selected component target.
        target: String,
    },
    /// A source-backed companion's inferred geometry differs from selection.
    #[error("realtime recipe geometry differs for target {target}")]
    RecipeGeometryMismatch {
        /// Affected selected component target.
        target: String,
    },
    /// Primary recipe scalar encoding differs from its selected source descriptor.
    #[error("realtime recipe encoding differs for target {target}")]
    RecipeEncodingMismatch {
        /// Affected selected component target.
        target: String,
    },
    /// Concrete component payload does not exactly cover the lowering.
    #[error("realtime component payload differs for target {target}")]
    ComponentCoverageMismatch {
        /// Affected selected lowering target.
        target: String,
    },
    /// Task targets do not exactly cover selection.
    #[error("realtime materialization tasks do not exactly cover selected targets")]
    TaskCoverageMismatch,
    /// A task contains a lowering that differs from selection.
    #[error("realtime materialization task differs from selection for target {target}")]
    TaskSelectionMismatch {
        /// Affected selected lowering target.
        target: String,
    },
    /// A selected target has no declared execution parameter owner.
    #[error("realtime materialization target {target} has no execution owner")]
    TaskOwnerUnavailable {
        /// Affected selected lowering target.
        target: String,
    },
    /// A task owner differs from the exact selected execution owner.
    #[error("realtime materialization owner differs from selection for target {target}")]
    TaskOwnerMismatch {
        /// Affected selected lowering target.
        target: String,
    },
    /// Canonical task-to-binding derivation or metadata preflight failed.
    #[error("realtime binding plan is invalid: {detail}")]
    BindingPlan {
        /// Exact metadata-only causal failure.
        detail: String,
    },
}

/// Failure while constructing one selected layered realtime model.
#[derive(Debug, thiserror::Error)]
pub enum RealtimeModelConstructionError<A, P, M>
where
    A: std::fmt::Display,
    P: std::fmt::Display,
    M: std::fmt::Display,
{
    /// Neutral architecture construction failed.
    #[error("realtime architecture construction failed: {0}")]
    Architecture(A),
    /// Selected and constructed neutral contracts differ.
    #[error("invalid realtime model construction: {0}")]
    Contract(String),
    /// Generic materialization, state, or storage mechanism failed.
    #[error("realtime model mechanism failed: {0}")]
    Mechanism(M),
    /// Resident/bounded policy failure reserved for execution-time composition.
    #[error("realtime residency policy failed: {0}")]
    Policy(P),
}