cadmpeg-ir 0.6.2

CAD data model, validation, diffing, and codec API for cadmpeg.
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
// SPDX-License-Identifier: Apache-2.0
//! Recursion depth and local work slices for geometry evaluation.

use std::cell::Cell;

use cadmpeg_core::decode::{
    u64_from_index, DecodeContext, DepthGuard, ResourceDimension, ResourceFailure, ResourceLimit,
    WorkBudget,
};

use super::EvaluationFailure;

const INDEPENDENT_EVALUATION_DEPTH: usize = 256;

/// Local work cap for one model evaluation that runs without a caller's slice.
///
/// Model carriers may share a support below two readers, and the cycle check
/// covers only the active path, so a carrier chain stated by a few records
/// can request work exponential in its nesting depth.
const MAX_MODEL_EVALUATION_WORK: usize = 1 << 24;

/// Local work cap for the model evaluations of one validation pass.
///
/// Each evaluation of the pass runs under a slice of at most
/// [`MAX_MODEL_EVALUATION_WORK`] drawn from this allowance, so many readers of
/// one costly carrier do not multiply the per-evaluation cap.
const MAX_MODEL_PASS_EVALUATION_WORK: usize = 1 << 30;

/// Why an evaluation work charge was not admitted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EvaluationRefusal {
    /// The evaluation's local work slice ran out. The decode session continues.
    WorkExhausted,
    /// The decode session refused. The session keeps this refusal.
    ResourceLimit(ResourceLimit),
}

impl From<ResourceLimit> for EvaluationRefusal {
    fn from(limit: ResourceLimit) -> Self {
        Self::ResourceLimit(limit)
    }
}

impl EvaluationRefusal {
    /// No value for an exhausted work slice; the session refusal otherwise.
    pub(super) fn absent<T>(self) -> Result<Option<T>, ResourceLimit> {
        match self {
            Self::WorkExhausted => Ok(None),
            Self::ResourceLimit(limit) => Err(limit),
        }
    }
}

#[cfg(test)]
impl EvaluationRefusal {
    /// The session refusal of an evaluation that runs without a work slice.
    pub(super) fn into_limit(self) -> ResourceLimit {
        match self {
            Self::ResourceLimit(limit) => limit,
            Self::WorkExhausted => panic!("an evaluation without a work slice exhausted one"),
        }
    }
}

/// Evaluation nests under the caller's decode session or an independent depth limit.
#[derive(Clone, Copy)]
pub enum EvaluationAdmission<'ctx, 'arena> {
    /// Count nesting against this live decode context.
    Decode(&'ctx DecodeContext<'arena>),
    /// Use an independent depth limit of 256 and, for a model evaluation, a
    /// fresh work slice.
    Standard,
    /// Evaluate within a work slice established by `within_work_slice`.
    WorkSlice(EvaluationWorkSlice<'ctx, 'arena>),
}

/// A local work slice bound to its recursion policy.
#[derive(Clone, Copy)]
pub struct EvaluationWorkSlice<'ctx, 'arena> {
    policy: WorkSlicePolicy<'ctx, 'arena>,
}

