incin-core 0.1.0

Core tensor operations and static shape checking for incin
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
//! Immutable compiled execution plans and dynamic runtime guards.

use alloc::boxed::Box;
use alloc::vec::Vec;

use crate::backend_authoring::TensorMeta;
use crate::compiled::alloc::{AllocationPlanner, LivenessMap, MemoryPlan};
use crate::compiled::capture::CapturedGraph;
use crate::err::{Error, Result};
use crate::exec::{DimExpr, LayoutClass, OperationIdentity, ShapeExpr, SymbolTable};
use crate::graph::ValueId;
use crate::tensor::device::DeviceId;
use crate::tensor::dtype::{DTypeDescriptor, DTypeId};

#[cfg(feature = "std")]
use crate::exec::catalog::{CapturedDescriptor, Descriptor, op};

/// Operation fusion strategy for graph compilation.
#[derive(
    Debug, Default, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum FusionPolicy {
    /// Kernel fusion is requested, but compiled fused lowering is not yet
    /// available for this plan.
    Enabled,
    /// Kernel fusion disabled for exact execution tracing.
    #[default]
    Disabled,
}

/// Dynamic shape handling policy.
#[derive(
    Debug, Default, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum DynamicShapePolicy {
    /// Runtime shape and dtype verification using guard checks (default).
    #[default]
    Guarded,
    /// Strict static shape validation matching compiled dimensions exactly.
    Strict,
}

/// Options controlling graph compilation.
#[derive(
    Debug, Default, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
pub struct CompileOptions {
    /// Kernel fusion policy.
    pub fusion: FusionPolicy,
    /// Dynamic shape handling policy.
    pub dynamic_shapes: DynamicShapePolicy,
}

impl CompileOptions {
    /// Creates default compilation options.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            fusion: FusionPolicy::Disabled,
            dynamic_shapes: DynamicShapePolicy::Guarded,
        }
    }
}

/// A dynamic runtime guard verifying shape and datatype expectations.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ShapeGuard {
    /// Value ID in the captured graph.
    pub value_id: ValueId,
    /// Expected tensor shape.
    pub shape: ShapeExpr,
    /// Expected logical datatype.
    pub expected_dtype: DTypeDescriptor,
    /// Device required when capture established one.
    pub expected_device: Option<DeviceId>,
    /// Layout required when capture established one.
    pub expected_layout: Option<LayoutClass>,
}

impl ShapeGuard {
    /// Creates a new guard for a value ID with expected shape and datatype.
    #[must_use]
    pub fn new(value_id: ValueId, shape: ShapeExpr, expected_dtype: DTypeDescriptor) -> Self {
        Self {
            value_id,
            shape,
            expected_dtype,
            expected_device: None,
            expected_layout: None,
        }
    }

    #[must_use]
    /// Attaches optional device and layout expectations to this guard.
    pub fn with_metadata(mut self, device: Option<DeviceId>, layout: Option<LayoutClass>) -> Self {
        self.expected_device = device;
        self.expected_layout = layout;
        self
    }

    /// Verifies actual runtime shape and datatype against this guard.
    pub fn check(&self, actual_shape: &[usize], actual_dtype: DTypeDescriptor) -> Result<()> {
        if self.expected_dtype != actual_dtype {
            return Err(Error::DTypeStorageMismatch {
                expected: self.expected_dtype,
                got: actual_dtype,
            });
        }
        if let Err(reason) = self.shape.validate(actual_shape) {
            return Err(Error::Msg(alloc::format!(
                "shape guard failed for input value {}: {}",
                self.value_id,
                reason
            )));
        }
        Ok(())
    }

    /// Checks runtime metadata against this guard's expectations.
    pub fn check_metadata(&self, metadata: &TensorMeta) -> Result<()> {
        self.check(metadata.shape.as_ref(), metadata.dtype)?;
        if let Some(expected) = self.expected_device
            && expected != metadata.device
        {
            return Err(Error::Msg(alloc::format!(
                "shape guard failed for input value {}: expected device {:?}, got {:?}",
                self.value_id,
                expected,
                metadata.device
            )));
        }
        if let Some(expected) = self.expected_layout
            && expected != metadata.layout
        {
            return Err(Error::Msg(alloc::format!(
                "shape guard failed for input value {}: expected layout {}, got {}",
                self.value_id,
                expected.as_str(),
                metadata.layout.as_str()
            )));
        }
        Ok(())
    }
}

