axioval-engine 0.3.0

Trusted capability compiler and deterministic source-neutral validation runtime
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
//! Source-neutral fall-protection evidence.
//!
//! ADR 0004: a service returns what was *measured*; a capability decides what
//! it means. Here the measurement is the set of exposed horizontal edges in a
//! model, together with the candidate barriers, landings and climbable objects
//! near each one -- and how near.
//!
//! The search radii travel with the request. Broad-phase distances and
//! sampling density decide *which* candidates are worth measuring, so they are
//! measurement inputs; the heights, gaps and widths that decide whether an
//! edge is adequately guarded stay with the capability. Without this
//! separation an adapter has to read the rule declaration to size its search,
//! which is how policy leaked behind the seam in the first place.

use std::sync::Arc;

use axioval_ir::{Evidence, ObjectId};

use crate::services::reviewable_exact_evidence;

/// Why fall-protection geometry could not be measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum GuardError {
    /// A reported quantity is non-finite, or an interval is malformed.
    #[error("guard quantities must be finite and intervals ordered within [0, 1]")]
    InvalidQuantity,
    /// The evidence backing the measurement was not exact and reviewable.
    #[error("guard evidence must be exact and reviewable")]
    InexactEvidence,
    /// The adapter cannot measure fall protection for this model.
    #[error("guard measurement is unavailable")]
    Unavailable,
    /// The requested search radii are not usable.
    #[error("guard search radii must be finite and positive")]
    InvalidSearch,
}

/// How far to look for candidates, how finely to sample an edge, which
/// walking surfaces to measure, and which objects may play each role.
///
/// Measurement inputs, not thresholds: these bound the search, they do not
/// judge what is found. The surfaces come from the rule's selection, so which
/// edges are checked for fall protection is stated in the ruleset rather than
/// guessed by a host.
///
/// The candidate sets work the same way. A mesh does not say whether a body
/// is a railing or a cupboard, so without them any nearby body counts as a
/// barrier, landing or climbing aid. A set that is present restricts that role
/// to its members; an absent set leaves the role open to every body.
#[derive(Clone, Debug, PartialEq)]
pub struct GuardSearch {
    candidate_radius_metres: f64,
    sample_spacing_metres: f64,
    surfaces: Vec<ObjectId>,
    barriers: Option<Vec<ObjectId>>,
    landings: Option<Vec<ObjectId>>,
    climbables: Option<Vec<ObjectId>>,
}

/// Sorts and deduplicates a candidate set so requests compare canonically.
fn canonical(mut objects: Vec<ObjectId>) -> Vec<ObjectId> {
    objects.sort();
    objects.dedup();
    objects
}

/// Whether `object` may play a role restricted to `set`.
fn admits(set: Option<&[ObjectId]>, object: &ObjectId) -> bool {
    set.is_none_or(|set| set.binary_search(object).is_ok())
}