/// A session slice counts each evaluation step; an independent slice counts
/// the stored representation's evaluation cost. A standalone slice counts
/// each step with no decode session behind it.
#[derive(Clone, Copy)]
enum WorkSlicePolicy<'ctx, 'arena> {
    Independent(&'ctx WorkBudget),
    Standalone(&'ctx WorkBudget),
    Session {
        context: &'ctx DecodeContext<'arena>,
        work: &'ctx WorkBudget,
    },
}

impl<'ctx, 'arena> From<&'ctx DecodeContext<'arena>> for EvaluationAdmission<'ctx, 'arena> {
    fn from(context: &'ctx DecodeContext<'arena>) -> Self {
        Self::Decode(context)
    }
}

impl<'ctx, 'arena> EvaluationAdmission<'ctx, 'arena> {
    /// Model carriers share the caller's depth, cycle path and work slice.
    /// An admission without a slice evaluates under a fresh slice of
    /// [`MAX_MODEL_EVALUATION_WORK`].
    pub(super) fn within_model<T, R>(
        self,
        run: impl for<'frame> FnOnce(
            EvaluationAdmission<'frame, 'frame>,
        ) -> Result<T, EvaluationFailure<R>>,
    ) -> Result<T, EvaluationFailure<R>> {
        let evaluate = |admission: EvaluationAdmission<'_, '_>| {
            let scratch = super::decode::Scratch::new(admission);
            scratch.unless_refused()?;
            let result = run(admission);
            let result = match admission.work_slice() {
                Some(_) => super::ModelEvaluationDepthGuard::finish_sliced(admission, result),
                None => result,
            };
            scratch.settle(result)
        };
        let work = WorkBudget::new(MAX_MODEL_EVALUATION_WORK);
        match self {
            Self::Decode(_) => self.within_work_slice(&work, evaluate),
            Self::Standard => evaluate(EvaluationAdmission::WorkSlice(EvaluationWorkSlice {
                policy: WorkSlicePolicy::Standalone(&work),
            })),
            Self::WorkSlice(_) => evaluate(self),
        }
    }

    /// An independent slice counts no evaluation steps, so a cycle ends its
    /// walk by exhausting it.
    pub(super) fn independent_work_slice(self) -> Option<&'ctx WorkBudget> {
        match self {
            Self::WorkSlice(EvaluationWorkSlice {
                policy: WorkSlicePolicy::Independent(work),
            }) => Some(work),
            _ => None,
        }
    }

