cortex-hybrid 0.2.0

Backend-neutral ANN stage layer and deterministic Vec reference backend for hybrid ANN/SNN systems.
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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! External Rust ML adapter contract.
//!
//! The types in this file never name Candle, Burn, or any other engine's
//! tensor, device, or module types. An adapter implements [`ExternalAdapterMarker`] with its own
//! associated tensor, reports capabilities in cortex terms, and converts
//! hidden state through [`HiddenStateBuffer`]. The optional `candle` feature
//! compiles `CandleExecutor` in a child module. That executor copies row-major
//! `f32` values through its own `HiddenState` type and does not implement this
//! contract. The optional `burn` feature is a policy stub.
//!
//! Capability reports are facts an orchestrator can translate. This module
//! does not select a backend, rank engines, or place ANN stages against SNN
//! stages — that negotiation belongs to `hybrid-fusion` (see
//! [hybrid-fusion#41](https://github.com/rmems/hybrid-fusion/issues/41)).
//! [`NegotiationDocument`] is the cortex-owned document that translation
//! consumes. It is not `hybrid-fusion`'s `BackendCapabilities` type, which
//! has not landed.

use crate::error::{CortexError, Result};
use crate::stage::{
    AnnCapabilities, AnnExecutor, AnnStage, DType, StageId, StageInput, StageKind, StageKindTag,
    StageTensor,
};
use std::collections::BTreeSet;
use std::fmt;

/// Where an external adapter may place tensors.
///
/// A capability fact, not a device handle. Native engine device types stay
/// inside optional adapters.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeviceClass {
    /// Host CPU.
    Cpu,
    /// NVIDIA CUDA device. Reported only; this crate does not ship CUDA kernels.
    Cuda,
    /// Apple Metal device. Reported only; this crate does not ship Metal kernels.
    Metal,
}

impl DeviceClass {
    /// Stable negotiation token.
    pub fn as_str(self) -> &'static str {
        match self {
            DeviceClass::Cpu => "cpu",
            DeviceClass::Cuda => "cuda",
            DeviceClass::Metal => "metal",
        }
    }
}

impl fmt::Display for DeviceClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// What an adapter explicitly cannot do.
///
/// Absence from [`AnnCapabilities`] or [`AdapterCapabilities::devices`]
/// already means "not advertised." [`AdapterCapabilities::require_supported`]
/// rejects both these explicit refusals and any request the adapter never
/// listed. This struct records the refusals an orchestrator should surface,
/// including toolchain gaps that are not a stage kind.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackendLimitations {
    /// Stage kinds the adapter will reject.
    pub unsupported_tags: BTreeSet<StageKindTag>,
    /// Element types the adapter will reject.
    pub unsupported_dtypes: BTreeSet<DType>,
    /// Device classes the adapter will reject.
    pub unsupported_devices: BTreeSet<DeviceClass>,
    /// Human-readable limits. Not a performance ranking.
    pub notes: Vec<String>,
}

/// Owned hidden-state bytes crossing an adapter boundary.
///
/// This is the conversion boundary, not a universal tensor format and not a
/// checkpoint. Adapters copy into and out of their native storage here so
/// core traits never name that storage.
#[derive(Debug, Clone, PartialEq)]
pub struct HiddenStateBuffer {
    /// Row-major elements in the reference interchange dtype of `dtype`.
    /// `F32` payloads are IEEE-754 `f32` bits stored as `f32` values.
    pub data: Vec<f32>,
    /// Row-major extents, outermost dimension first.
    pub shape: Vec<usize>,
    /// Element type the producing adapter claims.
    pub dtype: DType,
}

/// Capability report every external adapter and the reference backend share.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdapterCapabilities {
    /// Stage kinds, dtypes, and statefulness, in the existing ANN vocabulary.
    pub ann: AnnCapabilities,
    /// Device classes the adapter can place tensors on.
    pub devices: BTreeSet<DeviceClass>,
    /// Whether a leading batch axis is accepted. The reference backend is unbatched.
    pub batch: bool,
    /// Whether the adapter keeps a KV / sequence cache across calls.
    pub sequence_cache: bool,
    /// Whether hidden state can be imported and exported through [`HiddenStateBuffer`].
    pub hidden_state_io: bool,
    /// Explicit refusals, including kinds absent from [`AnnCapabilities`].
    pub limitations: BackendLimitations,
}

