omena-cascade 0.5.0

Cascade-formal substrate for Omena CSS
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
use std::{
    panic::Location,
    sync::{
        Mutex,
        atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering},
    },
};

use omena_syntax::ident::AuthoredPropertyTextV0;
use serde::Serialize;

use crate::{
    CascadeDeclaration, CascadeLevel, CascadeOutcome, SpecificityExactnessV0,
    axis_order::CascadeKeyAxisV0,
    ranking::{InexactSpecificityAdjudicationV0, adjudicate_inexact_specificity_v0},
};

static CAPTURE_ACTIVE: AtomicBool = AtomicBool::new(false);
static CAPTURED_ROWS: Mutex<Vec<CascadeRankedSetLossCensusRowV0>> = Mutex::new(Vec::new());
static CAPTURE_STATE_RECOVERY_COUNT: AtomicUsize = AtomicUsize::new(0);
static MEASUREMENT_INVOCATION_COUNT: AtomicUsize = AtomicUsize::new(0);
static RANKED_SET_OUTCOME_COUNT: AtomicUsize = AtomicUsize::new(0);
static RECOVERED_DEFINITE_OUTCOME_COUNT: AtomicUsize = AtomicUsize::new(0);
static MULTI_CANDIDATE_INEXACT_RANKED_SET_COUNT: AtomicUsize = AtomicUsize::new(0);

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum CascadeRankedSetFunctionV0 {
    CascadeProperty,
    CascadePropertyOpenWorld,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum CascadeAxisPrefixV0 {
    Level,
    LayerRank,
    /// Retained for 0.x wire compatibility. The current specification order
    /// places specificity before scope proximity, so the pre-specificity
    /// classifier cannot emit this variant.
    ScopeProximity,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum CascadeRankedSetLossClassV0 {
    RecoverableAxisDominant { axis: CascadeAxisPrefixV0 },
    AxisWinnerInexact,
    NoStrictAxisDominance,
    SingleInexactCandidate,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum CascadeRankedSetFinalOutcomeV0 {
    RankedSet,
    Definite,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CascadeRankedSetLossCandidateV0 {
    pub declaration_id: String,
    pub level: CascadeLevel,
    pub layer_rank: i32,
    pub scope_proximity: u32,
    pub specificity_exactness: SpecificityExactnessV0,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CascadeRankedSetLossCensusRowV0 {
    pub function: CascadeRankedSetFunctionV0,
    pub invocation_site: &'static str,
    pub source_path: String,
    pub property: AuthoredPropertyTextV0,
    pub declaration_ids: Vec<String>,
    pub candidate_count: usize,
    pub candidates: Vec<CascadeRankedSetLossCandidateV0>,
    pub classification: CascadeRankedSetLossClassV0,
    pub final_outcome: CascadeRankedSetFinalOutcomeV0,
    pub definite_winner_declaration_id: Option<String>,
}

impl PartialEq for CascadeRankedSetLossCensusRowV0 {
    fn eq(&self, other: &Self) -> bool {
        self.function == other.function
            && self.invocation_site == other.invocation_site
            && self.source_path == other.source_path
            && self
                .property
                .to_property_name()
                .same_as(&other.property.to_property_name())
            && self.declaration_ids == other.declaration_ids
            && self.candidate_count == other.candidate_count
            && self.candidates == other.candidates
            && self.classification == other.classification
            && self.final_outcome == other.final_outcome
            && self.definite_winner_declaration_id == other.definite_winner_declaration_id
    }
}

impl Eq for CascadeRankedSetLossCensusRowV0 {}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CascadeRankedSetLossCaptureV0 {
    pub schema_version: &'static str,
    pub product: &'static str,
    pub capture_state_recovery_count: usize,
    pub measurement_invocation_count: usize,
    pub ranked_set_outcome_count: usize,
    pub recovered_definite_outcome_count: usize,
    pub multi_candidate_inexact_ranked_set_count: usize,
    pub rows: Vec<CascadeRankedSetLossCensusRowV0>,
}

/// Captures inexactness-bail `RankedSet` outcomes produced while `operation` runs.
///
/// Capture is process-wide so worker threads participate in the same bounded
/// measurement. Nested or concurrent captures are rejected instead of merging
/// unrelated populations.
pub fn capture_cascade_ranked_set_losses<R>(
    operation: impl FnOnce() -> R,
) -> Result<(R, CascadeRankedSetLossCaptureV0), &'static str> {
    CAPTURE_ACTIVE
        .compare_exchange(false, true, AtomicOrdering::AcqRel, AtomicOrdering::Acquire)
        .map_err(|_| "cascade ranked-set loss capture is already active")?;
    CAPTURE_STATE_RECOVERY_COUNT.store(0, AtomicOrdering::Release);
    captured_rows().clear();
    MEASUREMENT_INVOCATION_COUNT.store(0, AtomicOrdering::Release);
    RANKED_SET_OUTCOME_COUNT.store(0, AtomicOrdering::Release);
    RECOVERED_DEFINITE_OUTCOME_COUNT.store(0, AtomicOrdering::Release);
    MULTI_CANDIDATE_INEXACT_RANKED_SET_COUNT.store(0, AtomicOrdering::Release);
    let guard = CaptureGuard;
    let result = operation();
    let mut rows = std::mem::take(&mut *captured_rows());
    rows.sort_by(|left, right| {
        let left_property_key = left.property.to_property_name().canonical_key();
        let right_property_key = right.property.to_property_name().canonical_key();
        (
            left.function,
            left.invocation_site,
            left.source_path.as_str(),
            left_property_key,
            left.declaration_ids.as_slice(),
        )
            .cmp(&(
                right.function,
                right.invocation_site,
                right.source_path.as_str(),
                right_property_key,
                right.declaration_ids.as_slice(),
            ))
    });
    drop(guard);
    Ok((
        result,
        CascadeRankedSetLossCaptureV0 {
            schema_version: "0",
            product: "omena-cascade.ranked-set-loss-capture",
            capture_state_recovery_count: CAPTURE_STATE_RECOVERY_COUNT
                .load(AtomicOrdering::Acquire),
            measurement_invocation_count: MEASUREMENT_INVOCATION_COUNT
                .load(AtomicOrdering::Acquire),
            ranked_set_outcome_count: RANKED_SET_OUTCOME_COUNT.load(AtomicOrdering::Acquire),
            recovered_definite_outcome_count: RECOVERED_DEFINITE_OUTCOME_COUNT
                .load(AtomicOrdering::Acquire),
            multi_candidate_inexact_ranked_set_count: MULTI_CANDIDATE_INEXACT_RANKED_SET_COUNT
                .load(AtomicOrdering::Acquire),
            rows,
        },
    ))
}

pub fn classify_cascade_ranked_set_loss(
    declarations: &[CascadeDeclaration],
) -> CascadeRankedSetLossClassV0 {
    match adjudicate_inexact_specificity_v0(declarations) {
        InexactSpecificityAdjudicationV0::Recoverable { deciding_axis, .. } => {
            CascadeRankedSetLossClassV0::RecoverableAxisDominant {
                axis: match deciding_axis {
                    CascadeKeyAxisV0::Level => CascadeAxisPrefixV0::Level,
                    CascadeKeyAxisV0::LayerRank => CascadeAxisPrefixV0::LayerRank,
                    CascadeKeyAxisV0::ScopeProximity
                    | CascadeKeyAxisV0::SpecificityIds
                    | CascadeKeyAxisV0::SpecificityClasses
                    | CascadeKeyAxisV0::SpecificityElements
                    | CascadeKeyAxisV0::SourceOrder => unreachable!(
                        "an exact winner cannot cross inexact specificity to recover on a later axis"
                    ),
                },
            }
        }
        InexactSpecificityAdjudicationV0::AxisWinnerInexact => {
            CascadeRankedSetLossClassV0::AxisWinnerInexact
        }
        InexactSpecificityAdjudicationV0::NoStrictAxisDominance => {
            CascadeRankedSetLossClassV0::NoStrictAxisDominance
        }
        InexactSpecificityAdjudicationV0::SingleInexactCandidate => {
            CascadeRankedSetLossClassV0::SingleInexactCandidate
        }
    }
}

pub(crate) fn observe_cascade_outcome(
    function: CascadeRankedSetFunctionV0,
    caller: &'static Location<'static>,
    outcome: &CascadeOutcome,
) {
    if !CAPTURE_ACTIVE.load(AtomicOrdering::Acquire) {
        return;
    }
    MEASUREMENT_INVOCATION_COUNT.fetch_add(1, AtomicOrdering::AcqRel);
    let (declarations, final_outcome, definite_winner_declaration_id) = match outcome {
        CascadeOutcome::RankedSet(declarations) => {
            RANKED_SET_OUTCOME_COUNT.fetch_add(1, AtomicOrdering::AcqRel);
            (
                declarations.clone(),
                CascadeRankedSetFinalOutcomeV0::RankedSet,
                None,
            )
        }
        CascadeOutcome::Definite {
            winner,
            also_considered,
            ..
        } => {
            let mut declarations = Vec::with_capacity(also_considered.len().saturating_add(1));
            declarations.push(winner.clone());
            declarations.extend(also_considered.iter().cloned());
            if !declarations.iter().any(|declaration| {
                declaration.specificity_exactness == SpecificityExactnessV0::Inexact
            }) {
                return;
            }
            assert_definite_inexact_outcome_is_recoverable(&declarations);
            RECOVERED_DEFINITE_OUTCOME_COUNT.fetch_add(1, AtomicOrdering::AcqRel);
            (
                declarations,
                CascadeRankedSetFinalOutcomeV0::Definite,
                Some(winner.id.clone()),
            )
        }
        CascadeOutcome::Inherit | CascadeOutcome::Top => return,
    };
    if !declarations
        .iter()
        .any(|declaration| declaration.specificity_exactness == SpecificityExactnessV0::Inexact)
    {
        return;
    }
    if final_outcome == CascadeRankedSetFinalOutcomeV0::RankedSet && declarations.len() > 1 {
        MULTI_CANDIDATE_INEXACT_RANKED_SET_COUNT.fetch_add(1, AtomicOrdering::AcqRel);
    }
    let row = CascadeRankedSetLossCensusRowV0 {
        function,
        invocation_site: invocation_site(caller.file()),
        source_path: caller.file().to_string(),
        property: declarations
            .first()
            .map(|declaration| declaration.property.clone())
            .unwrap_or_else(|| AuthoredPropertyTextV0::new("")),
        declaration_ids: declarations
            .iter()
            .map(|declaration| declaration.id.clone())
            .collect(),
        candidate_count: declarations.len(),
        candidates: declarations
            .iter()
            .map(|declaration| CascadeRankedSetLossCandidateV0 {
                declaration_id: declaration.id.clone(),
                level: declaration.key.level,
                layer_rank: declaration.key.layer_rank.get(),
                scope_proximity: declaration.key.scope_proximity,
                specificity_exactness: declaration.specificity_exactness,
            })
            .collect(),
        classification: classify_cascade_ranked_set_loss(&declarations),
        final_outcome,
        definite_winner_declaration_id,
    };
    captured_rows().push(row);
}

fn assert_definite_inexact_outcome_is_recoverable(declarations: &[CascadeDeclaration]) {
    assert!(
        matches!(
            classify_cascade_ranked_set_loss(declarations),
            CascadeRankedSetLossClassV0::RecoverableAxisDominant { .. }
        ),
        "a definite inexact outcome must be justified by an earlier exact axis"
    );
}

fn invocation_site(source_path: &str) -> &'static str {
    if source_path.ends_with("omena-query/src/style/cascade_checker/runtime_state.rs") {
        "queryRuntimeStateScenarioEvaluation"
    } else if source_path.ends_with("omena-query/src/style/cascade_checker/confidence.rs") {
        "queryCascadeMarginForEvaluation"
    } else if source_path.ends_with("omena-query/src/style/cascade_checker/replica_ensemble.rs") {
        "collectQueryReplicaEnsembleSiteOutcomes"
    } else if source_path.ends_with("omena-cascade/src/computed_value.rs") {
        "computeCascadeComputedValue"
    } else if source_path.ends_with("omena-transform-passes/src/runtime/winner_equality.rs") {
        "transformWinnerEqualityFromCascadeOutcome"
    } else {
        "unclassified"
    }
}

fn captured_rows() -> std::sync::MutexGuard<'static, Vec<CascadeRankedSetLossCensusRowV0>> {
    let (rows, recovered) = recover_captured_rows(CAPTURED_ROWS.lock(), &CAPTURED_ROWS);
    if recovered {
        CAPTURE_STATE_RECOVERY_COUNT.fetch_add(1, AtomicOrdering::AcqRel);
    }
    rows
}

fn recover_captured_rows<'a>(
    lock: std::sync::LockResult<std::sync::MutexGuard<'a, Vec<CascadeRankedSetLossCensusRowV0>>>,
    mutex: &'a Mutex<Vec<CascadeRankedSetLossCensusRowV0>>,
) -> (
    std::sync::MutexGuard<'a, Vec<CascadeRankedSetLossCensusRowV0>>,
    bool,
) {
    match lock {
        Ok(rows) => (rows, false),
        Err(poisoned) => {
            mutex.clear_poison();
            let mut rows = poisoned.into_inner();
            rows.clear();
            (rows, true)
        }
    }
}

struct CaptureGuard;

impl Drop for CaptureGuard {
    fn drop(&mut self) {
        CAPTURE_ACTIVE.store(false, AtomicOrdering::Release);
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CascadeAxisPrefixV0, CascadeRankedSetFinalOutcomeV0, CascadeRankedSetLossCensusRowV0,
        CascadeRankedSetLossClassV0, assert_definite_inexact_outcome_is_recoverable,
        capture_cascade_ranked_set_losses, classify_cascade_ranked_set_loss, recover_captured_rows,
    };
    use crate::{
        CascadeDeclaration, CascadeKey, CascadeLevel, CascadeOutcome, CascadeValue, LayerOrdinal,
        OpenWorldTieEvidence, Specificity, SpecificityExactnessV0, cascade_property,
        normalized_layer_rank,
    };

    fn declaration(
        id: &str,
        level: CascadeLevel,
        layer_ordinal: i32,
        scope_proximity: u32,
        specificity: Specificity,
        exactness: SpecificityExactnessV0,
    ) -> CascadeDeclaration {
        CascadeDeclaration {
            id: id.to_string(),
            property: omena_syntax::ident::AuthoredPropertyTextV0::new("color"),
            property_key: omena_syntax::ident::PropertyNameV0::standard("color").canonical_key(),
            value: CascadeValue::Literal(id.to_string()),
            key: CascadeKey::new(
                level,
                normalized_layer_rank(false, LayerOrdinal::new(layer_ordinal)),
                scope_proximity,
                specificity,
                0,
            ),
            open_world_tie_evidence: OpenWorldTieEvidence::NONE,
            specificity_exactness: exactness,
        }
    }

    #[test]
    fn axis_winner_exactness_changes_the_recoverability_class() {
        let lower = declaration(
            "lower",
            CascadeLevel::UserNormal,
            0,
            0,
            Specificity::new(9, 9, 9),
            SpecificityExactnessV0::Inexact,
        );
        let exact_winner = declaration(
            "winner",
            CascadeLevel::AuthorNormal,
            0,
            0,
            Specificity::ZERO,
            SpecificityExactnessV0::Exact,
        );
        assert_eq!(
            classify_cascade_ranked_set_loss(&[lower.clone(), exact_winner.clone()]),
            CascadeRankedSetLossClassV0::RecoverableAxisDominant {
                axis: CascadeAxisPrefixV0::Level
            }
        );

        let mut inexact_winner = exact_winner;
        inexact_winner.specificity_exactness = SpecificityExactnessV0::Inexact;
        assert_eq!(
            classify_cascade_ranked_set_loss(&[lower, inexact_winner]),
            CascadeRankedSetLossClassV0::AxisWinnerInexact
        );
    }

    #[test]
    fn specificity_only_winner_has_no_strict_axis_dominance() {
        let weaker = declaration(
            "weaker",
            CascadeLevel::AuthorNormal,
            0,
            0,
            Specificity::new(0, 1, 0),
            SpecificityExactnessV0::Inexact,
        );
        let stronger = declaration(
            "stronger",
            CascadeLevel::AuthorNormal,
            0,
            0,
            Specificity::new(1, 0, 0),
            SpecificityExactnessV0::Exact,
        );
        assert_eq!(
            classify_cascade_ranked_set_loss(&[weaker, stronger]),
            CascadeRankedSetLossClassV0::NoStrictAxisDominance
        );
    }

    #[test]
    fn single_inexact_candidate_is_not_vacuously_recoverable() {
        let candidate = declaration(
            "only",
            CascadeLevel::AuthorNormal,
            0,
            0,
            Specificity::ZERO,
            SpecificityExactnessV0::Inexact,
        );
        assert_eq!(
            classify_cascade_ranked_set_loss(&[candidate]),
            CascadeRankedSetLossClassV0::SingleInexactCandidate
        );
    }

    #[test]
    #[should_panic(expected = "requires an inexact declaration")]
    fn exact_only_input_is_outside_the_loss_classifier_domain() {
        let candidate = declaration(
            "exact",
            CascadeLevel::AuthorNormal,
            0,
            0,
            Specificity::ZERO,
            SpecificityExactnessV0::Exact,
        );
        let _ = classify_cascade_ranked_set_loss(&[candidate]);
    }

    #[test]
    fn capture_retains_the_row_that_product_ranking_recovers_to_definite() {
        let inexact_lower = declaration(
            "inexact-lower",
            CascadeLevel::UserNormal,
            0,
            0,
            Specificity::new(9, 9, 9),
            SpecificityExactnessV0::Inexact,
        );
        let exact_winner = declaration(
            "exact-winner",
            CascadeLevel::AuthorNormal,
            0,
            0,
            Specificity::ZERO,
            SpecificityExactnessV0::Exact,
        );
        let captured = capture_cascade_ranked_set_losses(|| {
            cascade_property([inexact_lower, exact_winner], "color")
        });
        assert!(captured.is_ok(), "capture should be exclusive");
        let Ok((outcome, capture)) = captured else {
            return;
        };

        assert!(matches!(outcome, CascadeOutcome::Definite { .. }));
        assert_eq!(capture.ranked_set_outcome_count, 0);
        assert_eq!(capture.recovered_definite_outcome_count, 1);
        assert_eq!(capture.multi_candidate_inexact_ranked_set_count, 0);
        assert_eq!(capture.rows.len(), 1);
        assert_eq!(
            capture.rows[0].classification,
            CascadeRankedSetLossClassV0::RecoverableAxisDominant {
                axis: CascadeAxisPrefixV0::Level
            }
        );
        assert_eq!(
            capture.rows[0].final_outcome,
            CascadeRankedSetFinalOutcomeV0::Definite
        );
        assert_eq!(
            capture.rows[0].definite_winner_declaration_id.as_deref(),
            Some("exact-winner")
        );
    }

    #[test]
    #[should_panic(expected = "a definite inexact outcome must be justified")]
    fn release_build_rejects_an_unjustified_definite_outcome() {
        let inexact = declaration(
            "inexact",
            CascadeLevel::AuthorNormal,
            0,
            0,
            Specificity::new(0, 1, 0),
            SpecificityExactnessV0::Inexact,
        );
        let exact = declaration(
            "exact",
            CascadeLevel::AuthorNormal,
            0,
            0,
            Specificity::new(1, 0, 0),
            SpecificityExactnessV0::Exact,
        );
        assert_definite_inexact_outcome_is_recoverable(&[exact, inexact]);
    }

    #[test]
    fn poisoned_capture_storage_is_cleared_and_reported() {
        let rows = std::sync::Arc::new(
            std::sync::Mutex::<Vec<CascadeRankedSetLossCensusRowV0>>::new(Vec::new()),
        );
        let poisoned_rows = std::sync::Arc::clone(&rows);
        let poison_result = std::thread::spawn(move || {
            let _guard = match poisoned_rows.lock() {
                Ok(guard) => guard,
                Err(error) => error.into_inner(),
            };
            std::panic::resume_unwind(Box::new("poison capture storage"));
        })
        .join();
        assert!(poison_result.is_err());

        let (recovered_rows, recovered) = recover_captured_rows(rows.lock(), &rows);
        assert!(recovered);
        assert!(recovered_rows.is_empty());
        assert!(!rows.is_poisoned());
    }
}