impl GuardSearch {
    pub fn try_new(
        candidate_radius_metres: f64,
        sample_spacing_metres: f64,
    ) -> Result<Self, GuardError> {
        let positive = |v: f64| v.is_finite() && v > 0.0;
        if !positive(candidate_radius_metres) || !positive(sample_spacing_metres) {
            return Err(GuardError::InvalidSearch);
        }
        Ok(Self {
            candidate_radius_metres,
            sample_spacing_metres,
            surfaces: Vec::new(),
            barriers: None,
            landings: None,
            climbables: None,
        })
    }
    /// Asks for these walking surfaces to be measured, in canonical order.
    #[must_use]
    pub fn with_surfaces(mut self, surfaces: Vec<ObjectId>) -> Self {
        self.surfaces = canonical(surfaces);
        self
    }
    /// Restricts barriers to these objects. An empty set admits none.
    #[must_use]
    pub fn with_barrier_candidates(mut self, barriers: Vec<ObjectId>) -> Self {
        self.barriers = Some(canonical(barriers));
        self
    }
    /// Restricts landings to these objects. An empty set admits none.
    #[must_use]
    pub fn with_landing_candidates(mut self, landings: Vec<ObjectId>) -> Self {
        self.landings = Some(canonical(landings));
        self
    }
    /// Restricts climbing aids to these objects. An empty set admits none.
    #[must_use]
    pub fn with_climbable_candidates(mut self, climbables: Vec<ObjectId>) -> Self {
        self.climbables = Some(canonical(climbables));
        self
    }
    /// Walking surfaces the caller asks to be measured.
    pub fn surfaces(&self) -> &[ObjectId] {
        &self.surfaces
    }
    /// Objects allowed to count as barriers, or `None` when any body may.
    pub fn barrier_candidates(&self) -> Option<&[ObjectId]> {
        self.barriers.as_deref()
    }
    /// Objects allowed to count as landings, or `None` when any body may.
    pub fn landing_candidates(&self) -> Option<&[ObjectId]> {
        self.landings.as_deref()
    }
    /// Objects allowed to count as climbing aids, or `None` when any body may.
    pub fn climbable_candidates(&self) -> Option<&[ObjectId]> {
        self.climbables.as_deref()
    }
    /// Whether `object` may be reported as a barrier.
    pub fn admits_barrier(&self, object: &ObjectId) -> bool {
        admits(self.barrier_candidates(), object)
    }
    /// Whether `object` may be reported as a landing.
    pub fn admits_landing(&self, object: &ObjectId) -> bool {
        admits(self.landing_candidates(), object)
    }
    /// Whether `object` may be reported as a climbing aid.
    pub fn admits_climbable(&self, object: &ObjectId) -> bool {
        admits(self.climbable_candidates(), object)
    }
    pub fn candidate_radius_metres(&self) -> f64 {
        self.candidate_radius_metres
    }
    pub fn sample_spacing_metres(&self) -> f64 {
        self.sample_spacing_metres
    }
}

/// An element near an exposed edge, with the geometry a policy needs.
#[derive(Clone, Debug, PartialEq)]
pub struct GuardCandidate {
    element: ObjectId,
    horizontal_gap_metres: f64,
    /// Height of the candidate's top above the walking surface. Negative when
    /// the candidate lies below it, which is how a landing is distinguished
    /// from a barrier.
    top_offset_metres: f64,
    /// Portion of the edge this candidate covers, normalised to `[0, 1]`.
    edge_interval: [f64; 2],
    landing_width_metres: f64,
    /// Top of a curb beneath the candidate, when one exists.
    curb_top_offset_metres: Option<f64>,
}

impl GuardCandidate {
    pub fn try_new(
        element: ObjectId,
        horizontal_gap_metres: f64,
        top_offset_metres: f64,
        edge_interval: [f64; 2],
        landing_width_metres: f64,
        curb_top_offset_metres: Option<f64>,
    ) -> Result<Self, GuardError> {
        let finite = |v: f64| v.is_finite();
        if !finite(horizontal_gap_metres)
            || !finite(top_offset_metres)
            || !finite(landing_width_metres)
            || horizontal_gap_metres < 0.0
            || landing_width_metres < 0.0
            || curb_top_offset_metres.is_some_and(|v| !v.is_finite())
        {
            return Err(GuardError::InvalidQuantity);
        }
        // A coverage interval outside [0, 1] or running backwards cannot be
        // unioned with its neighbours, and would silently distort coverage.
        let [start, end] = edge_interval;
        if !finite(start) || !finite(end) || start < 0.0 || end > 1.0 || start > end {
            return Err(GuardError::InvalidQuantity);
        }
        Ok(Self {
            element,
            horizontal_gap_metres,
            top_offset_metres,
            edge_interval,
            landing_width_metres,
            curb_top_offset_metres,
        })
    }

    pub fn element(&self) -> &ObjectId {
        &self.element
    }
    pub fn horizontal_gap_metres(&self) -> f64 {
        self.horizontal_gap_metres
    }
    pub fn top_offset_metres(&self) -> f64 {
        self.top_offset_metres
    }
    pub fn edge_interval(&self) -> [f64; 2] {
        self.edge_interval
    }
    pub fn landing_width_metres(&self) -> f64 {
        self.landing_width_metres
    }
    pub fn curb_top_offset_metres(&self) -> Option<f64> {
        self.curb_top_offset_metres
    }
}