/// Cortex-owned facts an orchestrator translates into its own negotiation type.
///
/// Field names here are stable for that translation. They are not
/// `hybrid-fusion`'s future `BackendCapabilities` struct: that type has not
/// landed (hybrid-fusion#41), and this crate does not depend on `hybrid-fusion`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NegotiationDocument {
    /// [`AnnCapabilities::backend_name`].
    pub backend_name: &'static str,
    /// Supported [`StageKindTag`] tokens, sorted.
    pub stage_kinds: Vec<String>,
    /// Supported [`DType`] tokens, sorted.
    pub dtypes: Vec<String>,
    /// Supported [`DeviceClass`] tokens, sorted.
    pub devices: Vec<String>,
    /// Copied from [`AdapterCapabilities::batch`].
    pub batch: bool,
    /// Copied from [`AdapterCapabilities::sequence_cache`].
    pub sequence_cache: bool,
    /// Copied from [`AnnCapabilities::stateful`].
    pub stateful: bool,
    /// Copied from [`AdapterCapabilities::hidden_state_io`].
    pub hidden_state_io: bool,
    /// Unsupported stage-kind tokens, sorted.
    ///
    /// Prefixed `stage_kind:` so a caller can tell a refused stage from a
    /// refused dtype or device without parsing notes.
    pub unsupported: Vec<String>,
    /// Unsupported dtype tokens, sorted. Prefixed `dtype:`.
    pub unsupported_dtypes: Vec<String>,
    /// Unsupported device tokens, sorted. Prefixed `device:`.
    pub unsupported_devices: Vec<String>,
    /// Limitation notes, including the orchestrator boundary.
    pub limitations: Vec<String>,
}

impl AdapterCapabilities {
    /// Refuse a request the adapter did not advertise.
    ///
    /// Membership in [`AnnCapabilities::supported_tags`],
    /// [`AnnCapabilities::supported_dtypes`], and [`Self::devices`] is
    /// required. [`BackendLimitations`] supplies the reason when the gap is
    /// an explicit refusal. A request absent from both the advertised set and
    /// the refusal set is still rejected.
    ///
    /// Checks run in category order: stage kind, dtype, then device.
    ///
    /// # Errors
    ///
    /// Returns [`CortexError::UnsupportedOperation`] for the first gap.
    pub fn require_supported(
        &self,
        stage_id: &StageId,
        kind: &StageKind,
        dtype: DType,
        device: DeviceClass,
    ) -> Result<()> {
        let backend = self.ann.backend_name;
        let tag = kind.tag();
        if !self.ann.supported_tags.contains(&tag) {
            let detail = if self.limitations.unsupported_tags.contains(&tag) {
                format!("{tag} is not supported")
            } else {
                format!("{tag} is not advertised")
            };
            return Err(unsupported_operation(
                backend,
                stage_id,
                "stage_kind",
                detail,
            ));
        }
        if !self.ann.supported_dtypes.contains(&dtype) {
            let detail = if self.limitations.unsupported_dtypes.contains(&dtype) {
                format!("{dtype} is not supported")
            } else {
                format!("{dtype} is not advertised")
            };
            return Err(unsupported_operation(backend, stage_id, "dtype", detail));
        }
        if !self.devices.contains(&device) {
            let detail = if self.limitations.unsupported_devices.contains(&device) {
                format!("{device} is not supported")
            } else {
                format!("{device} is not advertised")
            };
            return Err(unsupported_operation(backend, stage_id, "device", detail));
        }
        Ok(())
    }

    /// Project this report into the document hybrid-fusion negotiation consumes.
    ///
    /// The projection is side-effect free. It does not choose a backend or
    /// fill a fallback.
    pub fn negotiation_document(&self) -> NegotiationDocument {
        let mut stage_kinds: Vec<String> = self
            .ann
            .supported_tags
            .iter()
            .map(|tag| tag.as_str().to_string())
            .collect();
        stage_kinds.sort();
        let mut dtypes: Vec<String> = self
            .ann
            .supported_dtypes
            .iter()
            .map(|dtype| dtype.as_str().to_string())
            .collect();
        dtypes.sort();
        let mut devices: Vec<String> = self
            .devices
            .iter()
            .map(|device| device.as_str().to_string())
            .collect();
        devices.sort();
        let mut unsupported: Vec<String> = self
            .limitations
            .unsupported_tags
            .iter()
            .map(|tag| format!("stage_kind:{}", tag.as_str()))
            .collect();
        unsupported.sort();
        let mut unsupported_dtypes: Vec<String> = self
            .limitations
            .unsupported_dtypes
            .iter()
            .map(|dtype| format!("dtype:{}", dtype.as_str()))
            .collect();
        unsupported_dtypes.sort();
        let mut unsupported_devices: Vec<String> = self
            .limitations
            .unsupported_devices
            .iter()
            .map(|device| format!("device:{}", device.as_str()))
            .collect();
        unsupported_devices.sort();
        let mut limitations = self.limitations.notes.clone();
        limitations.push(
            "translation target is hybrid-fusion negotiation (hybrid-fusion#41); this document does not place or rank backends".to_string(),
        );
        NegotiationDocument {
            backend_name: self.ann.backend_name,
            stage_kinds,
            dtypes,
            devices,
            batch: self.batch,
            sequence_cache: self.sequence_cache,
            stateful: self.ann.stateful,
            hidden_state_io: self.hidden_state_io,
            unsupported,
            unsupported_dtypes,
            unsupported_devices,
            limitations,
        }
    }
}