    pub(super) fn work_slice(self) -> Option<&'ctx WorkBudget> {
        match self {
            Self::WorkSlice(EvaluationWorkSlice {
                policy:
                    WorkSlicePolicy::Independent(work)
                    | WorkSlicePolicy::Standalone(work)
                    | WorkSlicePolicy::Session { work, .. },
            }) => Some(work),
            Self::Decode(_) | Self::Standard => None,
        }
    }

    /// Each model carrier consumes one work step before reading its payload.
    /// An exhausted slice is [`EvaluationFailure::WorkExhausted`] unless the
    /// session refused behind it.
    pub(super) fn model_step<R>(self) -> Result<(), EvaluationFailure<R>> {
        match self.work_slice() {
            Some(work) if !work.charge() => Err(self.exhausted().into()),
            _ => Ok(()),
        }
    }

    /// Run one evaluation under a bounded slice of `parent`. The child's
    /// consumption transfers to the parent once.
    ///
    /// A slice that runs out leaves the parent exhausted and the decode
    /// session unrefused; the evaluation reports
    /// [`EvaluationFailure::WorkExhausted`]. A session refusal before or
    /// after the evaluation is its result.
    pub fn within_work_slice<T, R>(
        self,
        parent: &WorkBudget,
        run: impl for<'slice> FnOnce(
            EvaluationAdmission<'slice, 'slice>,
        ) -> Result<T, EvaluationFailure<R>>,
    ) -> Result<T, EvaluationFailure<R>> {
        match self.context() {
            Some(context) => {
                session_refusal(context)?;
                let child = WorkBudget::new(parent.remaining());
                let result = run(EvaluationAdmission::WorkSlice(EvaluationWorkSlice {
                    policy: WorkSlicePolicy::Session {
                        context,
                        work: &child,
                    },
                }));
                // A transfer that does not fit exhausts the parent; a child
                // that ran out leaves the parent exhausted as well.
                if parent.consume_child(&child).is_ok() && child.exhausted() {
                    parent.exhaust();
                }
                session_refusal(context)?;
                result
            }
            None => {
                let policy = match self {
                    Self::WorkSlice(EvaluationWorkSlice {
                        policy: WorkSlicePolicy::Standalone(_),
                    }) => WorkSlicePolicy::Standalone(parent),
                    _ => WorkSlicePolicy::Independent(parent),
                };
                run(EvaluationAdmission::WorkSlice(EvaluationWorkSlice {
                    policy,
                }))
            }
        }
    }

    pub(super) fn context(self) -> Option<&'ctx DecodeContext<'arena>> {
        match self {
            Self::Decode(context) => Some(context),
            Self::Standard => None,
            Self::WorkSlice(EvaluationWorkSlice {
                policy: WorkSlicePolicy::Session { context, .. },
            }) => Some(context),
            Self::WorkSlice(EvaluationWorkSlice {
                policy: WorkSlicePolicy::Independent(_) | WorkSlicePolicy::Standalone(_),
            }) => None,
        }
    }

    pub(super) fn independent_cost<R>(
        self,
        cost: Option<usize>,
    ) -> Result<(), EvaluationFailure<R>> {
        match self {
            Self::WorkSlice(EvaluationWorkSlice {
                policy: WorkSlicePolicy::Independent(work),
            }) => cost
                .is_some_and(|cost| work.charge_by(cost))
                .then_some(())
                .ok_or(EvaluationFailure::WorkExhausted),
            _ => Ok(()),
        }
    }

    /// Count evaluation steps against a session or standalone slice. A slice
    /// that cannot cover them is [`EvaluationRefusal::WorkExhausted`] unless
    /// the session refused behind it; the session stays unrefused.
    pub(super) fn work(self, count: usize) -> Result<(), EvaluationRefusal> {
        match self {
            Self::WorkSlice(EvaluationWorkSlice {
                policy: WorkSlicePolicy::Session { work, .. } | WorkSlicePolicy::Standalone(work),
            }) if !work.charge_by(count) => Err(self.exhausted()),
            _ => Ok(()),
        }
    }

    /// The refusal this admission already holds: the session's refusal, or
    /// an exhausted session slice.
    pub(super) fn refusal(self) -> Option<EvaluationRefusal> {
        let refusal = self
            .context()
            .and_then(DecodeContext::resource_refusal)
            .map(EvaluationRefusal::ResourceLimit);
        match self {
            Self::WorkSlice(EvaluationWorkSlice {
                policy: WorkSlicePolicy::Session { work, .. } | WorkSlicePolicy::Standalone(work),
            }) if work.exhausted() => refusal.or(Some(EvaluationRefusal::WorkExhausted)),
            _ => refusal,
        }
    }

    /// An exhausted slice, or the session refusal behind it.
    fn exhausted(self) -> EvaluationRefusal {
        self.context()
            .and_then(DecodeContext::resource_refusal)
            .map_or(
                EvaluationRefusal::WorkExhausted,
                EvaluationRefusal::ResourceLimit,
            )
    }

    pub(super) fn enter<'scratch>(
        self,
        depth: &'scratch Cell<usize>,
    ) -> Result<EvaluationDepthGuard<'scratch>, ResourceLimit>
    where
        'ctx: 'scratch,
    {
        match self.context() {
            Some(context) => context
                .enter_nested_limit("geometry evaluation nesting")
                .map(|guard| EvaluationDepthGuard::Decode { _guard: guard }),
            None => {
                if depth.get() >= INDEPENDENT_EVALUATION_DEPTH {
                    return Err(ResourceLimit {
                        dimension: ResourceDimension::RecursionDepth,
                        reason: ResourceFailure::BudgetExceeded,
                        limit: u64_from_index(INDEPENDENT_EVALUATION_DEPTH),
                        used: u64_from_index(depth.get()),
                        additional: 1,
                        operation: "independent geometry evaluation nesting",
                    });
                }
                depth.set(depth.get() + 1);
                Ok(EvaluationDepthGuard::Standard { depth })
            }
        }
    }
}

fn session_refusal<R>(context: &DecodeContext<'_>) -> Result<(), EvaluationFailure<R>> {
    context
        .resource_refusal()
        .map_or(Ok(()), |limit| Err(EvaluationFailure::ResourceLimit(limit)))
}

/// The model evaluation work of one validation pass.
///
/// An evaluation that runs out of its slice reports
/// [`EvaluationFailure::WorkExhausted`]; the pass and the decode session go
/// on, and the pass counts it against the cap that ran out.
pub(crate) struct ModelEvaluationPass {
    allowance: WorkBudget,
    capped: Cell<usize>,
    starved: Cell<usize>,
}

impl ModelEvaluationPass {
    pub(crate) fn new() -> Self {
        Self::with_allowance(MAX_MODEL_PASS_EVALUATION_WORK)
    }

