tenferro-ad 0.3.0

Eager runtime, eager tensors, and traced AD extension traits for tenferro.
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
//! Semantic-program automatic-differentiation rules for extension operations.
//!
//! Rules in this module are owned explicitly by [`crate::AdContext`]. They
//! operate on opaque semantic [`ProgramValue`] tokens and never expose
//! computegraph node keys or execution-program slots.

use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;

use tenferro_ops::ext_op::ExtensionOp;
use tenferro_runtime::program::{
    ProgramBuildError, ProgramValue, SemanticOpRef, SemanticOperationView, SemanticProgramBuilder,
    SemanticProvenanceView,
};

/// One optional semantic AD value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AdValue {
    /// This primal, tangent, or cotangent is inactive.
    Absent,
    /// Active value owned by the destination semantic-program builder.
    Value(ProgramValue),
}

impl AdValue {
    /// Return the active semantic value, if present.
    #[must_use]
    pub const fn value(self) -> Option<ProgramValue> {
        match self {
            Self::Absent => None,
            Self::Value(value) => Some(value),
        }
    }
}

/// Semantic extension AD rule role.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SemanticAdRuleRole {
    /// Definitional forward linearization.
    Linearize,
    /// Transpose of a linearized extension operation.
    LinearTranspose,
    /// Direct reverse rule expressed against primal values.
    PrimalVjp,
}

/// Registration failures for semantic extension AD rules.
#[derive(Debug, thiserror::Error)]
pub enum SemanticExtensionRegistryError {
    /// A rule with the same family and role is already present.
    #[error("semantic extension AD {role:?} rule for family {family_id:?} is already registered")]
    DuplicateRule {
        /// Duplicate extension family identifier.
        family_id: &'static str,
        /// Duplicate semantic AD role.
        role: SemanticAdRuleRole,
    },
    /// A rule family is not a namespaced, versioned identifier.
    #[error("semantic extension AD family {family_id:?} is not namespaced and versioned")]
    MalformedFamilyId {
        /// Invalid extension family identifier.
        family_id: &'static str,
    },
}

/// Failures while dispatching or building semantic extension AD.
#[derive(Debug, thiserror::Error)]
pub enum SemanticAdError {
    /// The supplied operation is not an extension operation.
    #[error("semantic AD extension dispatch received a core operation")]
    CoreOperation,
    /// Observable effects make implicit differentiation unsafe.
    #[error("semantic extension family {family_id:?} has observable effects")]
    EffectfulExtension {
        /// Effectful extension family.
        family_id: &'static str,
    },
    /// No rule is registered for the requested family and role.
    #[error("semantic extension family {family_id:?} has no {role:?} AD rule")]
    MissingRule {
        /// Extension family without a rule.
        family_id: &'static str,
        /// Missing semantic AD role.
        role: SemanticAdRuleRole,
    },
    /// An ordered request or result field has the wrong length.
    #[error("semantic AD field {field} expects {expected} values, got {actual}")]
    Arity {
        /// Name of the invalid ordered field.
        field: &'static str,
        /// Required field length.
        expected: usize,
        /// Supplied field length.
        actual: usize,
    },
    /// A request or result value belongs to another builder.
    #[error("semantic AD field {field}[{index}] does not belong to the destination builder")]
    ForeignValue {
        /// Name of the invalid ordered field.
        field: &'static str,
        /// Index of the foreign value.
        index: usize,
    },
    /// A family-specific rule deliberately rejects this payload.
    #[error("semantic extension family {family_id:?} does not support {role:?}: {message}")]
    Unsupported {
        /// Extension family that rejected the transform.
        family_id: &'static str,
        /// Rejected semantic AD role.
        role: SemanticAdRuleRole,
        /// Bounded family-specific diagnostic.
        message: String,
    },
    /// A family-specific rule failed with a typed source error.
    #[error("semantic extension family {family_id:?} {role:?} rule failed: {source}")]
    Rule {
        /// Extension family whose rule failed.
        family_id: &'static str,
        /// Semantic AD role being evaluated.
        role: SemanticAdRuleRole,
        /// Original typed rule failure.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync + 'static>,
    },
    /// A family-specific semantic rule invariant was violated.
    #[error("semantic extension family {family_id:?} {role:?} invariant failed: {message}")]
    Invariant {
        /// Extension family whose invariant failed.
        family_id: &'static str,
        /// Semantic AD role being evaluated.
        role: SemanticAdRuleRole,
        /// Bounded invariant diagnostic.
        message: String,
    },
    /// Semantic-program construction failed inside a rule.
    #[error("semantic extension AD program construction failed: {0}")]
    Build(#[from] ProgramBuildError),
}

/// Ordered inputs for one semantic extension linearization rule.
#[derive(Clone, Copy)]
pub struct SemanticLinearizeRequest<'a> {
    op: &'a dyn ExtensionOp,
    primal_inputs: &'a [ProgramValue],
    primal_outputs: &'a [ProgramValue],
    tangent_inputs: &'a [AdValue],
    active_outputs: &'a [bool],
    provenance: SemanticProvenanceView<'a>,
}