/// An immutable compiled execution plan built from a captured graph.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct CompiledPlan {
    /// The captured IR graph.
    pub graph: CapturedGraph,
    /// Compilation options used.
    pub options: CompileOptions,
    /// Dynamic shape guards for graph inputs.
    pub input_guards: Vec<ShapeGuard>,
    /// Symbol table for dynamic extents.
    pub symbols: SymbolTable,
    /// Buffer liveness intervals per slot.
    pub liveness: LivenessMap,
    /// Allocation layout derived from liveness.
    pub memory_plan: MemoryPlan,
}

impl CompiledPlan {
    /// Creates a compiled plan from a captured graph and options, initializing input guards.
    pub fn compile(mut graph: CapturedGraph, options: CompileOptions) -> Result<Self> {
        if matches!(options.fusion, FusionPolicy::Enabled) {
            return Err(Error::Msg(
                "compiled fusion is not available for executable plans".into(),
            ));
        }
        for node in &graph.nodes {
            let site = node.execution_site.ok_or_else(|| {
                Error::Msg(alloc::format!(
                    "compiled operation {:?} has no execution-site classification",
                    node.operation
                ))
            })?;
            if !site.is_backend_executable() {
                return Err(Error::Msg(alloc::format!(
                    "compiled execution does not support {:?} at {:?}",
                    node.operation,
                    site
                )));
            }
        }
        propagate_symbolic_outputs(&mut graph)?;
        validate_static_constraints(&graph)?;
        let mut symbols = SymbolTable::default();
        for value in graph.value_metadata.values() {
            for constraint in &value.shape_expr.constraints {
                symbols.constraints.push(constraint.clone());
                collect_constraint_symbols(constraint, &mut symbols);
            }
        }
        let input_guards = graph
            .inputs
            .iter()
            .filter_map(|&in_id| {
                graph.value_metadata.get(&in_id).map(|value| {
                    for expr in &value.shape_expr.dims {
                        collect_symbols(expr, &mut symbols);
                    }
                    for constraint in &value.shape_expr.constraints {
                        collect_constraint_symbols(constraint, &mut symbols);
                    }
                    let shape = match options.dynamic_shapes {
                        DynamicShapePolicy::Guarded => value.shape_expr.clone(),
                        DynamicShapePolicy::Strict => ShapeExpr::concrete(&value.shape),
                    };
                    ShapeGuard::new(in_id, shape, value.dtype)
                        .with_metadata(value.device, value.layout)
                })
            })
            .collect();

        let liveness = LivenessMap::compute(&graph);
        let memory_plan = AllocationPlanner.plan(&liveness, &graph)?;
        Ok(Self {
            graph,
            options,
            input_guards,
            symbols,
            liveness,
            memory_plan,
        })
    }

    /// Validates dynamic guards for provided inputs.
    pub fn verify_input(&self, index: usize, shape: &[usize], dtype: DTypeId) -> Result<()> {
        let guard = self.input_guards.get(index).ok_or_else(|| {
            Error::Msg(alloc::format!(
                "compiled input guard index {} is out of range ({} inputs)",
                index,
                self.input_guards.len()
            ))
        })?;
        guard.check(shape, dtype.into())
    }

