axiolid-dispatch 0.3.1

Provider registration, ordering, fallback, and execution policy
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
//! Provider registration, ordering, fallback, and budget policy for mesh booleans.

use std::sync::Arc;

use axiolid_contracts::{BackendId, ExecutionOptions, GeomError, GeomResult, Operation};

use crate::device::matches_device;
use axiolid_core::BooleanOperator;
use axiolid_mesh::TriMesh;
use axiolid_mesh_boolean_contract::{conformance, BooleanOutcome, MeshBoolean};
use axiolid_mesh_contracts::SolidRequirements;

#[derive(Debug, Clone)]
struct RegisteredBoolean {
    priority: i32,
    provider: Arc<dyn MeshBoolean>,
}

/// Ordered executable providers for one narrow operation.
///
/// Fallback happens only for `Unsupported` or `Unavailable`; numerical and data
/// failures are returned immediately rather than hidden by another algorithm.
#[derive(Debug, Clone, Default)]
pub struct MeshBooleanRegistry {
    providers: Vec<RegisteredBoolean>,
    /// Caller-owned CPU context. Every dispatched provider call runs inside
    /// its pool, so a provider's internal rayon work is bounded by the
    /// embedding application's policy rather than the process-global pool.
    #[cfg(feature = "parallel")]
    execution: Option<axiolid_backend_cpu::CpuExecution>,
}

impl MeshBooleanRegistry {
    /// Empty registry.
    pub const fn new() -> Self {
        Self {
            providers: Vec::new(),
            #[cfg(feature = "parallel")]
            execution: None,
        }
    }

    /// Scope every dispatched provider call to `execution`'s local pool.
    ///
    /// This bounds whatever parallelism a provider already does; it does not
    /// make a single-threaded provider concurrent. With no provider threading
    /// it costs nothing but the `install` call.
    #[cfg(feature = "parallel")]
    #[must_use]
    pub fn with_execution(mut self, execution: axiolid_backend_cpu::CpuExecution) -> Self {
        self.execution = Some(execution);
        self
    }

    /// Register an implementation. Higher priorities run first.
    pub fn register<B>(&mut self, priority: i32, provider: B)
    where
        B: MeshBoolean + 'static,
    {
        self.register_arc(priority, Arc::new(provider));
    }

    /// Register only if the provider passes the shared conformance suite.
    ///
    /// ADR 0017 ยง6 makes conformance a *precondition* of registration rather
    /// than a test someone might remember to run. A provider that violates the
    /// contract is rejected here, with the failing report, instead of being
    /// discovered later by a caller receiving wrong geometry.
    ///
    /// [`Self::register`] remains available for tests and for deliberately
    /// partial providers; this is the door production code should use.
    ///
    /// # Errors
    ///
    /// Returns the report when the provider violates any obligation.
    pub fn register_conformant<B>(
        &mut self,
        priority: i32,
        provider: B,
    ) -> Result<(), Box<conformance::ConformanceReport>>
    where
        B: MeshBoolean + 'static,
    {
        let report = conformance::run(&provider);
        if !report.is_conformant() {
            return Err(Box::new(report));
        }
        self.register_arc(priority, Arc::new(provider));
        Ok(())
    }

    /// Register a shared trait object.
    pub fn register_arc(&mut self, priority: i32, provider: Arc<dyn MeshBoolean>) {
        self.providers
            .push(RegisteredBoolean { priority, provider });
        self.providers
            .sort_by_key(|entry| std::cmp::Reverse(entry.priority));
    }

    /// Registered providers in dispatch order.
    pub fn providers(&self) -> impl Iterator<Item = &dyn MeshBoolean> {
        self.providers.iter().map(|entry| entry.provider.as_ref())
    }