impl<'a> SemanticLinearizeRequest<'a> {
    /// Borrow the extension payload.
    pub const fn op(self) -> &'a dyn ExtensionOp {
        self.op
    }

    /// Borrow ordered destination-local primal inputs.
    pub const fn primal_inputs(self) -> &'a [ProgramValue] {
        self.primal_inputs
    }

    /// Borrow ordered destination-local primal outputs.
    pub const fn primal_outputs(self) -> &'a [ProgramValue] {
        self.primal_outputs
    }

    /// Borrow ordered optional tangent inputs.
    pub const fn tangent_inputs(self) -> &'a [AdValue] {
        self.tangent_inputs
    }

    /// Borrow the ordered active-output mask.
    pub const fn active_outputs(self) -> &'a [bool] {
        self.active_outputs
    }

    /// Return bounded operation provenance.
    pub const fn provenance(self) -> SemanticProvenanceView<'a> {
        self.provenance
    }
}

/// Output of one semantic extension linearization rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SemanticLinearizeResult {
    tangent_outputs: Box<[AdValue]>,
    residuals: Box<[ProgramValue]>,
}

impl SemanticLinearizeResult {
    /// Construct ordered tangent outputs and residuals.
    #[must_use]
    pub fn new(
        tangent_outputs: impl IntoIterator<Item = AdValue>,
        residuals: impl IntoIterator<Item = ProgramValue>,
    ) -> Self {
        Self {
            tangent_outputs: tangent_outputs.into_iter().collect(),
            residuals: residuals.into_iter().collect(),
        }
    }

    /// Borrow ordered optional tangent outputs.
    pub fn tangent_outputs(&self) -> &[AdValue] {
        &self.tangent_outputs
    }

    /// Borrow ordered residual values saved for transpose.
    pub fn residuals(&self) -> &[ProgramValue] {
        &self.residuals
    }
}

/// Ordered inputs for one semantic linear-transpose rule.
#[derive(Clone, Copy)]
pub struct SemanticLinearTransposeRequest<'a> {
    op: &'a dyn ExtensionOp,
    primal_inputs: &'a [ProgramValue],
    primal_outputs: &'a [ProgramValue],
    cotangent_outputs: &'a [AdValue],
    active_inputs: &'a [bool],
    residuals: &'a [ProgramValue],
    provenance: SemanticProvenanceView<'a>,
}

impl<'a> SemanticLinearTransposeRequest<'a> {
    /// Borrow the extension payload.
    pub const fn op(self) -> &'a dyn ExtensionOp {
        self.op
    }

    /// Borrow ordered destination-local primal inputs.
    pub const fn primal_inputs(self) -> &'a [ProgramValue] {
        self.primal_inputs
    }

    /// Borrow ordered destination-local primal outputs.
    pub const fn primal_outputs(self) -> &'a [ProgramValue] {
        self.primal_outputs
    }

    /// Borrow ordered optional output cotangents.
    pub const fn cotangent_outputs(self) -> &'a [AdValue] {
        self.cotangent_outputs
    }

    /// Borrow the ordered active-input mask.
    pub const fn active_inputs(self) -> &'a [bool] {
        self.active_inputs
    }

    /// Borrow ordered residuals produced by linearization.
    pub const fn residuals(self) -> &'a [ProgramValue] {
        self.residuals
    }

    /// Return bounded operation provenance.
    pub const fn provenance(self) -> SemanticProvenanceView<'a> {
        self.provenance
    }
}

/// Ordered inputs for one direct semantic primal-VJP rule.
#[derive(Clone, Copy)]
pub struct SemanticPrimalVjpRequest<'a> {
    op: &'a dyn ExtensionOp,
    primal_inputs: &'a [ProgramValue],
    primal_outputs: &'a [ProgramValue],
    cotangent_outputs: &'a [AdValue],
    active_inputs: &'a [bool],
    provenance: SemanticProvenanceView<'a>,
}