/// An object next to a barrier that could be climbed to defeat it.
#[derive(Clone, Debug, PartialEq)]
pub struct ClimbableCandidate {
    element: ObjectId,
    barrier: ObjectId,
    distance_to_barrier_metres: f64,
    top_offset_metres: f64,
    minimum_side_length_metres: f64,
}

impl ClimbableCandidate {
    pub fn try_new(
        element: ObjectId,
        barrier: ObjectId,
        distance_to_barrier_metres: f64,
        top_offset_metres: f64,
        minimum_side_length_metres: f64,
    ) -> Result<Self, GuardError> {
        if !distance_to_barrier_metres.is_finite()
            || !top_offset_metres.is_finite()
            || !minimum_side_length_metres.is_finite()
            || distance_to_barrier_metres < 0.0
            || minimum_side_length_metres < 0.0
        {
            return Err(GuardError::InvalidQuantity);
        }
        Ok(Self {
            element,
            barrier,
            distance_to_barrier_metres,
            top_offset_metres,
            minimum_side_length_metres,
        })
    }
    pub fn element(&self) -> &ObjectId {
        &self.element
    }
    pub fn barrier(&self) -> &ObjectId {
        &self.barrier
    }
    pub fn distance_to_barrier_metres(&self) -> f64 {
        self.distance_to_barrier_metres
    }
    pub fn top_offset_metres(&self) -> f64 {
        self.top_offset_metres
    }
    pub fn minimum_side_length_metres(&self) -> f64 {
        self.minimum_side_length_metres
    }
}

/// One exposed edge of a walking surface, and what sits near it.
#[derive(Clone, Debug, PartialEq)]
pub struct GuardEdge {
    surface: ObjectId,
    barriers: Vec<GuardCandidate>,
    landings: Vec<GuardCandidate>,
    climbables: Vec<ClimbableCandidate>,
}

impl GuardEdge {
    pub fn new(
        surface: ObjectId,
        barriers: Vec<GuardCandidate>,
        landings: Vec<GuardCandidate>,
        climbables: Vec<ClimbableCandidate>,
    ) -> Self {
        Self {
            surface,
            barriers,
            landings,
            climbables,
        }
    }
    pub fn surface(&self) -> &ObjectId {
        &self.surface
    }
    pub fn barriers(&self) -> &[GuardCandidate] {
        &self.barriers
    }
    pub fn landings(&self) -> &[GuardCandidate] {
        &self.landings
    }
    pub fn climbables(&self) -> &[ClimbableCandidate] {
        &self.climbables
    }

    /// Fraction of this edge covered by candidates whose gap is within
    /// `maximum_gap_metres`, unioning overlapping intervals.
    ///
    /// Union rather than sum: two barriers covering the same half of an edge
    /// guard half of it, not all of it. Summing would let overlapping rails
    /// hide an unguarded run.
    pub fn covered_fraction(candidates: &[GuardCandidate], maximum_gap_metres: f64) -> f64 {
        let mut intervals: Vec<[f64; 2]> = candidates
            .iter()
            .filter(|candidate| candidate.horizontal_gap_metres() <= maximum_gap_metres)
            .map(GuardCandidate::edge_interval)
            .collect();
        intervals.sort_by(|a, b| a[0].total_cmp(&b[0]));
        let mut covered = 0.0;
        let mut cursor = f64::NEG_INFINITY;
        for [start, end] in intervals {
            let from = start.max(cursor);
            if end > from {
                covered += end - from;
                cursor = end;
            }
        }
        covered
    }
}

/// Measured fall-protection geometry for a model.
#[derive(Clone, Debug, PartialEq)]
pub struct GuardEvidence {
    edges: Vec<GuardEdge>,
    evaluated_surfaces: usize,
    evidence: Evidence,
}

impl GuardEvidence {
    pub fn try_new(
        edges: Vec<GuardEdge>,
        evaluated_surfaces: usize,
        evidence: Evidence,
    ) -> Result<Self, GuardError> {
        if !reviewable_exact_evidence(&evidence) {
            return Err(GuardError::InexactEvidence);
        }
        Ok(Self {
            edges,
            evaluated_surfaces,
            evidence,
        })
    }
    pub fn edges(&self) -> &[GuardEdge] {
        &self.edges
    }
    /// How many walking surfaces the measurement considered.
    pub fn evaluated_surfaces(&self) -> usize {
        self.evaluated_surfaces
    }
    pub fn evidence(&self) -> &Evidence {
        &self.evidence
    }
}