    fn dispatch(
        &self,
        options: &ExecutionOptions,
        elements: usize,
        execute: impl Fn(&dyn MeshBoolean) -> GeomResult<BooleanOutcome> + Sync,
    ) -> GeomResult<BooleanOutcome> {
        let mut last_retryable = None;
        let mut over_budget = None;
        for entry in &self.providers {
            let descriptor = entry.provider.descriptor();
            if !matches_device(options.device(), descriptor.id, descriptor.target) {
                continue;
            }
            // Budget is checked before dispatch, not after: a provider that
            // cannot fit the caller's memory bound must never get the chance to
            // allocate. Treated as retryable so a leaner provider can still run.
            if !entry
                .provider
                .scratch_requirement()
                .fits_budget(options, elements)
            {
                over_budget = Some(GeomError::BudgetExceeded { resource: "memory" });
                continue;
            }
            match self.run_scoped(&execute, entry.provider.as_ref()) {
                Ok(outcome) => return Ok(outcome),
                Err(error @ (GeomError::Unsupported { .. } | GeomError::Unavailable { .. })) => {
                    last_retryable = Some(error);
                }
                Err(error) => return Err(error),
            }
        }
        Err(last_retryable
            .or(over_budget)
            .unwrap_or(GeomError::Unsupported {
                backend: BackendId::new("mesh-boolean-registry"),
                operation: Operation::MeshBoolean,
            }))
    }

    /// Run one provider call, inside the configured pool when there is one.
    ///
    /// `CpuExecution::install` already falls through to a direct call when
    /// the context was built single-threaded, so a configured context with
    /// one worker costs nothing extra here.
    #[cfg(feature = "parallel")]
    fn run_scoped(
        &self,
        execute: &(impl Fn(&dyn MeshBoolean) -> GeomResult<BooleanOutcome> + Sync),
        provider: &dyn MeshBoolean,
    ) -> GeomResult<BooleanOutcome> {
        match &self.execution {
            Some(execution) => execution.install(|| execute(provider)),
            None => execute(provider),
        }
    }

    #[cfg(not(feature = "parallel"))]
    fn run_scoped(
        &self,
        execute: &impl Fn(&dyn MeshBoolean) -> GeomResult<BooleanOutcome>,
        provider: &dyn MeshBoolean,
    ) -> GeomResult<BooleanOutcome> {
        execute(provider)
    }

    /// Execute according to device policy with narrow fallback semantics.
    pub fn boolean(
        &self,
        subject: &TriMesh,
        tool: &TriMesh,
        operation: BooleanOperator,
        options: &ExecutionOptions,
    ) -> GeomResult<BooleanOutcome> {
        // Admissibility is contract-level and checked before any provider sees
        // the operands, so dispatch cannot change which inputs are legal.
        SolidRequirements::Oriented.validate_operands(subject, &[tool])?;
        self.dispatch(options, subject.triangle_count(), |provider| {
            provider.boolean(subject, tool, operation, options)
        })
    }

    /// Subtract many tools through one provider dispatch.
    pub fn subtract_many(
        &self,
        subject: &TriMesh,
        tools: &[TriMesh],
        options: &ExecutionOptions,
    ) -> GeomResult<BooleanOutcome> {
        let borrowed: Vec<&TriMesh> = tools.iter().collect();
        SolidRequirements::Oriented.validate_operands(subject, &borrowed)?;
        let elements =
            subject.triangle_count() + tools.iter().map(TriMesh::triangle_count).sum::<usize>();
        self.dispatch(options, elements, |provider| {
            provider.subtract_many(subject, tools, options)
        })
    }

    /// Union many solids through one provider dispatch.
    ///
    /// An empty batch is answered without consulting a provider: the union
    /// of nothing is nothing, and there is no operand to validate or size a
    /// budget against.
    pub fn union_many(
        &self,
        solids: &[TriMesh],
        options: &ExecutionOptions,
    ) -> GeomResult<BooleanOutcome> {
        let Some((first, rest)) = solids.split_first() else {
            return Ok(BooleanOutcome::new(TriMesh::default(), Default::default()));
        };
        // Union has no privileged operand, but validation is expressed as
        // subject-plus-tools. Naming the first solid the subject validates
        // exactly the same set, in the same way the provider reports it.
        let borrowed: Vec<&TriMesh> = rest.iter().collect();
        SolidRequirements::Oriented.validate_operands(first, &borrowed)?;
        let elements = solids.iter().map(TriMesh::triangle_count).sum::<usize>();
        self.dispatch(options, elements, |provider| {
            provider.union_many(solids, options)
        })
    }
}