impl<'a> SemanticPrimalVjpRequest<'a> {
    /// Borrow the extension payload.
    pub const fn op(self) -> &'a dyn ExtensionOp {
        self.op
    }

    /// Borrow ordered destination-local primal inputs.
    pub const fn primal_inputs(self) -> &'a [ProgramValue] {
        self.primal_inputs
    }

    /// Borrow ordered destination-local primal outputs.
    pub const fn primal_outputs(self) -> &'a [ProgramValue] {
        self.primal_outputs
    }

    /// Borrow ordered optional output cotangents.
    pub const fn cotangent_outputs(self) -> &'a [AdValue] {
        self.cotangent_outputs
    }

    /// Borrow the ordered active-input mask.
    pub const fn active_inputs(self) -> &'a [bool] {
        self.active_inputs
    }

    /// Return bounded operation provenance.
    pub const fn provenance(self) -> SemanticProvenanceView<'a> {
        self.provenance
    }
}

/// Definitional JVP rule for one extension family.
pub trait SemanticLinearizeRule: Debug + Send + Sync + 'static {
    /// Return the versioned extension family handled by this rule.
    fn family_id(&self) -> &'static str;

    /// Emit ordered tangent outputs and residuals into `builder`.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticAdError::Unsupported`] when the payload is outside
    /// the rule's supported domain, or [`SemanticAdError::Build`] when emitted
    /// semantic operations fail validation.
    fn linearize(
        &self,
        request: SemanticLinearizeRequest<'_>,
        builder: &mut SemanticProgramBuilder,
    ) -> Result<SemanticLinearizeResult, SemanticAdError>;
}

/// Transpose rule for an extension viewed as a linear map.
pub trait SemanticLinearTransposeRule: Debug + Send + Sync + 'static {
    /// Return the versioned extension family handled by this rule.
    fn family_id(&self) -> &'static str;

    /// Emit ordered optional input cotangents into `builder`.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticAdError::Unsupported`] when the payload is outside
    /// the rule's supported domain, or [`SemanticAdError::Build`] when emitted
    /// semantic operations fail validation.
    fn linear_transpose(
        &self,
        request: SemanticLinearTransposeRequest<'_>,
        builder: &mut SemanticProgramBuilder,
    ) -> Result<Box<[AdValue]>, SemanticAdError>;
}

/// Optional direct VJP rule expressed against primal semantic values.
pub trait SemanticPrimalVjpRule: Debug + Send + Sync + 'static {
    /// Return the versioned extension family handled by this rule.
    fn family_id(&self) -> &'static str;

    /// Emit ordered optional input cotangents into `builder`.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticAdError::Unsupported`] when the payload is outside
    /// the rule's supported domain, or [`SemanticAdError::Build`] when emitted
    /// semantic operations fail validation.
    fn primal_vjp(
        &self,
        request: SemanticPrimalVjpRequest<'_>,
        builder: &mut SemanticProgramBuilder,
    ) -> Result<Box<[AdValue]>, SemanticAdError>;
}

type LinearizeMap = HashMap<&'static str, Arc<dyn SemanticLinearizeRule>>;
type LinearTransposeMap = HashMap<&'static str, Arc<dyn SemanticLinearTransposeRule>>;
type PrimalVjpMap = HashMap<&'static str, Arc<dyn SemanticPrimalVjpRule>>;

/// Explicit clone-on-write set of semantic extension AD rules.
#[derive(Clone, Default)]
pub struct SemanticExtensionRuleSet {
    linearize: Arc<LinearizeMap>,
    linear_transpose: Arc<LinearTransposeMap>,
    primal_vjp: Arc<PrimalVjpMap>,
}

impl Debug for SemanticExtensionRuleSet {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut linearize: Vec<_> = self.linearize.keys().copied().collect();
        let mut linear_transpose: Vec<_> = self.linear_transpose.keys().copied().collect();
        let mut primal_vjp: Vec<_> = self.primal_vjp.keys().copied().collect();
        linearize.sort_unstable();
        linear_transpose.sort_unstable();
        primal_vjp.sort_unstable();
        formatter
            .debug_struct("SemanticExtensionRuleSet")
            .field("linearize", &linearize)
            .field("linear_transpose", &linear_transpose)
            .field("primal_vjp", &primal_vjp)
            .finish()
    }
}