/// Marker for a backend that can be used through the external-adapter contract.
///
/// Generic code bounded by this trait can query capabilities, execute stages,
/// and move hidden state through [`HiddenStateBuffer`] without naming Candle
/// or Burn. Native engine tensors stay the backend's associated [`StageTensor`].
/// Inherent methods on each backend remain so a recording wrapper can call
/// conversion without implementing this trait itself.
pub trait ExternalAdapterMarker: AnnExecutor {
    /// Report the adapter capability surface. Must agree with
    /// [`AnnExecutor::capabilities`] on name, tags, dtypes, and statefulness.
    fn adapter_capabilities(&self) -> AdapterCapabilities;

    /// Copy `tensor` into the interchange buffer.
    ///
    /// # Errors
    ///
    /// Returns a [`CortexError`] when the adapter cannot export `tensor`.
    fn export_hidden(&self, tensor: &Self::Tensor) -> Result<HiddenStateBuffer>;

    /// Copy `buffer` into the backend's tensor type.
    ///
    /// # Errors
    ///
    /// Returns a [`CortexError`] when the adapter cannot import `buffer`.
    fn import_hidden(&self, buffer: &HiddenStateBuffer) -> Result<Self::Tensor>;
}

/// Build the reference backend's adapter capability report from its ANN report.
pub(crate) fn reference_adapter_capabilities(ann: AnnCapabilities) -> AdapterCapabilities {
    let unsupported_tags = all_stage_tags()
        .into_iter()
        .filter(|tag| !ann.supported_tags.contains(tag))
        .collect();
    AdapterCapabilities {
        ann,
        devices: BTreeSet::from([DeviceClass::Cpu]),
        batch: false,
        sequence_cache: false,
        hidden_state_io: true,
        limitations: BackendLimitations {
            unsupported_tags,
            unsupported_dtypes: BTreeSet::from([DType::F16, DType::BF16]),
            unsupported_devices: BTreeSet::from([DeviceClass::Cuda, DeviceClass::Metal]),
            notes: vec![
                "reference backend is f32, CPU-only, and dense; no batch axis and no sequence cache".to_string(),
            ],
        },
    }
}

fn unsupported_operation(
    backend: &'static str,
    stage_id: &StageId,
    category: &'static str,
    detail: String,
) -> CortexError {
    CortexError::UnsupportedOperation {
        backend,
        stage_id: Some(stage_id.to_string()),
        category,
        detail,
    }
}

fn all_stage_tags() -> [StageKindTag; 11] {
    [
        StageKindTag::Embedding,
        StageKindTag::Attention,
        StageKindTag::LayerNorm,
        StageKindTag::RmsNorm,
        StageKindTag::DenseMlp,
        StageKindTag::GatedMlp,
        StageKindTag::MoeRouter,
        StageKindTag::MoeExpert,
        StageKindTag::Add,
        StageKindTag::Readout,
        StageKindTag::Custom,
    ]
}

#[cfg(feature = "burn")]
fn policy_stub_capabilities(
    backend_name: &'static str,
    framework_name: &'static str,
) -> AdapterCapabilities {
    AdapterCapabilities {
        ann: AnnCapabilities {
            backend_name,
            supported_tags: BTreeSet::new(),
            supported_dtypes: BTreeSet::new(),
            stateful: false,
        },
        devices: BTreeSet::new(),
        batch: false,
        sequence_cache: false,
        hidden_state_io: false,
        limitations: BackendLimitations {
            unsupported_tags: BTreeSet::from(all_stage_tags()),
            unsupported_dtypes: BTreeSet::from([DType::F32, DType::F16, DType::BF16]),
            unsupported_devices: BTreeSet::from([
                DeviceClass::Cpu,
                DeviceClass::Cuda,
                DeviceClass::Metal,
            ]),
            notes: vec![format!(
                "{backend_name} adapter is a structured stub; cortex-hybrid does not depend on the {framework_name} crate"
            )],
        },
    }
}