#[cfg(test)]
mod tests {
    use axiolid_contracts::{DevicePreference, ExecutionTarget};
    /// Outward-oriented unit cube: the minimal admissible operand.
    ///
    /// Dispatch tests need a mesh that passes contract validation, because
    /// validation now runs before any provider is consulted.
    fn admissible_cube() -> TriMesh {
        let positions = vec![
            [0.0, 0.0, 0.0].into(),
            [1.0, 0.0, 0.0].into(),
            [1.0, 1.0, 0.0].into(),
            [0.0, 1.0, 0.0].into(),
            [0.0, 0.0, 1.0].into(),
            [1.0, 0.0, 1.0].into(),
            [1.0, 1.0, 1.0].into(),
            [0.0, 1.0, 1.0].into(),
        ];
        let indices = vec![
            0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7,
            6, 3, 0, 4, 3, 4, 7,
        ];
        TriMesh::new(positions, indices)
    }

    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    };

    use axiolid_contracts::{Backend, BackendDescriptor};
    use axiolid_core::Tolerance;
    use axiolid_mesh_boolean_contract::BooleanEvidence;

    use super::*;

    #[derive(Debug)]
    struct EchoBoolean {
        id: BackendId,
        target: ExecutionTarget,
    }

    impl Backend for EchoBoolean {
        fn descriptor(&self) -> BackendDescriptor {
            BackendDescriptor {
                id: self.id,
                target: self.target,
            }
        }
    }

    impl MeshBoolean for EchoBoolean {
        fn boolean(
            &self,
            subject: &TriMesh,
            _tool: &TriMesh,
            _operation: BooleanOperator,
            _options: &ExecutionOptions,
        ) -> GeomResult<BooleanOutcome> {
            Ok(BooleanOutcome::new(
                subject.clone(),
                BooleanEvidence::default(),
            ))
        }
    }

    #[derive(Debug, Clone, Copy)]
    enum ProbeResult {
        Success,
        Unsupported,
        Unavailable,
        Invalid,
    }

    #[derive(Debug)]
    struct ProbeBoolean {
        id: BackendId,
        target: ExecutionTarget,
        result: ProbeResult,
        calls: Arc<AtomicUsize>,
    }

    impl Backend for ProbeBoolean {
        fn descriptor(&self) -> BackendDescriptor {
            BackendDescriptor::new(self.id, self.target)
        }
    }

    impl MeshBoolean for ProbeBoolean {
        fn boolean(
            &self,
            subject: &TriMesh,
            _tool: &TriMesh,
            _operation: BooleanOperator,
            _options: &ExecutionOptions,
        ) -> GeomResult<BooleanOutcome> {
            self.calls.fetch_add(1, Ordering::Relaxed);
            match self.result {
                ProbeResult::Success => Ok(BooleanOutcome::new(
                    subject.clone(),
                    BooleanEvidence::default(),
                )),
                ProbeResult::Unsupported => Err(GeomError::Unsupported {
                    backend: self.id,
                    operation: Operation::MeshBoolean,
                }),
                ProbeResult::Unavailable => Err(GeomError::Unavailable {
                    backend: self.id,
                    reason: "probe unavailable".to_owned(),
                }),
                ProbeResult::Invalid => {
                    Err(GeomError::InvalidInput("probe rejected input".to_owned()))
                }
            }
        }
    }

    #[derive(Debug)]
    struct BatchBoolean {
        calls: Arc<AtomicUsize>,
    }

    impl Backend for BatchBoolean {
        fn descriptor(&self) -> BackendDescriptor {
            BackendDescriptor::new(BackendId::new("batch"), ExecutionTarget::OptimizedCpu)
        }
    }

    impl MeshBoolean for BatchBoolean {
        fn boolean(
            &self,
            _subject: &TriMesh,
            _tool: &TriMesh,
            _operation: BooleanOperator,
            _options: &ExecutionOptions,
        ) -> GeomResult<BooleanOutcome> {
            Err(GeomError::InvalidInput(
                "batch provider must use its batch override".to_owned(),
            ))
        }

        fn subtract_many(
            &self,
            subject: &TriMesh,
            _tools: &[TriMesh],
            _options: &ExecutionOptions,
        ) -> GeomResult<BooleanOutcome> {
            self.calls.fetch_add(1, Ordering::Relaxed);
            Ok(BooleanOutcome::new(
                subject.clone(),
                BooleanEvidence::default(),
            ))
        }
    }

    #[test]
    fn registry_stores_executable_traits_not_capability_flags() {
        let mut registry = MeshBooleanRegistry::new();
        registry.register(
            10,
            EchoBoolean {
                id: BackendId::new("echo"),
                target: ExecutionTarget::PortableCpu,
            },
        );
        let options = ExecutionOptions::new(Tolerance::METRE);
        let mesh = admissible_cube();
        assert_eq!(
            registry
                .boolean(&mesh, &mesh, BooleanOperator::Difference, &options)
                .expect("registered provider executes"),
            BooleanOutcome::new(mesh, BooleanEvidence::default())
        );
    }

    #[test]
    fn registry_dispatches_batch_subtraction_to_the_provider_override() {
        let calls = Arc::new(AtomicUsize::new(0));
        let mut registry = MeshBooleanRegistry::new();
        registry.register(
            10,
            BatchBoolean {
                calls: calls.clone(),
            },
        );
        let mesh = admissible_cube();
        let options = ExecutionOptions::new(Tolerance::METRE);

        assert_eq!(
            registry
                .subtract_many(&mesh, &[mesh.clone(), mesh.clone()], &options)
                .expect("batch provider executes"),
            BooleanOutcome::new(mesh, BooleanEvidence::default())
        );
        assert_eq!(calls.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn registry_falls_back_only_for_retryable_errors_and_honors_device_policy() {
        let high_calls = Arc::new(AtomicUsize::new(0));
        let unsupported_calls = Arc::new(AtomicUsize::new(0));
        let low_calls = Arc::new(AtomicUsize::new(0));
        let mut registry = MeshBooleanRegistry::new();
        registry.register(
            100,
            ProbeBoolean {
                id: BackendId::new("unavailable-gpu"),
                target: ExecutionTarget::Gpu,
                result: ProbeResult::Unavailable,
                calls: high_calls.clone(),
            },
        );
        registry.register(
            50,
            ProbeBoolean {
                id: BackendId::new("unsupported-cpu"),
                target: ExecutionTarget::OptimizedCpu,
                result: ProbeResult::Unsupported,
                calls: unsupported_calls.clone(),
            },
        );
        registry.register(
            10,
            ProbeBoolean {
                id: BackendId::new("portable-fallback"),
                target: ExecutionTarget::PortableCpu,
                result: ProbeResult::Success,
                calls: low_calls.clone(),
            },
        );
        let mesh = admissible_cube();
        let auto = ExecutionOptions::new(Tolerance::METRE);
        assert!(registry
            .boolean(&mesh, &mesh, BooleanOperator::Union, &auto)
            .is_ok());
        assert_eq!(high_calls.load(Ordering::Relaxed), 1);
        assert_eq!(unsupported_calls.load(Ordering::Relaxed), 1);
        assert_eq!(low_calls.load(Ordering::Relaxed), 1);

        let cpu = auto.clone().with_device(DevicePreference::Cpu);
        assert!(registry
            .boolean(&mesh, &mesh, BooleanOperator::Union, &cpu)
            .is_ok());
        assert_eq!(high_calls.load(Ordering::Relaxed), 1);
        assert_eq!(unsupported_calls.load(Ordering::Relaxed), 2);
        assert_eq!(low_calls.load(Ordering::Relaxed), 2);

        let invalid_calls = Arc::new(AtomicUsize::new(0));
        let skipped_calls = Arc::new(AtomicUsize::new(0));
        let mut fail_fast = MeshBooleanRegistry::new();
        fail_fast.register(
            100,
            ProbeBoolean {
                id: BackendId::new("invalid-input"),
                target: ExecutionTarget::PortableCpu,
                result: ProbeResult::Invalid,
                calls: invalid_calls.clone(),
            },
        );
        fail_fast.register(
            10,
            ProbeBoolean {
                id: BackendId::new("must-not-run"),
                target: ExecutionTarget::PortableCpu,
                result: ProbeResult::Success,
                calls: skipped_calls.clone(),
            },
        );
        assert!(matches!(
            fail_fast.boolean(&mesh, &mesh, BooleanOperator::Union, &auto),
            Err(GeomError::InvalidInput(_))
        ));
        assert_eq!(invalid_calls.load(Ordering::Relaxed), 1);
        assert_eq!(skipped_calls.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn empty_registry_returns_structured_unsupported_error() {
        let registry = MeshBooleanRegistry::new();
        let mesh = admissible_cube();
        let error = registry
            .boolean(
                &mesh,
                &mesh,
                BooleanOperator::Union,
                &ExecutionOptions::new(Tolerance::METRE),
            )
            .unwrap_err();
        assert!(matches!(
            error,
            GeomError::Unsupported {
                backend,
                operation: Operation::MeshBoolean,
            } if backend == BackendId::new("mesh-boolean-registry")
        ));
    }

    /// Records the rayon pool width it observes while running.
    ///
    /// `current_num_threads` reports the pool the call is INSIDE, so a
    /// provider dispatched through a scoped registry must see the
    /// configured width rather than the process-global one.
    #[cfg(feature = "parallel")]
    #[derive(Debug, Default)]
    struct PoolWidthBoolean {
        seen: std::sync::Mutex<Vec<usize>>,
    }

    #[cfg(feature = "parallel")]
    impl Backend for PoolWidthBoolean {
        fn descriptor(&self) -> BackendDescriptor {
            BackendDescriptor {
                id: BackendId::new("pool-width"),
                target: ExecutionTarget::PortableCpu,
            }
        }
    }

    #[cfg(feature = "parallel")]
    impl MeshBoolean for PoolWidthBoolean {
        fn boolean(
            &self,
            subject: &TriMesh,
            _tool: &TriMesh,
            _operation: BooleanOperator,
            _options: &ExecutionOptions,
        ) -> GeomResult<BooleanOutcome> {
            self.seen
                .lock()
                .expect("poisoned")
                .push(rayon::current_num_threads());
            Ok(BooleanOutcome::new(
                subject.clone(),
                BooleanEvidence::default(),
            ))
        }
    }

    /// The configured pool must actually wrap the provider call.
    ///
    /// Asserting the OBSERVED width, not just that a context was stored:
    /// a registry that accepted the context and ignored it would pass any
    /// weaker check. 3 is chosen to differ from this machine core count.
    #[test]
    #[cfg(feature = "parallel")]
    fn dispatch_runs_inside_the_configured_pool() {
        use axiolid_backend_cpu::CpuExecutionBuilder;
        use std::num::NonZeroUsize;
        use std::sync::Arc;

        let execution = CpuExecutionBuilder::new()
            .threads(NonZeroUsize::new(3).expect("nonzero"))
            .build()
            .expect("cpu execution");
        let provider = Arc::new(PoolWidthBoolean::default());
        let mut registry = MeshBooleanRegistry::new().with_execution(execution);
        registry.register_arc(0, provider.clone());

        let cube = admissible_cube();
        let options = ExecutionOptions::new(Tolerance::MILLIMETRE);
        registry
            .boolean(&cube, &cube, BooleanOperator::Union, &options)
            .expect("dispatch");

        let widths = provider.seen.lock().expect("poisoned").clone();
        assert_eq!(
            widths,
            vec![3],
            "provider must run inside the 3-worker pool"
        );
    }

    /// Negative control: without `with_execution` the provider sees the
    /// ambient pool, so the assertion above is testing the scoping and not
    /// some constant rayon happens to return.
    #[test]
    #[cfg(feature = "parallel")]
    fn an_unscoped_registry_does_not_see_the_configured_width() {
        use std::sync::Arc;

        let provider = Arc::new(PoolWidthBoolean::default());
        let mut registry = MeshBooleanRegistry::new();
        registry.register_arc(0, provider.clone());

        let cube = admissible_cube();
        let options = ExecutionOptions::new(Tolerance::MILLIMETRE);
        registry
            .boolean(&cube, &cube, BooleanOperator::Union, &options)
            .expect("dispatch");

        let widths = provider.seen.lock().expect("poisoned").clone();
        assert_eq!(widths.len(), 1, "one dispatch");
        assert_eq!(
            widths[0],
            rayon::current_num_threads(),
            "unscoped dispatch must observe the ambient pool"
        );
    }
}