    /// Checks shapes and dtypes before invocation.
    pub fn verify_inputs(&self, inputs: &[(Vec<usize>, DTypeDescriptor)]) -> Result<()> {
        if inputs.len() != self.input_guards.len() {
            return Err(Error::Msg(alloc::format!(
                "compiled invocation expected {} inputs, got {}",
                self.input_guards.len(),
                inputs.len()
            )));
        }
        let mut environment = self.symbols.environment();
        for (guard, (shape, dtype)) in self.input_guards.iter().zip(inputs) {
            if guard.expected_dtype != *dtype {
                return Err(Error::DTypeStorageMismatch {
                    expected: guard.expected_dtype,
                    got: *dtype,
                });
            }
            guard
                .shape
                .bind_and_validate(shape, &mut environment)
                .map_err(|reason| {
                    Error::Msg(alloc::format!(
                        "shape guard failed for input value {}: {}",
                        guard.value_id,
                        reason
                    ))
                })?;
        }
        let constraints = self
            .input_guards
            .iter()
            .flat_map(|guard| guard.shape.constraints.iter())
            .cloned()
            .chain(self.symbols.constraints.iter().cloned())
            .collect::<Vec<_>>();
        environment
            .validate_constraints(&constraints)
            .map_err(|reason| {
                Error::Msg(alloc::format!("compiled invocation guard failed: {reason}"))
            })
    }

    /// Same check against full metadata handles.
    pub fn verify_input_metadata(&self, inputs: &[&TensorMeta]) -> Result<()> {
        if inputs.len() != self.input_guards.len() {
            return Err(Error::Msg(alloc::format!(
                "compiled invocation expected {} inputs, got {}",
                self.input_guards.len(),
                inputs.len()
            )));
        }
        let mut environment = self.symbols.environment();
        for (guard, metadata) in self.input_guards.iter().zip(inputs) {
            guard.check_metadata(metadata)?;
            guard
                .shape
                .bind_and_validate(metadata.shape.as_ref(), &mut environment)
                .map_err(|reason| {
                    Error::Msg(alloc::format!(
                        "shape guard failed for input value {}: {}",
                        guard.value_id,
                        reason
                    ))
                })?;
        }
        let constraints = self
            .input_guards
            .iter()
            .flat_map(|guard| guard.shape.constraints.iter())
            .cloned()
            .chain(self.symbols.constraints.iter().cloned())
            .collect::<Vec<_>>();
        environment
            .validate_constraints(&constraints)
            .map_err(|reason| {
                Error::Msg(alloc::format!("compiled invocation guard failed: {reason}"))
            })
    }
}

fn validate_static_constraints(graph: &CapturedGraph) -> Result<()> {
    for value in graph.value_metadata.values() {
        for constraint in &value.shape_expr.constraints {
            let valid = match constraint {
                crate::exec::Constraint::Equal { lhs, rhs } => lhs
                    .evaluate(&[])
                    .zip(rhs.evaluate(&[]))
                    .map(|(l, r)| l == r),
                crate::exec::Constraint::LowerBound { value, bound } => {
                    value.evaluate(&[]).map(|value| value >= *bound)
                }
                crate::exec::Constraint::UpperBound { value, bound } => {
                    value.evaluate(&[]).map(|value| value <= *bound)
                }
                crate::exec::Constraint::Divisible { value, divisor } => value
                    .evaluate(&[])
                    .map(|value| *divisor != 0 && value % divisor == 0),
                crate::exec::Constraint::BroadcastCompatible { lhs, rhs } => lhs
                    .evaluate(&[])
                    .zip(rhs.evaluate(&[]))
                    .map(|(lhs, rhs)| lhs == rhs || lhs == 1 || rhs == 1),
            };
            if valid == Some(false) {
                return Err(Error::Msg(format!(
                    "compiled graph contains a statically invalid shape constraint: {constraint:?}"
                )));
            }
        }
    }
    Ok(())
}