#[cfg(feature = "burn")]
fn policy_stub_refusal(backend_name: &'static str, framework_name: &'static str) -> CortexError {
    CortexError::UnsupportedOperation {
        backend: backend_name,
        stage_id: None,
        category: "policy",
        detail: format!(
            "{framework_name} is not a dependency of cortex-hybrid; the feature is a structured stub and does not link {framework_name}"
        ),
    }
}

#[cfg(feature = "burn")]
macro_rules! define_policy_stub_adapter {
    ($adapter:ident, $tensor:ident, $backend:literal, $framework:literal) => {
        #[doc = concat!("Tensor stand-in used while ", $framework, " stays outside core.")]
        #[derive(Debug, Clone, PartialEq)]
        pub struct $tensor {
            shape: Vec<usize>,
            dtype: $crate::stage::DType,
        }

        impl $crate::stage::StageTensor for $tensor {
            fn meta(&self) -> $crate::stage::TensorMeta {
                $crate::stage::TensorMeta {
                    shape: self.shape.clone(),
                    dtype: self.dtype,
                }
            }
        }

        #[doc = concat!($framework, " participation stub.")]
        #[derive(Debug, Clone, Copy)]
        pub struct $adapter;

        impl $adapter {
            /// Adapter that reports the v0.3 dependency-policy gap.
            pub fn unavailable() -> Self {
                Self
            }
        }

        impl $crate::adapter::ExternalAdapterMarker for $adapter {
            fn adapter_capabilities(&self) -> $crate::adapter::AdapterCapabilities {
                $crate::adapter::policy_stub_capabilities($backend, $framework)
            }

            fn export_hidden(
                &self,
                _tensor: &Self::Tensor,
            ) -> $crate::Result<$crate::adapter::HiddenStateBuffer> {
                Err($crate::adapter::policy_stub_refusal($backend, $framework))
            }

            fn import_hidden(
                &self,
                _buffer: &$crate::adapter::HiddenStateBuffer,
            ) -> $crate::Result<Self::Tensor> {
                Err($crate::adapter::policy_stub_refusal($backend, $framework))
            }
        }

        impl $crate::stage::AnnExecutor for $adapter {
            type Tensor = $tensor;

            fn capabilities(&self) -> $crate::stage::AnnCapabilities {
                $crate::adapter::ExternalAdapterMarker::adapter_capabilities(self).ann
            }

            fn execute(
                &mut self,
                stage: &$crate::stage::AnnStage,
                _inputs: &[$crate::stage::StageInput<Self::Tensor>],
            ) -> $crate::Result<Self::Tensor> {
                Err($crate::CortexError::UnsupportedStage {
                    backend: $backend,
                    stage_id: stage.id.to_string(),
                    kind: format!("{:?}", stage.kind),
                })
            }
        }
    };
}

#[cfg(feature = "burn")]
pub(crate) use define_policy_stub_adapter;

/// Reject a hidden-state dtype the reference path cannot store.
pub(crate) fn require_f32_buffer(buffer: &HiddenStateBuffer) -> Result<()> {
    if buffer.dtype != DType::F32 {
        return Err(CortexError::StageDTypeMismatch {
            stage_id: "hidden_state".to_string(),
            expected: DType::F32.to_string(),
            got: buffer.dtype.to_string(),
        });
    }
    // Shared with the tensor constructors and the Candle adapter: a zero axis
    // short-circuits to 0, and overflow is `SizeOverflow`.
    let numel =
        crate::tensor::checked_numel(&buffer.shape).map_err(|err| CortexError::StageFailed {
            stage_id: "hidden_state".to_string(),
            source: Box::new(err),
        })?;
    if buffer.data.len() != numel {
        return Err(CortexError::StageFailed {
            stage_id: "hidden_state".to_string(),
            source: Box::new(CortexError::ShapeMismatch {
                expected: buffer.shape.clone(),
                got: vec![buffer.data.len()],
            }),
        });
    }
    Ok(())
}