impl SemanticExtensionRuleSet {
    /// Construct an empty rule set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register one semantic linearize rule.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
    /// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
    /// an existing family in this role.
    pub fn register_linearize(
        &mut self,
        rule: Arc<dyn SemanticLinearizeRule>,
    ) -> Result<(), SemanticExtensionRegistryError> {
        validate_insert(
            &self.linearize,
            rule.family_id(),
            SemanticAdRuleRole::Linearize,
        )?;
        Arc::make_mut(&mut self.linearize).insert(rule.family_id(), rule);
        Ok(())
    }

    /// Register one semantic linear-transpose rule.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
    /// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
    /// an existing family in this role.
    pub fn register_linear_transpose(
        &mut self,
        rule: Arc<dyn SemanticLinearTransposeRule>,
    ) -> Result<(), SemanticExtensionRegistryError> {
        validate_insert(
            &self.linear_transpose,
            rule.family_id(),
            SemanticAdRuleRole::LinearTranspose,
        )?;
        Arc::make_mut(&mut self.linear_transpose).insert(rule.family_id(), rule);
        Ok(())
    }

    /// Register one direct semantic primal-VJP rule.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
    /// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
    /// an existing family in this role.
    pub fn register_primal_vjp(
        &mut self,
        rule: Arc<dyn SemanticPrimalVjpRule>,
    ) -> Result<(), SemanticExtensionRegistryError> {
        validate_insert(
            &self.primal_vjp,
            rule.family_id(),
            SemanticAdRuleRole::PrimalVjp,
        )?;
        Arc::make_mut(&mut self.primal_vjp).insert(rule.family_id(), rule);
        Ok(())
    }

    /// Return a rule set containing one semantic linearize rule.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
    /// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
    /// an existing linearize rule.
    pub fn with_linearize(
        mut self,
        rule: Arc<dyn SemanticLinearizeRule>,
    ) -> Result<Self, SemanticExtensionRegistryError> {
        self.register_linearize(rule)?;
        Ok(self)
    }

    /// Return a rule set containing one semantic linear-transpose rule.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
    /// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
    /// an existing linear-transpose rule.
    pub fn with_linear_transpose(
        mut self,
        rule: Arc<dyn SemanticLinearTransposeRule>,
    ) -> Result<Self, SemanticExtensionRegistryError> {
        self.register_linear_transpose(rule)?;
        Ok(self)
    }

    /// Return a rule set containing one direct semantic primal-VJP rule.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
    /// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
    /// an existing primal-VJP rule.
    pub fn with_primal_vjp(
        mut self,
        rule: Arc<dyn SemanticPrimalVjpRule>,
    ) -> Result<Self, SemanticExtensionRegistryError> {
        self.register_primal_vjp(rule)?;
        Ok(self)
    }

    /// Merge another rule set atomically.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
    /// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
    /// a role-equivalent duplicate. The receiver is unchanged on failure.
    pub fn merge(&mut self, other: Self) -> Result<(), SemanticExtensionRegistryError> {
        let mut candidate = self.clone();
        for rule in other.linearize.values() {
            candidate.register_linearize(Arc::clone(rule))?;
        }
        for rule in other.linear_transpose.values() {
            candidate.register_linear_transpose(Arc::clone(rule))?;
        }
        for rule in other.primal_vjp.values() {
            candidate.register_primal_vjp(Arc::clone(rule))?;
        }
        *self = candidate;
        Ok(())
    }

    /// Look up a semantic linearize rule by extension family.
    #[must_use]
    pub fn lookup_linearize(&self, family_id: &str) -> Option<Arc<dyn SemanticLinearizeRule>> {
        self.linearize.get(family_id).cloned()
    }

    /// Look up a semantic linear-transpose rule by extension family.
    #[must_use]
    pub fn lookup_linear_transpose(
        &self,
        family_id: &str,
    ) -> Option<Arc<dyn SemanticLinearTransposeRule>> {
        self.linear_transpose.get(family_id).cloned()
    }

    /// Look up a direct semantic primal-VJP rule by extension family.
    #[must_use]
    pub fn lookup_primal_vjp(&self, family_id: &str) -> Option<Arc<dyn SemanticPrimalVjpRule>> {
        self.primal_vjp.get(family_id).cloned()
    }