fn propagate_symbolic_outputs(graph: &mut CapturedGraph) -> Result<()> {
    for node in &graph.nodes {
        let inputs = node
            .inputs
            .iter()
            .map(|value_id| {
                graph
                    .value_metadata
                    .get(value_id)
                    .map(|value| value.shape_expr.clone())
                    .ok_or_else(|| Error::Msg(format!("missing metadata for value {value_id}")))
            })
            .collect::<Result<Vec<_>>>()?;
        let Some(output_id) = node.outputs.first().copied() else {
            return Err(Error::Msg(format!("node {} has no output", node.id)));
        };
        let output = graph
            .value_metadata
            .get_mut(&output_id)
            .ok_or_else(|| Error::Msg(format!("missing metadata for value {output_id}")))?;
        let shape = match node.operation {
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::Relu) => {
                inputs.first().cloned()
            }
            OperationIdentity::Builtin(
                crate::shapes::error::OperationKind::Abs
                | crate::shapes::error::OperationKind::Exp
                | crate::shapes::error::OperationKind::Neg
                | crate::shapes::error::OperationKind::Sqrt
                | crate::shapes::error::OperationKind::Log
                | crate::shapes::error::OperationKind::Tanh
                | crate::shapes::error::OperationKind::Sigmoid
                | crate::shapes::error::OperationKind::Gelu
                | crate::shapes::error::OperationKind::Elu
                | crate::shapes::error::OperationKind::Mish
                | crate::shapes::error::OperationKind::Swish
                | crate::shapes::error::OperationKind::LogicalNot,
            ) => inputs.first().cloned(),
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::Softmax) => {
                #[cfg(feature = "std")]
                {
                    let _axis = node_attribute_axis(node)?;
                    inputs.first().cloned()
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(
                crate::shapes::error::OperationKind::AddScalar
                | crate::shapes::error::OperationKind::SubScalar
                | crate::shapes::error::OperationKind::MulScalar
                | crate::shapes::error::OperationKind::DivScalar,
            ) => inputs.first().cloned(),
            OperationIdentity::Builtin(
                crate::shapes::error::OperationKind::Add
                | crate::shapes::error::OperationKind::Sub
                | crate::shapes::error::OperationKind::Mul
                | crate::shapes::error::OperationKind::Div,
            ) => inputs
                .first()
                .zip(inputs.get(1))
                .map(|(lhs, rhs)| broadcast_shapes(lhs, rhs)),
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::MatMulExact) => inputs
                .first()
                .zip(inputs.get(1))
                .and_then(|(lhs, rhs)| matmul_shape(lhs, rhs)),
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::Linear) => {
                #[cfg(feature = "std")]
                {
                    let _descriptor = decode_descriptor::<op::Linear>(node)?;
                    inputs
                        .first()
                        .zip(inputs.get(1))
                        .map(|(input, weight)| linear_shape(input, weight))
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::Addmm) => inputs
                .first()
                .zip(inputs.get(1))
                .zip(inputs.get(2))
                .and_then(|((addend, lhs), rhs)| {
                    matmul_shape(lhs, rhs).map(|product| broadcast_shapes(addend, &product))
                }),
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::ReshapeExact) => {
                #[cfg(feature = "std")]
                {
                    let descriptor = decode_descriptor::<op::ReshapeExact>(node)?;
                    Some(ShapeExpr::concrete(&descriptor.attributes().shape))
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::TransposeExact) => {
                #[cfg(feature = "std")]
                {
                    let descriptor = decode_descriptor::<op::TransposeExact>(node)?;
                    inputs.first().map(|input| {
                        let mut shape = input.clone();
                        let attributes = descriptor.attributes();
                        shape.dims.swap(attributes.first, attributes.second);
                        shape
                    })
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::Narrow) => {
                #[cfg(feature = "std")]
                {
                    let descriptor = decode_descriptor::<op::Narrow>(node)?;
                    inputs.first().map(|input| {
                        let mut shape = input.clone();
                        let attributes = descriptor.attributes();
                        if let Some(extent) = shape.dims.get_mut(attributes.axis) {
                            *extent = DimExpr::Const(attributes.length);
                        }
                        shape
                    })
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::FlattenExact) => {
                #[cfg(feature = "std")]
                {
                    let descriptor = decode_descriptor::<op::FlattenExact>(node)?;
                    inputs.first().map(|input| {
                        let attributes = descriptor.attributes();
                        flatten_symbolic(input, attributes.start_axis, attributes.end_axis)
                    })
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::SliceExact) => {
                #[cfg(feature = "std")]
                {
                    let descriptor = decode_descriptor::<op::SliceExact>(node)?;
                    inputs.first().map(|input| {
                        let mut shape = input.clone();
                        shape.dims = descriptor
                            .attributes()
                            .ranges
                            .iter()
                            .map(|(start, end)| {
                                end.checked_sub(*start)
                                    .map(DimExpr::Const)
                                    .unwrap_or(DimExpr::Unknown)
                            })
                            .collect();
                        shape
                    })
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::SqueezeExact) => {
                #[cfg(feature = "std")]
                {
                    let axis = decode_descriptor::<op::SqueezeExact>(node)?
                        .attributes()
                        .axis;
                    inputs.first().map(|input| {
                        let mut shape = input.clone();
                        shape.dims.remove(axis);
                        shape.rank = crate::exec::RankExpr::Static(shape.dims.len());
                        shape
                    })
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::UnsqueezeExact) => {
                #[cfg(feature = "std")]
                {
                    let axis = decode_descriptor::<op::UnsqueezeExact>(node)?
                        .attributes()
                        .axis;
                    inputs.first().map(|input| {
                        let mut shape = input.clone();
                        shape.dims.insert(axis, DimExpr::Const(1));
                        shape.rank = crate::exec::RankExpr::Static(shape.dims.len());
                        shape
                    })
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::SumDim) => {
                #[cfg(feature = "std")]
                {
                    let axis = node_attribute_axis_or_sum_descriptor(node)?;
                    inputs.first().map(|input| remove_axis(input, axis))
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(
                crate::shapes::error::OperationKind::MeanDim
                | crate::shapes::error::OperationKind::MaxDim
                | crate::shapes::error::OperationKind::MinDim,
            ) => {
                #[cfg(feature = "std")]
                {
                    let axis = node_attribute_axis_or_sum_keep_descriptor(node)?;
                    inputs.first().map(|input| remove_axis(input, axis))
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(
                crate::shapes::error::OperationKind::MeanKeepDim
                | crate::shapes::error::OperationKind::MaxKeepDim
                | crate::shapes::error::OperationKind::MinKeepDim,
            ) => {
                #[cfg(feature = "std")]
                {
                    let axis = node_attribute_axis(node)?;
                    inputs.first().map(|input| keep_axis(input, axis))
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::SumKeepDim) => {
                #[cfg(feature = "std")]
                {
                    let axis = node_attribute_axis(node)?;
                    inputs.first().map(|input| keep_axis(input, axis))
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::ConcatExact) => {
                #[cfg(feature = "std")]
                {
                    let axis = decode_descriptor::<op::ConcatExact>(node)?
                        .attributes()
                        .axis;
                    inputs.first().map(|first| {
                        let mut shape = first.clone();
                        shape.dims[axis] =
                            inputs
                                .iter()
                                .skip(1)
                                .fold(shape.dims[axis].clone(), |lhs, rhs| {
                                    DimExpr::Add(Box::new(lhs), Box::new(rhs.dims[axis].clone()))
                                        .simplify()
                                });
                        shape
                    })
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            OperationIdentity::Builtin(crate::shapes::error::OperationKind::StackExact) => {
                #[cfg(feature = "std")]
                {
                    let axis = decode_descriptor::<op::StackExact>(node)?.attributes().axis;
                    inputs.first().map(|input| {
                        let mut shape = input.clone();
                        shape.dims.insert(axis, DimExpr::Const(inputs.len()));
                        shape.rank = crate::exec::RankExpr::Static(shape.dims.len());
                        shape
                    })
                }
                #[cfg(not(feature = "std"))]
                {
                    None
                }
            }
            _ => None,
        };
        let Some(shape) = shape else {
            return Err(Error::Msg(format!(
                "compiled symbolic propagation does not support {:?}",
                node.operation
            )));
        };
        output.shape_expr = shape;
    }
    Ok(())
}

#[cfg(feature = "std")]
fn node_attribute_axis(node: &crate::compiled::CapturedNode) -> Result<usize> {
    node.attributes
        .get("axis")
        .and_then(|value| match value {
            crate::graph::AttributeValue::Int(axis) => usize::try_from(*axis).ok(),
            _ => None,
        })
        .ok_or_else(|| {
            Error::Msg(format!(
                "compiled node {} has no valid axis attribute",
                node.id
            ))
        })
}

#[cfg(feature = "std")]
fn node_attribute_axis_or_sum_descriptor(node: &crate::compiled::CapturedNode) -> Result<usize> {
    if node.descriptor_payload.is_some() {
        return Ok(decode_descriptor::<op::SumDim>(node)?.attributes().axis);
    }
    node_attribute_axis(node)
}

#[cfg(feature = "std")]
fn node_attribute_axis_or_sum_keep_descriptor(
    node: &crate::compiled::CapturedNode,
) -> Result<usize> {
    if node.descriptor_payload.is_some() {
        return Ok(decode_descriptor::<op::SumKeepDim>(node)?.attributes().axis);
    }
    node_attribute_axis(node)
}

#[cfg(feature = "std")]
fn remove_axis(input: &ShapeExpr, axis: usize) -> ShapeExpr {
    let mut shape = input.clone();
    if axis < shape.dims.len() {
        shape.dims.remove(axis);
        shape.rank = crate::exec::RankExpr::Static(shape.dims.len());
    }
    shape
}

#[cfg(feature = "std")]
fn keep_axis(input: &ShapeExpr, axis: usize) -> ShapeExpr {
    let mut shape = input.clone();
    if let Some(dim) = shape.dims.get_mut(axis) {
        *dim = DimExpr::Const(1);
    }
    shape
}

#[cfg(feature = "std")]
fn decode_descriptor<O>(node: &crate::compiled::CapturedNode) -> Result<Descriptor<O>>
where
    O: crate::exec::catalog::CanonicalOperation,
    O::Attributes: crate::exec::catalog::AttributeContract,
{
    let payload = node.descriptor_payload.as_ref().ok_or_else(|| {
        Error::Msg(format!(
            "compiled node {} has no captured descriptor",
            node.id
        ))
    })?;
    CapturedDescriptor::from_payload(O::ID, payload.schema, payload.payload.clone())
        .decode()
        .map_err(|error| Error::Msg(format!("invalid captured descriptor: {error}")))
}

fn broadcast_shapes(lhs: &ShapeExpr, rhs: &ShapeExpr) -> ShapeExpr {
    let rank = lhs.dims.len().max(rhs.dims.len());
    let mut dims = Vec::with_capacity(rank);
    let mut constraints = lhs.constraints.clone();
    constraints.extend(rhs.constraints.iter().cloned());
    for offset in 0..rank {
        let left = aligned_dim(&lhs.dims, rank, offset);
        let right = aligned_dim(&rhs.dims, rank, offset);
        constraints.push(crate::exec::Constraint::broadcast(
            left.clone(),
            right.clone(),
        ));
        dims.push(DimExpr::Broadcast(Box::new(left), Box::new(right)).simplify());
    }
    ShapeExpr {
        rank: crate::exec::RankExpr::Static(rank),
        dims,
        constraints,
    }
}

fn aligned_dim(dims: &[DimExpr], rank: usize, offset: usize) -> DimExpr {
    let source_offset = rank.saturating_sub(dims.len());
    if offset < source_offset {
        DimExpr::Const(1)
    } else {
        dims.get(offset - source_offset)
            .cloned()
            .unwrap_or(DimExpr::Const(1))
    }
}

#[cfg(feature = "std")]
fn flatten_symbolic(input: &ShapeExpr, start: usize, end: usize) -> ShapeExpr {
    let mut dims = Vec::with_capacity(input.dims.len().saturating_sub(end - start));
    dims.extend_from_slice(&input.dims[..start]);
    let flattened = input.dims[start..=end]
        .iter()
        .cloned()
        .fold(DimExpr::Const(1), |lhs, rhs| {
            DimExpr::Mul(Box::new(lhs), Box::new(rhs)).simplify()
        });
    dims.push(flattened);
    dims.extend_from_slice(&input.dims[end + 1..]);
    ShapeExpr {
        rank: crate::exec::RankExpr::Static(dims.len()),
        dims,
        constraints: input.constraints.clone(),
    }
}

#[cfg(feature = "std")]
fn linear_shape(input: &ShapeExpr, weight: &ShapeExpr) -> ShapeExpr {
    let mut shape = input.clone();
    if let (Some(last), Some(output)) = (shape.dims.last_mut(), weight.dims.first()) {
        let input_width = last.clone();
        *last = output.clone();
        shape.constraints.push(crate::exec::Constraint::equal(
            input_width,
            weight.dims.get(1).cloned().unwrap_or(DimExpr::Unknown),
        ));
    }
    shape
}

fn matmul_shape(lhs: &ShapeExpr, rhs: &ShapeExpr) -> Option<ShapeExpr> {
    if lhs.dims.len() < 2 || rhs.dims.len() < 2 {
        return None;
    }
    let left_batch = ShapeExpr {
        rank: crate::exec::RankExpr::Static(lhs.dims.len() - 2),
        dims: lhs.dims[..lhs.dims.len() - 2].to_vec(),
        constraints: lhs.constraints.clone(),
    };
    let right_batch = ShapeExpr {
        rank: crate::exec::RankExpr::Static(rhs.dims.len() - 2),
        dims: rhs.dims[..rhs.dims.len() - 2].to_vec(),
        constraints: rhs.constraints.clone(),
    };
    let batches = broadcast_shapes(&left_batch, &right_batch);
    let mut result = batches.dims;
    result.push(lhs.dims[lhs.dims.len() - 2].clone());
    result.push(rhs.dims[rhs.dims.len() - 1].clone());
    Some(ShapeExpr {
        rank: crate::exec::RankExpr::Static(result.len()),
        dims: result,
        constraints: batches
            .constraints
            .into_iter()
            .chain(core::iter::once(crate::exec::Constraint::equal(
                lhs.dims[lhs.dims.len() - 1].clone(),
                rhs.dims[rhs.dims.len() - 2].clone(),
            )))
            .collect(),
    })
}

fn collect_symbols(expr: &crate::exec::DimExpr, symbols: &mut SymbolTable) {
    match expr {
        crate::exec::DimExpr::Symbol(id) => symbols.register(*id, None, None),
        crate::exec::DimExpr::NamedSymbol { id, name, identity } => {
            symbols.register(*id, Some(name.clone()), Some(identity.clone()));
        }
        crate::exec::DimExpr::NamedExpr {
            expr,
            id,
            name,
            identity,
        } => {
            symbols.register(*id, Some(name.clone()), Some(identity.clone()));
            collect_symbols(expr, symbols);
        }
        crate::exec::DimExpr::Add(lhs, rhs)
        | crate::exec::DimExpr::Sub(lhs, rhs)
        | crate::exec::DimExpr::Mul(lhs, rhs)
        | crate::exec::DimExpr::ExactDiv(lhs, rhs)
        | crate::exec::DimExpr::Broadcast(lhs, rhs)
        | crate::exec::DimExpr::Min(lhs, rhs)
        | crate::exec::DimExpr::Max(lhs, rhs) => {
            collect_symbols(lhs, symbols);
            collect_symbols(rhs, symbols);
        }
        crate::exec::DimExpr::Const(_)
        | crate::exec::DimExpr::Fresh(_)
        | crate::exec::DimExpr::NamedFresh { .. }
        | crate::exec::DimExpr::Unknown => {}
    }
}

fn collect_constraint_symbols(constraint: &crate::exec::Constraint, symbols: &mut SymbolTable) {
    match constraint {
        crate::exec::Constraint::Equal { lhs, rhs }
        | crate::exec::Constraint::BroadcastCompatible { lhs, rhs } => {
            collect_symbols(lhs, symbols);
            collect_symbols(rhs, symbols);
        }
        crate::exec::Constraint::LowerBound { value, .. }
        | crate::exec::Constraint::UpperBound { value, .. }
        | crate::exec::Constraint::Divisible { value, .. } => collect_symbols(value, symbols),
    }
}