    fn with_allowance(allowance: usize) -> Self {
        Self {
            allowance: WorkBudget::new(allowance),
            capped: Cell::new(0),
            starved: Cell::new(0),
        }
    }

    /// Run one model evaluation under a slice of the pass allowance.
    pub(crate) fn evaluate<T, R>(
        &self,
        admission: EvaluationAdmission<'_, '_>,
        run: impl for<'slice> FnOnce(
            EvaluationAdmission<'slice, 'slice>,
        ) -> Result<T, EvaluationFailure<R>>,
    ) -> Result<T, EvaluationFailure<R>> {
        let slice = self.allowance.child_slice(MAX_MODEL_EVALUATION_WORK);
        let full = slice.remaining() == MAX_MODEL_EVALUATION_WORK;
        let result = admission.within_work_slice(&slice, run);
        let ran_out = slice.exhausted();
        // The slice is no larger than the allowance's remainder, so the
        // transfer fits; an allowance it empties refuses the next slice.
        let transferred = self.allowance.consume_child(&slice).is_ok();
        if ran_out || !transferred {
            let count = if full { &self.capped } else { &self.starved };
            count.set(count.get() + 1);
        }
        result
    }

    /// One warning per cap that skipped an evaluation of this pass.
    pub(crate) fn report(&self, findings: &mut Vec<crate::report::check::Finding>) {
        for (count, cap, limit) in [
            (
                self.capped.get(),
                "MAX_MODEL_EVALUATION_WORK",
                MAX_MODEL_EVALUATION_WORK,
            ),
            (
                self.starved.get(),
                "MAX_MODEL_PASS_EVALUATION_WORK",
                MAX_MODEL_PASS_EVALUATION_WORK,
            ),
        ] {
            if count > 0 {
                findings.push(crate::report::check::Finding {
                    check: crate::report::check::Check::GeometricConsistency,
                    severity: crate::report::Severity::Warning,
                    message: format!(
                        "{count} model carrier evaluations reached the local work cap {cap} \
                         ({limit} steps); their geometric consistency checks were skipped"
                    ),
                    entity: None,
                    related: Vec::new(),
                });
            }
        }
    }
}

impl crate::ids::comparison::sealed::TextWork for EvaluationAdmission<'_, '_> {}

impl crate::ids::comparison::TextWork for EvaluationAdmission<'_, '_> {
    type Error = EvaluationRefusal;
    fn comparison_work(
        &self,
        count: u64,
        _operation: &'static str,
    ) -> Result<(), EvaluationRefusal> {
        usize::try_from(count).map_or(Err(EvaluationRefusal::WorkExhausted), |count| {
            self.work(count)
        })
    }
}

impl crate::index::sealed::IndexQuery for EvaluationAdmission<'_, '_> {}

impl crate::index::IndexQuery for EvaluationAdmission<'_, '_> {
    type Error = EvaluationRefusal;
    type Output<T> = Result<T, EvaluationRefusal>;
    fn finish<T>(&self, result: Result<T, EvaluationRefusal>) -> Self::Output<T> {
        result
    }
    fn work(&self, count: usize, _operation: &'static str) -> Result<(), EvaluationRefusal> {
        EvaluationAdmission::work(*self, count)
    }
}