/// Namespace for generic calls against [`ExternalAdapterMarker`].
///
/// `ReferenceExecutor` and the burn policy stub also expose the same methods
/// inherently. This helper lets tests and generic callers write
/// `ExternalAdapter::capabilities(backend)` without naming an engine.
pub struct ExternalAdapter;

impl ExternalAdapter {
    /// [`AdapterCapabilities`] for any [`ExternalAdapterMarker`].
    pub fn capabilities<A: ExternalAdapterMarker + ?Sized>(adapter: &A) -> AdapterCapabilities {
        adapter.adapter_capabilities()
    }

    /// [`AnnExecutor::execute`] under the adapter contract name.
    pub fn execute<A: ExternalAdapterMarker + ?Sized>(
        adapter: &mut A,
        stage: &AnnStage,
        inputs: &[StageInput<A::Tensor>],
    ) -> Result<A::Tensor> {
        adapter.execute(stage, inputs)
    }

    /// [`ExternalAdapterMarker::export_hidden`] for a generic adapter.
    pub fn export_hidden<A: ExternalAdapterMarker + ?Sized>(
        adapter: &A,
        tensor: &A::Tensor,
    ) -> Result<HiddenStateBuffer> {
        adapter.export_hidden(tensor)
    }

    /// [`ExternalAdapterMarker::import_hidden`] for a generic adapter.
    pub fn import_hidden<A: ExternalAdapterMarker + ?Sized>(
        adapter: &A,
        buffer: &HiddenStateBuffer,
    ) -> Result<A::Tensor> {
        adapter.import_hidden(buffer)
    }
}

/// Confirm an adapter tensor's reported dtype is one it claims to support.
pub fn require_supported_dtype<T: StageTensor>(
    caps: &AnnCapabilities,
    stage_id: &StageId,
    tensor: &T,
) -> Result<()> {
    let dtype = tensor.meta().dtype;
    if caps.supported_dtypes.contains(&dtype) {
        Ok(())
    } else {
        Err(CortexError::StageDTypeMismatch {
            stage_id: stage_id.to_string(),
            expected: caps
                .supported_dtypes
                .iter()
                .map(|dtype| dtype.as_str())
                .collect::<Vec<_>>()
                .join(", "),
            got: dtype.to_string(),
        })
    }
}

#[cfg(feature = "candle")]
mod candle;
#[cfg(feature = "candle")]
pub use candle::{
    AttentionWeights, CandleExecutor, CandleTensor, EmbeddingWeights, GatedMlpWeights, HiddenState,
    LayerNormWeights, LinearWeights, MlpWeights, RmsNormWeights, export_hidden_state,
    export_reference, import_hidden_state, import_reference,
};

#[cfg(feature = "burn")]
mod burn_adapter;
#[cfg(feature = "burn")]
pub use burn_adapter::BurnAdapter;

#[cfg(test)]
mod tests {
    use super::*;

    fn buffer(data: Vec<f32>, shape: Vec<usize>) -> HiddenStateBuffer {
        HiddenStateBuffer {
            data,
            shape,
            dtype: DType::F32,
        }
    }

    #[test]
    fn require_f32_buffer_overflow_is_wrapped_size_overflow() {
        let err = require_f32_buffer(&buffer(Vec::new(), vec![usize::MAX, 2])).unwrap_err();
        assert!(
            matches!(
                &err,
                CortexError::StageFailed { stage_id, source }
                    if stage_id == "hidden_state"
                        && matches!(
                            &**source,
                            CortexError::SizeOverflow { shape } if shape == &[usize::MAX, 2]
                        )
            ),
            "{err:?}"
        );
    }

    #[test]
    fn require_f32_buffer_zero_axis_short_circuits_overflow() {
        require_f32_buffer(&buffer(Vec::new(), vec![usize::MAX, usize::MAX, 0])).unwrap();
    }

    #[test]
    fn require_f32_buffer_length_mismatch_is_shape_mismatch() {
        require_f32_buffer(&buffer(vec![0.0; 6], vec![2, 3])).unwrap();
        let err = require_f32_buffer(&buffer(vec![0.0; 5], vec![2, 3])).unwrap_err();
        assert!(
            matches!(
                &err,
                CortexError::StageFailed { source, .. }
                    if matches!(
                        &**source,
                        CortexError::ShapeMismatch { expected, got }
                            if expected == &[2, 3] && got == &[5]
                    )
            ),
            "{err:?}"
        );
    }
}