    /// Validate and dispatch one semantic extension linearization.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticAdError::CoreOperation`] for a core operation,
    /// [`SemanticAdError::EffectfulExtension`] before rule dispatch for an
    /// effectful extension, or typed rule/arity/ownership/build failures.
    #[allow(clippy::too_many_arguments)]
    pub fn linearize_operation(
        &self,
        operation: SemanticOperationView<'_>,
        primal_inputs: &[ProgramValue],
        primal_outputs: &[ProgramValue],
        tangent_inputs: &[AdValue],
        active_outputs: &[bool],
        builder: &mut SemanticProgramBuilder,
    ) -> Result<SemanticLinearizeResult, SemanticAdError> {
        let op = extension_for_dispatch(operation)?;
        validate_operation_inputs(operation, primal_inputs, primal_outputs, builder)?;
        validate_len("tangent_inputs", op.input_count(), tangent_inputs.len())?;
        validate_len("active_outputs", op.output_count(), active_outputs.len())?;
        validate_ad_values("tangent_inputs", tangent_inputs, builder)?;
        let rule = self
            .lookup_linearize(op.family_id())
            .ok_or(SemanticAdError::MissingRule {
                family_id: op.family_id(),
                role: SemanticAdRuleRole::Linearize,
            })?;
        let result = rule.linearize(
            SemanticLinearizeRequest {
                op,
                primal_inputs,
                primal_outputs,
                tangent_inputs,
                active_outputs,
                provenance: operation.provenance(),
            },
            builder,
        )?;
        validate_len(
            "tangent_outputs",
            op.output_count(),
            result.tangent_outputs.len(),
        )?;
        validate_ad_values("tangent_outputs", &result.tangent_outputs, builder)?;
        validate_values("residuals", &result.residuals, builder)?;
        Ok(result)
    }

    /// Validate and dispatch one semantic extension linear transpose.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticAdError::EffectfulExtension`] before rule dispatch,
    /// [`SemanticAdError::MissingRule`] when no transpose rule exists,
    /// [`SemanticAdError::Arity`] / [`SemanticAdError::ForeignValue`] for an
    /// invalid request or result, or a typed family-rule failure.
    #[allow(clippy::too_many_arguments)]
    pub fn linear_transpose_operation(
        &self,
        operation: SemanticOperationView<'_>,
        primal_inputs: &[ProgramValue],
        primal_outputs: &[ProgramValue],
        cotangent_outputs: &[AdValue],
        active_inputs: &[bool],
        residuals: &[ProgramValue],
        builder: &mut SemanticProgramBuilder,
    ) -> Result<Box<[AdValue]>, SemanticAdError> {
        let op = extension_for_dispatch(operation)?;
        validate_operation_inputs(operation, primal_inputs, primal_outputs, builder)?;
        validate_len(
            "cotangent_outputs",
            op.output_count(),
            cotangent_outputs.len(),
        )?;
        validate_len("active_inputs", op.input_count(), active_inputs.len())?;
        validate_ad_values("cotangent_outputs", cotangent_outputs, builder)?;
        validate_values("residuals", residuals, builder)?;
        let rule =
            self.lookup_linear_transpose(op.family_id())
                .ok_or(SemanticAdError::MissingRule {
                    family_id: op.family_id(),
                    role: SemanticAdRuleRole::LinearTranspose,
                })?;
        let result = rule.linear_transpose(
            SemanticLinearTransposeRequest {
                op,
                primal_inputs,
                primal_outputs,
                cotangent_outputs,
                active_inputs,
                residuals,
                provenance: operation.provenance(),
            },
            builder,
        )?;
        validate_len("cotangent_inputs", op.input_count(), result.len())?;
        validate_ad_values("cotangent_inputs", &result, builder)?;
        Ok(result)
    }