pub(super) enum EvaluationDepthGuard<'scratch> {
    Decode { _guard: DepthGuard<'scratch> },
    Standard { depth: &'scratch Cell<usize> },
}

impl Drop for EvaluationDepthGuard<'_> {
    fn drop(&mut self) {
        if let Self::Standard { depth } = self {
            depth.set(depth.get() - 1);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::EvaluationAdmission;
    use crate::eval::EvaluationFailure;
    use cadmpeg_core::decode::{
        DecodeArena, DecodeContext, DecodePolicy, ResourceDimension, WorkBudget,
    };
    use cadmpeg_core::CodecError;

    #[test]
    fn model_text_comparison_exhausts_only_its_local_slice() {
        // equal("alpha", "alpha") takes one length step and five byte steps.
        for allowance in 0..=6_usize {
            let arena = DecodeArena::new();
            let policy = DecodePolicy::service();
            let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
            let parent = WorkBudget::new(allowance);
            let result: Result<bool, EvaluationFailure<()>> = EvaluationAdmission::Decode(&ctx)
                .within_work_slice(&parent, |admission| {
                    crate::ids::comparison::equal(
                        &admission,
                        "alpha",
                        "alpha",
                        "model text comparison",
                    )
                    .map_err(EvaluationFailure::from)
                });
            assert_eq!(parent.consumed(), allowance);
            if allowance < 6 {
                // The exhausted slice is local: the session keeps running.
                assert_eq!(result, Err(EvaluationFailure::WorkExhausted));
                assert!(parent.exhausted());
                assert_eq!(ctx.resource_refusal(), None);
            } else {
                assert_eq!(result, Ok(true));
            }
            assert!(ctx.finish_session().is_ok());
        }
        assert_eq!(
            crate::ids::comparison::compare(
                &EvaluationAdmission::Standard,
                "é",
                "ê",
                "standard text comparison"
            )
            .unwrap(),
            std::cmp::Ordering::Less
        );
    }

    #[test]
    fn model_entries_return_the_session_depth_refusal() {
        use crate::geometry::{
            Curve, CurveGeometry, SolvedCurveGeometry, SolvedSurfaceGeometry, Surface,
            SurfaceGeometry,
        };
        use crate::math::{Point3, Vector3};
        let mut ir = crate::CadIr::empty();
        let curve = crate::ids::CurveId::mint("test:model:curve#line").unwrap();
        let surface = crate::ids::SurfaceId::mint("test:model:surface#plane").unwrap();
        ir.model.curves.push(Curve {
            parameter_range: None,
            id: curve.clone(),
            geometry: CurveGeometry::Solved(SolvedCurveGeometry::Line(
                crate::geometry::analytic::LineCurve::try_new(
                    Point3::new(0.0, 0.0, 0.0),
                    Vector3::new(1.0, 0.0, 0.0),
                )
                .unwrap(),
            )),
            source_object: None,
        });
        ir.model.surfaces.push(Surface {
            id: surface.clone(),
            geometry: SurfaceGeometry::Solved(SolvedSurfaceGeometry::Plane(
                crate::geometry::analytic::PlaneSurface::try_new(
                    Point3::new(0.0, 0.0, 0.0),
                    Vector3::new(0.0, 0.0, 1.0),
                    Vector3::new(1.0, 0.0, 0.0),
                )
                .unwrap(),
            )),
            source_object: None,
        });
        let index = crate::index::ModelIndex::build(&ir);
        for route in 0..4 {
            let mut policy = DecodePolicy::service();
            policy.limits.max_recursion_depth = 0;
            let arena = DecodeArena::new();
            let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
            let evaluate = || match route {
                0 => crate::eval::model_curve_point_by_id(
                    EvaluationAdmission::Decode(&ctx),
                    &index,
                    &curve,
                    0.5,
                ),
                1 => crate::eval::model_surface_point_by_id(
                    EvaluationAdmission::Decode(&ctx),
                    &index,
                    &surface,
                    0.5,
                    0.5,
                ),
                2 => crate::eval::model_surface_partials_by_id(
                    EvaluationAdmission::Decode(&ctx),
                    &index,
                    &surface,
                    0.5,
                    0.5,
                )
                .map(|partials| partials.point),
                _ => crate::eval::model_surface_point(
                    EvaluationAdmission::Decode(&ctx),
                    &ir,
                    &ir.model.surfaces[0].geometry,
                    0.5,
                    0.5,
                ),
            };
            let EvaluationFailure::ResourceLimit(first) = evaluate().unwrap_err() else {
                panic!("a model depth refusal stays a resource error");
            };
            assert_eq!(first.dimension, ResourceDimension::RecursionDepth);
            assert_eq!((first.limit, first.used), (0, 0));
            assert!(first.additional > 0);
            assert_eq!(evaluate(), Err(EvaluationFailure::ResourceLimit(first)));
            assert!(
                matches!(ctx.finish_session(), Err(CodecError::ResourceLimit(sticky)) if sticky == first)
            );
        }
    }

    #[test]
    fn model_work_slice_keeps_cycles_distinct_from_resource_refusal() {
        use crate::geometry::{
            Curve, CurveGeometry, ProceduralCurve, ProceduralCurveDefinition, SolvedCurveGeometry,
        };
        let mut ir = crate::CadIr::empty();
        let id = crate::ids::CurveId::mint("test:model:curve#cycle").unwrap();
        ir.model.curves.push(Curve {
            parameter_range: None,
            id: id.clone(),
            geometry: CurveGeometry::Solved(SolvedCurveGeometry::Unknown { record: None }),
            source_object: None,
        });
        ir.model
            .add_procedural_curve(
                &id,
                ProceduralCurve::new(
                    crate::ids::ProceduralCurveId::mint("test:model:procedural#cycle").unwrap(),
                    ProceduralCurveDefinition::Replica {
                        source: id.clone(),
                        transform: crate::transform::Transform::identity(),
                    },
                ),
            )
            .unwrap();
        let index = crate::index::ModelIndex::build(&ir);
        let arena = DecodeArena::new();
        let policy = DecodePolicy::service();
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let parent = WorkBudget::new(100_000);
        assert_eq!(
            EvaluationAdmission::Decode(&ctx).within_work_slice(&parent, |admission| {
                crate::eval::model_curve_point_by_id(admission, &index, &id, 0.5)
            }),
            Err(EvaluationFailure::NoValue)
        );
        assert!(ctx.finish_session().is_ok());
    }

    /// A line, then `levels` tolerant intersections. Each intersection reads
    /// two axis revolutions of the curve below, so a point of the top curve
    /// reads the bottom line `2^levels` times.
    fn doubling_model(levels: usize) -> (crate::CadIr, crate::ids::CurveId) {
        use crate::geometry::pcurve::{LinePcurve, PcurveGeometry};
        use crate::geometry::surface_payloads::AxisRevolutionSurfaceConstruction;
        use crate::geometry::{
            Curve, CurveGeometry, ProceduralCurve, ProceduralCurveDefinition, ProceduralSurface,
            ProceduralSurfaceDefinition, SolvedCurveGeometry, SolvedSurfaceGeometry, Surface,
            SurfaceGeometry, TolerantIntersectionConstruction,
            TolerantIntersectionParameterization,
        };
        use crate::ids::{CurveId, ProceduralCurveId, ProceduralSurfaceId, SurfaceId};
        use crate::math::{Point2, Point3, Vector3};

        let line = |id: &CurveId| Curve {
            parameter_range: None,
            id: id.clone(),
            geometry: CurveGeometry::Solved(SolvedCurveGeometry::Line(
                crate::geometry::analytic::LineCurve::try_new(
                    Point3::new(0.0, 0.0, 0.0),
                    Vector3::new(1.0, 0.0, 0.0),
                )
                .unwrap(),
            )),
            source_object: None,
        };
        let pcurve = PcurveGeometry::Line(
            LinePcurve::try_new(Point2::new(0.0, 0.0), Point2::new(1.0, 0.0)).unwrap(),
        );
        let mut ir = crate::CadIr::empty();
        let mut below = CurveId::mint("test:model:curve#0").unwrap();
        ir.model.curves.push(line(&below));
        for level in 1..=levels {
            let supports = [0, 1]
                .map(|side| SurfaceId::mint(format!("test:model:surface#{level}-{side}")).unwrap());
            for (side, support) in supports.iter().enumerate() {
                ir.model.surfaces.push(Surface {
                    id: support.clone(),
                    geometry: SurfaceGeometry::Solved(SolvedSurfaceGeometry::Plane(
                        crate::geometry::analytic::PlaneSurface::try_new(
                            Point3::new(0.0, 0.0, 0.0),
                            Vector3::new(0.0, 0.0, 1.0),
                            Vector3::new(1.0, 0.0, 0.0),
                        )
                        .unwrap(),
                    )),
                    source_object: None,
                });
                ir.model
                    .add_procedural_surface(
                        support,
                        ProceduralSurface::new(
                            ProceduralSurfaceId::mint(format!(
                                "test:model:procedural#surface-{level}-{side}"
                            ))
                            .unwrap(),
                            ProceduralSurfaceDefinition::AxisRevolution(
                                AxisRevolutionSurfaceConstruction::try_new(
                                    below.clone(),
                                    Point3::new(0.0, 0.0, 0.0),
                                    Vector3::new(0.0, 0.0, 1.0),
                                )
                                .unwrap(),
                            ),
                            None,
                        ),
                    )
                    .unwrap();
            }
            let curve = CurveId::mint(format!("test:model:curve#{level}")).unwrap();
            ir.model.curves.push(line(&curve));
            ir.model
                .add_procedural_curve(
                    &curve,
                    ProceduralCurve::new(
                        ProceduralCurveId::mint(format!("test:model:procedural#curve-{level}"))
                            .unwrap(),
                        ProceduralCurveDefinition::TolerantIntersection {
                            construction: TolerantIntersectionConstruction::try_new(
                                supports,
                                [Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 0.0, 0.0)],
                                1.0e-9,
                            )
                            .unwrap(),
                            parameterization: Some(
                                TolerantIntersectionParameterization::try_new(
                                    [pcurve.clone(), pcurve.clone()],
                                    [-1.0, 1.0],
                                )
                                .unwrap(),
                            ),
                            cache: None,
                        },
                    ),
                )
                .unwrap();
            below = curve;
        }
        (ir, below)
    }

    #[test]
    fn decode_model_evaluation_has_a_local_work_cap() {
        let evaluate = |levels| {
            let (ir, curve) = doubling_model(levels);
            let index = crate::index::ModelIndex::build(&ir);
            let arena = DecodeArena::new();
            let policy = DecodePolicy::service();
            let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
            let result = crate::eval::model_curve_point_by_id(
                EvaluationAdmission::Decode(&ctx),
                &index,
                &curve,
                0.5,
            );
            // Exhausting the cap skips the evaluation; the session continues.
            assert_eq!(ctx.resource_refusal(), None);
            assert!(ctx.finish_session().is_ok());
            result
        };
        assert!(evaluate(2).is_ok());
        assert_eq!(evaluate(18), Err(EvaluationFailure::WorkExhausted));
    }

    #[test]
    fn standard_model_evaluation_has_a_local_work_cap() {
        let evaluate = |levels| {
            let (ir, curve) = doubling_model(levels);
            let index = crate::index::ModelIndex::build(&ir);
            crate::eval::model_curve_point_by_id(EvaluationAdmission::Standard, &index, &curve, 0.5)
        };
        assert!(evaluate(2).is_ok());
        assert_eq!(evaluate(18), Err(EvaluationFailure::WorkExhausted));
    }

    #[test]
    fn validation_pass_evaluations_share_one_allowance() {
        const EVALUATIONS: usize = 1 << 12;
        let (ir, curve) = doubling_model(18);
        let index = crate::index::ModelIndex::build(&ir);
        let arena = DecodeArena::new();
        let policy = DecodePolicy::service();
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let evaluate = |pass: &super::ModelEvaluationPass, index, curve| {
            pass.evaluate(EvaluationAdmission::Decode(&ctx), |admission| {
                crate::eval::model_curve_point_by_id(admission, index, curve, 0.5)
            })
        };
        // One evaluation uses up a full slice, the next a slice of one step;
        // the rest find the allowance empty and stop at their first step.
        let pass = super::ModelEvaluationPass::with_allowance(super::MAX_MODEL_EVALUATION_WORK + 1);
        for _ in 0..EVALUATIONS {
            assert_eq!(
                evaluate(&pass, &index, &curve),
                Err(EvaluationFailure::WorkExhausted)
            );
        }
        assert_eq!(pass.allowance.remaining(), 0);
        let (cheap_ir, cheap_curve) = doubling_model(2);
        let cheap_index = crate::index::ModelIndex::build(&cheap_ir);
        assert_eq!(
            evaluate(&pass, &cheap_index, &cheap_curve),
            Err(EvaluationFailure::WorkExhausted)
        );
        let mut findings = Vec::new();
        pass.report(&mut findings);
        let messages: Vec<_> = findings
            .iter()
            .map(|finding| (finding.severity, finding.message.as_str()))
            .collect();
        assert_eq!(
            messages,
            [
                (
                    crate::report::Severity::Warning,
                    "1 model carrier evaluations reached the local work cap \
                     MAX_MODEL_EVALUATION_WORK (16777216 steps); their geometric consistency \
                     checks were skipped"
                ),
                (
                    crate::report::Severity::Warning,
                    "4096 model carrier evaluations reached the local work cap \
                     MAX_MODEL_PASS_EVALUATION_WORK (1073741824 steps); their geometric \
                     consistency checks were skipped"
                ),
            ]
        );
        // A fresh pass evaluates the cheap carrier and reports nothing.
        let fresh = super::ModelEvaluationPass::new();
        assert!(evaluate(&fresh, &cheap_index, &cheap_curve).is_ok());
        let mut findings = Vec::new();
        fresh.report(&mut findings);
        assert!(findings.is_empty());
        assert_eq!(ctx.resource_refusal(), None);
        assert!(ctx.finish_session().is_ok());
    }

    #[test]
    fn validation_reports_a_capped_endpoint_evaluation_as_skipped() {
        let (ir, _) = doubling_model(16);
        let report = crate::validate::validate_neutral(&ir, Vec::new()).unwrap();
        assert!(report.findings.iter().any(|finding| {
            finding.severity == crate::report::Severity::Warning
                && finding.message.contains("MAX_MODEL_EVALUATION_WORK")
        }));
        // The capped top intersection is skipped, not reported as a carrier
        // that does not evaluate.
        assert!(!report.findings.iter().any(|finding| {
            finding.entity.as_deref() == Some("test:model:procedural#curve-16")
                && finding.message.contains("does not evaluate")
        }));
    }

    #[test]
    fn exhausted_work_slice_leaves_the_session_unrefused() {
        let arena = DecodeArena::new();
        let policy = DecodePolicy::service();
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let parent = WorkBudget::new(0);
        let result: Result<(), EvaluationFailure<()>> = EvaluationAdmission::Decode(&ctx)
            .within_work_slice(&parent, |admission| {
                admission.work(1).map_err(EvaluationFailure::from)
            });
        assert_eq!(result, Err(EvaluationFailure::WorkExhausted));
        assert!(parent.exhausted());
        assert_eq!(ctx.resource_refusal(), None);
        // The next evaluation runs; its own slice is the exhausted remainder.
        let called = std::cell::Cell::new(false);
        let repeated: Result<(), EvaluationFailure<()>> = EvaluationAdmission::Decode(&ctx)
            .within_work_slice(&parent, |admission| {
                called.set(true);
                admission.work(1).map_err(EvaluationFailure::from)
            });
        assert!(called.get());
        assert_eq!(repeated, Err(EvaluationFailure::WorkExhausted));
        assert!(ctx.finish_session().is_ok());
    }

    #[test]
    fn work_slice_preserves_active_session_depth() {
        let mut policy = DecodePolicy::service();
        policy.limits.max_recursion_depth = 1;
        let arena = DecodeArena::new();
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let outer = ctx.enter_nested_limit("test outer evaluation").unwrap();
        let parent = WorkBudget::new(10);
        let depth = std::cell::Cell::new(0);
        let result: Result<(), EvaluationFailure<()>> = EvaluationAdmission::Decode(&ctx)
            .within_work_slice(&parent, |admission| {
                admission
                    .enter(&depth)
                    .map(|_guard| ())
                    .map_err(EvaluationFailure::ResourceLimit)
            });
        let EvaluationFailure::ResourceLimit(first) = result.unwrap_err() else {
            panic!("a child slice shares active depth");
        };
        assert_eq!(first.dimension, ResourceDimension::RecursionDepth);
        assert_eq!((first.limit, first.used, first.additional), (1, 1, 1));
        drop(outer);
        assert!(
            matches!(ctx.finish_session(), Err(CodecError::ResourceLimit(sticky)) if sticky == first)
        );
    }
}