/// Measures exposed edges and the elements that could guard them.
///
/// ADR 0004: every method returns a measurement. None returns a finding.
pub trait GuardService: Send + Sync + 'static {
    fn measure_guard_edges(&self, search: GuardSearch) -> Result<GuardEvidence, GuardError>;
}

/// Registry handle for a [`GuardService`].
#[derive(Clone)]
pub struct GuardServiceHandle(Arc<dyn GuardService>);

impl GuardServiceHandle {
    pub fn new(service: Arc<dyn GuardService>) -> Self {
        Self(service)
    }
    pub fn measure_guard_edges(&self, search: GuardSearch) -> Result<GuardEvidence, GuardError> {
        self.0.measure_guard_edges(search)
    }
}

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

    fn oid(local: &str) -> ObjectId {
        ObjectId::new(SourceId::new("cad", "m").unwrap(), local).unwrap()
    }
    fn candidate(gap: f64, interval: [f64; 2]) -> GuardCandidate {
        GuardCandidate::try_new(oid("rail"), gap, 1.1, interval, 0.0, None).unwrap()
    }

    /// Two rails guarding the same half of an edge guard half of it. Summing
    /// would report full coverage and hide the unguarded run.
    #[test]
    fn overlapping_candidates_are_unioned_not_summed() {
        let covered = GuardEdge::covered_fraction(
            &[candidate(0.0, [0.0, 0.5]), candidate(0.0, [0.25, 0.5])],
            0.1,
        );
        assert!((covered - 0.5).abs() < 1.0e-9, "{covered}");
    }

    #[test]
    fn candidates_beyond_the_gap_do_not_count_as_coverage() {
        let covered = GuardEdge::covered_fraction(&[candidate(0.9, [0.0, 1.0])], 0.1);
        assert!(covered.abs() < 1.0e-9, "{covered}");
    }

    #[test]
    fn disjoint_candidates_accumulate() {
        let covered = GuardEdge::covered_fraction(
            &[candidate(0.0, [0.0, 0.25]), candidate(0.0, [0.75, 1.0])],
            0.1,
        );
        assert!((covered - 0.5).abs() < 1.0e-9, "{covered}");
    }

    #[test]
    fn malformed_intervals_are_refused() {
        for interval in [[0.5, 0.25], [-0.1, 0.5], [0.0, 1.5], [f64::NAN, 1.0]] {
            assert_eq!(
                GuardCandidate::try_new(oid("r"), 0.0, 1.0, interval, 0.0, None),
                Err(GuardError::InvalidQuantity)
            );
        }
    }

    #[test]
    fn non_positive_search_radii_are_refused() {
        assert_eq!(
            GuardSearch::try_new(0.0, 0.1),
            Err(GuardError::InvalidSearch)
        );
        assert_eq!(
            GuardSearch::try_new(1.0, 0.0),
            Err(GuardError::InvalidSearch)
        );
        assert!(GuardSearch::try_new(1.0, 0.1).is_ok());
    }

    /// An absent set admits every body; a present one only its members, and
    /// an empty one none at all.
    #[test]
    fn candidate_sets_restrict_only_their_own_role() {
        let open = GuardSearch::try_new(1.0, 0.1).unwrap();
        assert!(open.admits_barrier(&oid("cupboard")));
        assert!(open.admits_landing(&oid("cupboard")));
        assert!(open.admits_climbable(&oid("cupboard")));

        let restricted = open
            .with_barrier_candidates(vec![oid("rail"), oid("rail")])
            .with_landing_candidates(Vec::new());
        assert_eq!(restricted.barrier_candidates(), Some(&[oid("rail")][..]));
        assert!(restricted.admits_barrier(&oid("rail")));
        assert!(!restricted.admits_barrier(&oid("cupboard")));
        assert!(!restricted.admits_landing(&oid("terrace")));
        assert!(restricted.admits_climbable(&oid("cupboard")));
    }
}