    /// Validate and dispatch one direct semantic primal VJP.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticAdError::EffectfulExtension`] before rule dispatch,
    /// [`SemanticAdError::MissingRule`] when no primal-VJP rule exists,
    /// [`SemanticAdError::Arity`] / [`SemanticAdError::ForeignValue`] for an
    /// invalid request or result, or a typed family-rule failure.
    #[allow(clippy::too_many_arguments)]
    pub fn primal_vjp_operation(
        &self,
        operation: SemanticOperationView<'_>,
        primal_inputs: &[ProgramValue],
        primal_outputs: &[ProgramValue],
        cotangent_outputs: &[AdValue],
        active_inputs: &[bool],
        builder: &mut SemanticProgramBuilder,
    ) -> Result<Box<[AdValue]>, SemanticAdError> {
        let op = extension_for_dispatch(operation)?;
        validate_operation_inputs(operation, primal_inputs, primal_outputs, builder)?;
        validate_len(
            "cotangent_outputs",
            op.output_count(),
            cotangent_outputs.len(),
        )?;
        validate_len("active_inputs", op.input_count(), active_inputs.len())?;
        validate_ad_values("cotangent_outputs", cotangent_outputs, builder)?;
        let rule = self
            .lookup_primal_vjp(op.family_id())
            .ok_or(SemanticAdError::MissingRule {
                family_id: op.family_id(),
                role: SemanticAdRuleRole::PrimalVjp,
            })?;
        let result = rule.primal_vjp(
            SemanticPrimalVjpRequest {
                op,
                primal_inputs,
                primal_outputs,
                cotangent_outputs,
                active_inputs,
                provenance: operation.provenance(),
            },
            builder,
        )?;
        validate_len("cotangent_inputs", op.input_count(), result.len())?;
        validate_ad_values("cotangent_inputs", &result, builder)?;
        Ok(result)
    }
}

fn extension_for_dispatch(
    operation: SemanticOperationView<'_>,
) -> Result<&dyn ExtensionOp, SemanticAdError> {
    let SemanticOpRef::Extension(op) = operation.op() else {
        return Err(SemanticAdError::CoreOperation);
    };
    if !operation.effects().is_empty() {
        return Err(SemanticAdError::EffectfulExtension {
            family_id: op.family_id(),
        });
    }
    Ok(op)
}

fn validate_operation_inputs(
    operation: SemanticOperationView<'_>,
    primal_inputs: &[ProgramValue],
    primal_outputs: &[ProgramValue],
    builder: &SemanticProgramBuilder,
) -> Result<(), SemanticAdError> {
    validate_len(
        "primal_inputs",
        operation.inputs().len(),
        primal_inputs.len(),
    )?;
    validate_len(
        "primal_outputs",
        operation.outputs().len(),
        primal_outputs.len(),
    )?;
    validate_values("primal_inputs", primal_inputs, builder)?;
    validate_values("primal_outputs", primal_outputs, builder)
}

fn validate_values(
    field: &'static str,
    values: &[ProgramValue],
    builder: &SemanticProgramBuilder,
) -> Result<(), SemanticAdError> {
    for (index, value) in values.iter().copied().enumerate() {
        if builder.validate_value(value).is_err() {
            return Err(SemanticAdError::ForeignValue { field, index });
        }
    }
    Ok(())
}

fn validate_ad_values(
    field: &'static str,
    values: &[AdValue],
    builder: &SemanticProgramBuilder,
) -> Result<(), SemanticAdError> {
    for (index, value) in values.iter().copied().enumerate() {
        if let AdValue::Value(value) = value {
            if builder.validate_value(value).is_err() {
                return Err(SemanticAdError::ForeignValue { field, index });
            }
        }
    }
    Ok(())
}

fn validate_len(
    field: &'static str,
    expected: usize,
    actual: usize,
) -> Result<(), SemanticAdError> {
    if expected != actual {
        return Err(SemanticAdError::Arity {
            field,
            expected,
            actual,
        });
    }
    Ok(())
}

fn validate_insert<T>(
    map: &HashMap<&'static str, T>,
    family_id: &'static str,
    role: SemanticAdRuleRole,
) -> Result<(), SemanticExtensionRegistryError> {
    if !is_valid_family_id(family_id) {
        return Err(SemanticExtensionRegistryError::MalformedFamilyId { family_id });
    }
    if map.contains_key(family_id) {
        return Err(SemanticExtensionRegistryError::DuplicateRule { family_id, role });
    }
    Ok(())
}

fn is_valid_family_id(family_id: &str) -> bool {
    let Some((prefix, version)) = family_id.rsplit_once('.') else {
        return false;
    };
    let Some(version) = version.strip_prefix('v') else {
        return false;
    };
    let Some((crate_name, op_name)) = prefix.split_once('.') else {
        return false;
    };
    !crate_name.is_empty()
        && !op_name.is_empty()
        && !version.is_empty()
        && version.bytes().all(|byte| byte.is_ascii_digit())
        && crate_name.is_ascii()
        && op_name.is_ascii()
        && !crate_name.chars().any(char::is_whitespace)
        && !op_name.chars().any(char::is_whitespace)
}