Skip to main content

rustev_eval/
selection.rs

1//! Declarative selection evidence (spec 029, 3.12), never an execution grant.
2use std::collections::{BTreeMap, BTreeSet};
3
4use rustev_contract::decimal::Decimal;
5use rustev_contract::ids::ContentDigest;
6use rustev_contract::limits::{DESCRIPTOR_V1, REPLAY_V1};
7use rustev_contract::{Document, Identified};
8use serde::{Deserialize, Serialize};
9
10use crate::baseline::{Baseline, valid_name};
11use crate::comparison::{
12    NamedCandidate, RepeatEvidence, check_names, compatible, observed, verify, verify_baseline,
13};
14use crate::config::Direction;
15use crate::repeat::{
16    BandDoc, CohortStatus, FigureDoc, HeldOut, MetricReport, Observation, RepeatReport, SplitRole,
17};
18
19pub const SELECTION_GATE: &str = "rustev.selection-gate/1";
20pub const SELECTION: &str = "rustev.selection/1";
21/// Conservative declaration bounds, matching DESCRIPTOR_V1 collection sizes.
22pub const MAX_GATE_ITEMS: usize = 1024;
23pub const MAX_METRIC_NAME: usize = 256;
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct SelectionGate {
28    pub schema: String,
29    pub gate: String,
30    pub per: Per,
31    pub metrics: BTreeMap<String, Direction>,
32    pub min_comparable_coverage: Decimal,
33    pub min_labeled_coverage: Decimal,
34    pub require: Vec<Clause>,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub and_any: Option<Vec<Clause>>,
37    pub rank_by: Vec<String>,
38}
39crate::doc::eval_document!(SelectionGate, SELECTION_GATE, DESCRIPTOR_V1, ContentDigest);
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Per {
44    Variant,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(untagged, deny_unknown_fields)]
49pub enum MetricClause {
50    NotWorse {
51        metric: String,
52        not_worse_than: BaselineTarget,
53        within: Within,
54    },
55    Better {
56        metric: String,
57        better_than: BaselineTarget,
58    },
59}
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum BaselineTarget {
63    Baseline,
64}
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case", deny_unknown_fields)]
67pub enum Within {
68    Noise,
69    Absolute(Decimal),
70}
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(untagged, deny_unknown_fields)]
73pub enum Clause {
74    Metric(MetricClause),
75    AllSlices { all_slices: MetricClause },
76    HeldOut { held_out: HeldOutLimit },
77}
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(deny_unknown_fields)]
80pub struct HeldOutLimit {
81    pub max_evaluations: u64,
82}
83
84impl MetricClause {
85    fn metric(&self) -> &str {
86        match self {
87            Self::NotWorse { metric, .. } | Self::Better { metric, .. } => metric,
88        }
89    }
90}
91impl SelectionGate {
92    /// Semantic checks accompany the strict document parser, as for RepeatConfig.
93    pub fn check(&self) -> Result<(), String> {
94        if self.schema != SELECTION_GATE || !valid_name(&self.gate) {
95            return Err("wrong schema or invalid gate name".into());
96        }
97        if [self.min_comparable_coverage, self.min_labeled_coverage]
98            .iter()
99            .any(|v| *v < Decimal::ZERO || *v > Decimal::from_i64(1))
100        {
101            return Err("coverage minima must be in [0, 1]".into());
102        }
103        if self.require.is_empty()
104            || self.require.len() > MAX_GATE_ITEMS
105            || self
106                .and_any
107                .as_ref()
108                .is_some_and(|a| a.is_empty() || a.len() > MAX_GATE_ITEMS)
109            || self.metrics.len() > MAX_GATE_ITEMS
110            || self.rank_by.len() > MAX_GATE_ITEMS
111        {
112            return Err("require and present and_any must contain 1 to 1024 clauses; metrics and rank_by at most 1024".into());
113        }
114        if self
115            .metrics
116            .keys()
117            .any(|m| m.is_empty() || m.len() > MAX_METRIC_NAME)
118        {
119            return Err("metric names must contain 1 to 256 bytes".into());
120        }
121        for c in self.require.iter().chain(self.and_any.iter().flatten()) {
122            let m = match c {
123                Clause::Metric(m) | Clause::AllSlices { all_slices: m } => m,
124                Clause::HeldOut { .. } => continue,
125            };
126            if !self.metrics.contains_key(m.metric()) {
127                return Err("clause metric has no declared direction".into());
128            }
129            if let MetricClause::NotWorse {
130                within: Within::Absolute(t),
131                ..
132            } = m
133                && t.is_negative()
134            {
135                return Err("absolute tolerance is negative".into());
136            }
137        }
138        let mut seen = BTreeSet::new();
139        for m in &self.rank_by {
140            if !self.metrics.contains_key(m) || !seen.insert(m) {
141                return Err("rank metrics must have a direction and be unique".into());
142            }
143        }
144        Ok(())
145    }
146}
147
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149#[serde(deny_unknown_fields)]
150pub struct Selection {
151    pub schema: String,
152    pub gate: ContentDigest,
153    pub baseline: ContentDigest,
154    pub candidates: Vec<CandidateSelection>,
155    pub ranked: Vec<String>,
156    pub unranked: Vec<Unranked>,
157}
158crate::doc::eval_document!(Selection, SELECTION, REPLAY_V1);
159
160#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
161#[serde(deny_unknown_fields)]
162pub struct CandidateSelection {
163    pub name: String,
164    pub repeat_report: ContentDigest,
165    pub verdict: Verdict,
166    pub clauses: Vec<ClauseResult>,
167}
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "snake_case", deny_unknown_fields)]
170pub enum Verdict {
171    Qualifies,
172    Rejected { clause: String },
173    Unknown { clause: String },
174}
175#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
176#[serde(deny_unknown_fields)]
177pub struct ClauseResult {
178    pub clause: String,
179    pub result: ClauseOutcome,
180    /// Each declared slice's result, retained even after a failure.
181    pub slices: Vec<SliceResult>,
182}
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
184#[serde(deny_unknown_fields)]
185pub struct SliceResult {
186    pub slice: String,
187    pub result: ClauseOutcome,
188}
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
190#[serde(rename_all = "snake_case", deny_unknown_fields)]
191pub enum ClauseOutcome {
192    Pass { reason: String },
193    Fail { reason: String },
194    Unknown { reason: String },
195}
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct Unranked {
199    pub name: String,
200    pub reason: String,
201}
202impl Selection {
203    /// The library equivalent of the command's 0, 11 and 12 status contract.
204    pub fn exit_code(&self) -> u8 {
205        if self
206            .candidates
207            .iter()
208            .any(|c| matches!(c.verdict, Verdict::Unknown { .. }))
209        {
210            12
211        } else if self
212            .candidates
213            .iter()
214            .any(|c| c.verdict == Verdict::Qualifies)
215        {
216            0
217        } else {
218            11
219        }
220    }
221}
222fn pass(s: impl Into<String>) -> ClauseOutcome {
223    ClauseOutcome::Pass { reason: s.into() }
224}
225fn fail(s: impl Into<String>) -> ClauseOutcome {
226    ClauseOutcome::Fail { reason: s.into() }
227}
228fn unknown(s: impl Into<String>) -> ClauseOutcome {
229    ClauseOutcome::Unknown { reason: s.into() }
230}
231fn outcome(ok: bool, s: &str) -> ClauseOutcome {
232    if ok { pass(s) } else { fail(s) }
233}
234fn result(clause: String, result: ClauseOutcome) -> ClauseResult {
235    ClauseResult {
236        clause,
237        result,
238        slices: vec![],
239    }
240}
241
242/// The metric a clause gates, if any.
243fn clause_metric(clause: &Clause) -> Option<&str> {
244    match clause {
245        Clause::Metric(m) | Clause::AllSlices { all_slices: m } => Some(m.metric()),
246        Clause::HeldOut { .. } => None,
247    }
248}
249
250/// Whether a run set's evaluator configuration produces `metric` from an
251/// opaque scorer, or an agreement with one (spec 041, 3.12).
252fn opaque(e: &RepeatEvidence<'_>, metric: &str) -> bool {
253    e.inputs.runs.iter().any(|r| {
254        r.evaluated
255            .config
256            .declarations()
257            .is_some_and(|d| d.metric_names().get(metric).is_some_and(|(_, o)| *o))
258    })
259}
260
261/// Verify all supplied bindings before comparing values. A failed precondition
262/// makes that candidate unknown. Once preconditions hold, any definite clause
263/// failure dominates unknown clauses, including unknown coverage denominators.
264pub fn evaluate_selection(
265    gate: &SelectionGate,
266    baseline: &Baseline,
267    baseline_evidence: &RepeatEvidence<'_>,
268    candidates: &[NamedCandidate<'_>],
269) -> Result<Selection, String> {
270    gate.check()?;
271    SelectionGate::parse(&gate.canonical().map_err(|e| e.to_string())?)
272        .map_err(|e| e.to_string())?;
273    check_names(candidates)?;
274    let base = verify_baseline(baseline, baseline_evidence);
275    let mut decisions = Vec::new();
276    let mut ranks = Vec::new();
277    let mut unranked = Vec::new();
278    for c in candidates {
279        let precondition = base
280            .clone()
281            .and_then(|()| compatible(baseline_evidence, &c.evidence))
282            .and_then(|()| verify(&c.evidence))
283            .and_then(|()| stable(baseline_evidence, &c.evidence));
284        let mut clauses = Vec::new();
285        let precondition_reason = precondition.err();
286        clauses.push(result(
287            "preconditions".into(),
288            match &precondition_reason {
289                Some(r) => unknown(r),
290                None => pass("bindings and cohorts verified"),
291            },
292        ));
293        if precondition_reason.is_none() {
294            for (side, e) in [("baseline", baseline_evidence), ("candidate", &c.evidence)] {
295                for (r, run) in e.inputs.runs.iter().enumerate() {
296                    for (metric, min) in [
297                        ("coverage", gate.min_comparable_coverage),
298                        ("labeled_proposal_coverage", gate.min_labeled_coverage),
299                    ] {
300                        let value = match run
301                            .evaluated
302                            .detail
303                            .count(metric)
304                            .filter(|v| v.denominator > 0)
305                        {
306                            None => unknown("coverage has no count or a zero denominator"),
307                            Some(v) => outcome(
308                                i128::from(v.numerator) * 1_000_000_000
309                                    >= min.units() * i128::from(v.denominator),
310                                "coverage minimum",
311                            ),
312                        };
313                        clauses.push(result(format!("{side}.runs[{r}].{metric}"), value));
314                    }
315                }
316            }
317        }
318        for (group, list) in [
319            ("require", gate.require.as_slice()),
320            ("and_any", gate.and_any.as_deref().unwrap_or(&[])),
321        ] {
322            for (i, clause) in list.iter().enumerate() {
323                let label = format!("{group}[{i}]");
324                let opaque_side = clause_metric(clause).and_then(|m| {
325                    [("baseline", baseline_evidence), ("candidate", &c.evidence)]
326                        .into_iter()
327                        .find(|(_, e)| opaque(e, m))
328                        .map(|(side, _)| (side, m))
329                });
330                clauses.push(match (&precondition_reason, opaque_side) {
331                    (Some(r), _) => result(label, unknown(format!("precondition: {r}"))),
332                    // Spec 041, 3.12.2: an opaque scorer's identity names
333                    // code whose change no digest shows.
334                    (None, Some((side, m))) => result(
335                        label,
336                        unknown(format!("the {side}'s `{m}` comes from an opaque scorer")),
337                    ),
338                    (None, None) => evaluate_clause(
339                        label,
340                        clause,
341                        gate,
342                        baseline_evidence.report,
343                        c.evidence.report,
344                    ),
345                });
346            }
347        }
348        if let Some(any) = &gate.and_any {
349            let members: Vec<_> = clauses
350                .iter()
351                .filter(|r| r.clause.starts_with("and_any["))
352                .map(|r| &r.result)
353                .collect();
354            debug_assert_eq!(members.len(), any.len());
355            let v = if members
356                .iter()
357                .any(|r| matches!(r, ClauseOutcome::Pass { .. }))
358            {
359                pass("at least one clause passes")
360            } else if members
361                .iter()
362                .all(|r| matches!(r, ClauseOutcome::Fail { .. }))
363            {
364                fail("every clause fails")
365            } else {
366                unknown("no clause passes and at least one is unknown")
367            };
368            clauses.push(result("and_any".into(), v));
369        }
370        // Individual OR members do not act as required clauses.
371        let relevant: Vec<_> = clauses
372            .iter()
373            .filter(|r| !r.clause.starts_with("and_any["))
374            .collect();
375        let verdict = if let Some(r) = relevant
376            .iter()
377            .find(|r| matches!(r.result, ClauseOutcome::Fail { .. }))
378        {
379            Verdict::Rejected {
380                clause: r.clause.clone(),
381            }
382        } else if let Some(r) = relevant
383            .iter()
384            .find(|r| matches!(r.result, ClauseOutcome::Unknown { .. }))
385        {
386            let clause = if r.clause == "and_any" {
387                clauses
388                    .iter()
389                    .find(|r| {
390                        r.clause.starts_with("and_any[")
391                            && matches!(r.result, ClauseOutcome::Unknown { .. })
392                    })
393                    .expect("an unknown disjunction has an unknown member")
394                    .clause
395                    .clone()
396            } else {
397                r.clause.clone()
398            };
399            Verdict::Unknown { clause }
400        } else {
401            Verdict::Qualifies
402        };
403        if verdict == Verdict::Qualifies {
404            let values: Result<Vec<_>, String> = gate
405                .rank_by
406                .iter()
407                .map(|m| {
408                    if opaque(&c.evidence, m) || opaque(baseline_evidence, m) {
409                        return Err(format!("`{m}` comes from an opaque scorer"));
410                    }
411                    metric(c.evidence.report, "all", m).and_then(|m| value(m, true))
412                })
413                .collect();
414            match values {
415                Ok(values) => ranks.push((c.name.to_string(), values)),
416                Err(reason) => unranked.push(Unranked {
417                    name: c.name.into(),
418                    reason,
419                }),
420            }
421        }
422        decisions.push(CandidateSelection {
423            name: c.name.into(),
424            repeat_report: c
425                .evidence
426                .report
427                .record_digest()
428                .map_err(|e| e.to_string())?,
429            verdict,
430            clauses,
431        });
432    }
433    ranks.sort_by(|(an, av), (bn, bv)| {
434        for ((a, b), m) in av.iter().zip(bv).zip(&gate.rank_by) {
435            // Numeric equality includes both signs of zero. All values finite.
436            let order = a.partial_cmp(b).expect("finite rank values");
437            let order = match gate.metrics[m] {
438                Direction::HigherIsBetter => order.reverse(),
439                Direction::LowerIsBetter => order,
440            };
441            if !order.is_eq() {
442                return order;
443            }
444        }
445        an.as_bytes().cmp(bn.as_bytes())
446    });
447    let doc = Selection {
448        schema: SELECTION.into(),
449        gate: gate.id().map_err(|e| e.to_string())?,
450        baseline: baseline.record_digest().map_err(|e| e.to_string())?,
451        candidates: decisions,
452        ranked: ranks.into_iter().map(|(n, _)| n).collect(),
453        unranked,
454    };
455    Selection::parse(&doc.record_canonical().map_err(|e| e.to_string())?).map_err(|e| e.to_string())
456}
457
458fn stable(b: &RepeatEvidence<'_>, c: &RepeatEvidence<'_>) -> Result<(), String> {
459    if b.report.stable_cohort != c.report.stable_cohort {
460        return Err("stable cohorts differ".into());
461    }
462    let live = c.report.source == crate::repeat::Source::Live;
463    for (b, c) in b.inputs.runs.iter().zip(c.inputs.runs) {
464        let comparable = |e: &crate::report::Evaluated| -> BTreeSet<String> {
465            e.detail
466                .cases
467                .iter()
468                .filter(|c| {
469                    c.outcome.starts_with("proposal:") || c.outcome.starts_with("abstention:")
470                })
471                .map(|c| c.case.clone())
472                .collect()
473        };
474        if comparable(b.evaluated) != comparable(c.evaluated) {
475            return Err("per-run comparable cohorts differ".into());
476        }
477        if b.evaluated
478            .detail
479            .count("candidate_outcome_change")
480            .is_some()
481            || (!live
482                && c.evaluated
483                    .detail
484                    .count("candidate_outcome_change")
485                    .is_none())
486        {
487            return Err("run baseline and candidate roles do not hold".into());
488        }
489    }
490    Ok(())
491}
492
493fn metric<'a>(r: &'a RepeatReport, cohort: &str, name: &str) -> Result<&'a MetricReport, String> {
494    let c = r
495        .cohorts
496        .iter()
497        .find(|c| c.name == cohort)
498        .ok_or_else(|| format!("missing cohort {cohort}"))?;
499    if c.status == CohortStatus::BelowMinimum {
500        return Err(format!("{cohort}: below_minimum"));
501    }
502    c.metrics
503        .iter()
504        .find(|m| m.name == name)
505        .ok_or_else(|| format!("metric {name} not reported in {cohort}"))
506}
507fn value(m: &MetricReport, candidate: bool) -> Result<f64, String> {
508    if candidate && observed(&m.name) && m.observation != Some(Observation::Candidate) {
509        return Err(format!(
510            "{}: historical or missing candidate observation",
511            m.name
512        ));
513    }
514    match &m.pooled {
515        FigureDoc::Value(v) if v.is_finite() => Ok(*v),
516        FigureDoc::Unknown(r) => Err(format!("{}: {r}", m.name)),
517        _ => Err("non-finite value".into()),
518    }
519}
520fn band(m: &MetricReport) -> Result<f64, String> {
521    match &m.band {
522        BandDoc::Value { value, .. } if value.is_finite() && *value >= 0.0 => Ok(*value),
523        BandDoc::Unknown(r) => Err(format!("{} band: {r}", m.name)),
524        _ => Err("invalid band".into()),
525    }
526}
527/// An exact decimal `(-1)^negative * digits * 10^exponent`, its digits most
528/// significant first.
529struct Exact {
530    negative: bool,
531    digits: Vec<u8>,
532    exponent: i32,
533}
534/// The shortest decimal that round-trips to `v` (what `{}` prints), exactly.
535/// `value` already refuses a non-finite pooled value, so the clause is
536/// unknown (spec 029, 3.12.4: "A clause is unknown when a value ... it needs
537/// is unknown"); NaN and the infinities are refused here too, never read as
538/// a number.
539fn shortest(v: f64) -> Result<Exact, String> {
540    if !v.is_finite() {
541        return Err("non-finite value".into());
542    }
543    let s = format!("{v:e}");
544    let (mantissa, exponent) = s
545        .split_once('e')
546        .ok_or_else(|| format!("no decimal exponent in {s}"))?;
547    let exponent: i32 = exponent
548        .parse()
549        .map_err(|_| format!("invalid decimal exponent in {s}"))?;
550    let (negative, mantissa) = match mantissa.strip_prefix('-') {
551        Some(m) => (true, m),
552        None => (false, mantissa),
553    };
554    let fraction = mantissa.split_once('.').map_or(0, |(_, f)| f.len());
555    let fraction = i32::try_from(fraction).map_err(|_| format!("mantissa too long in {s}"))?;
556    Ok(Exact {
557        negative,
558        digits: mantissa
559            .bytes()
560            .filter(u8::is_ascii_digit)
561            .map(|d| d - b'0')
562            .collect(),
563        exponent: exponent - fraction,
564    })
565}
566fn exact(t: Decimal) -> Exact {
567    Exact {
568        negative: t.is_negative(),
569        digits: t
570            .units()
571            .unsigned_abs()
572            .to_string()
573            .bytes()
574            .map(|d| d - b'0')
575            .collect(),
576        exponent: -i32::try_from(rustev_contract::decimal::SCALE).expect("small scale"),
577    }
578}
579/// Compares `sum(lhs)` with `sum(rhs)` exactly. Binary64 exponents bound the
580/// aligned magnitudes to under 700 digits.
581fn exact_sum_cmp(lhs: &[Exact], rhs: &[Exact]) -> std::cmp::Ordering {
582    let terms = lhs
583        .iter()
584        .map(|t| (t, false))
585        .chain(rhs.iter().map(|t| (t, true)));
586    let low = lhs.iter().chain(rhs).map(|t| t.exponent).min().unwrap_or(0);
587    // Positive and negative contributions, least significant digit first.
588    let (mut pos, mut neg) = (Vec::new(), Vec::new());
589    for (t, subtract) in terms {
590        let shift = usize::try_from(t.exponent - low).expect("aligned to the lowest exponent");
591        let mut m = vec![0u8; shift];
592        m.extend(t.digits.iter().rev());
593        add_digits(
594            if t.negative != subtract {
595                &mut neg
596            } else {
597                &mut pos
598            },
599            &m,
600        );
601    }
602    let trim = |v: &mut Vec<u8>| {
603        while v.last() == Some(&0) {
604            v.pop();
605        }
606    };
607    trim(&mut pos);
608    trim(&mut neg);
609    pos.len()
610        .cmp(&neg.len())
611        .then_with(|| pos.iter().rev().cmp(neg.iter().rev()))
612}
613fn add_digits(acc: &mut Vec<u8>, m: &[u8]) {
614    if acc.len() < m.len() {
615        acc.resize(m.len(), 0);
616    }
617    let mut carry = 0;
618    for (i, a) in acc.iter_mut().enumerate() {
619        let sum = *a + m.get(i).copied().unwrap_or(0) + carry;
620        *a = sum % 10;
621        carry = sum / 10;
622        if carry == 0 && i >= m.len() {
623            break;
624        }
625    }
626    if carry > 0 {
627        acc.push(carry);
628    }
629}
630fn metric_clause(
631    clause: &MetricClause,
632    gate: &SelectionGate,
633    b: &RepeatReport,
634    c: &RepeatReport,
635    cohort: &str,
636) -> ClauseOutcome {
637    let compare = || -> Result<bool, String> {
638        let bm = metric(b, cohort, clause.metric())?;
639        let cm = metric(c, cohort, clause.metric())?;
640        let bv = value(bm, false)?;
641        let cv = value(cm, true)?;
642        let higher = gate.metrics[clause.metric()] == Direction::HigherIsBetter;
643        let better = matches!(clause, MetricClause::Better { .. });
644        // Spec 029, 3.12.3: every band, a noise band or an absolute
645        // tolerance, is compared in exact decimal against the shortest
646        // round-trip decimals of `b` and `c` (and of a binary64 band), so a
647        // candidate exactly on the boundary is decided by the rule as
648        // written, never by binary64 rounding (#474).
649        let tolerance = match clause {
650            MetricClause::NotWorse {
651                within: Within::Absolute(t),
652                ..
653            } => exact(*t),
654            _ => shortest(band(bm)?.max(band(cm)?))?,
655        };
656        let (b, c) = (shortest(bv)?, shortest(cv)?);
657        Ok(match (higher, better) {
658            // c > b + band.
659            (true, true) => exact_sum_cmp(&[c], &[b, tolerance]).is_gt(),
660            // c < b - band, that is b > c + band.
661            (false, true) => exact_sum_cmp(&[b], &[c, tolerance]).is_gt(),
662            // c >= b - band, that is c + band >= b.
663            (true, false) => exact_sum_cmp(&[c, tolerance], &[b]).is_ge(),
664            // c <= b + band, that is b + band >= c.
665            (false, false) => exact_sum_cmp(&[b, tolerance], &[c]).is_ge(),
666        })
667    };
668    match compare() {
669        Ok(ok) => outcome(ok, &format!("{} in {cohort}", clause.metric())),
670        Err(r) => unknown(r),
671    }
672}
673fn evaluate_clause(
674    label: String,
675    clause: &Clause,
676    gate: &SelectionGate,
677    b: &RepeatReport,
678    c: &RepeatReport,
679) -> ClauseResult {
680    match clause {
681        Clause::Metric(m) => result(label, metric_clause(m, gate, b, c, "all")),
682        Clause::HeldOut { held_out } => result(
683            label,
684            if c.split_role != SplitRole::HeldOut {
685                pass("nothing is held out")
686            } else {
687                match &c.held_out {
688                    Some(HeldOut::Counted(r))
689                        if r.count > 0
690                            && r.plan_count > 0
691                            && r.count <= r.dataset_count
692                            && r.plan_count <= r.dataset_count
693                            && r.dataset_count <= 10_000 =>
694                    {
695                        outcome(
696                            r.count <= held_out.max_evaluations,
697                            "held-out lineage count",
698                        )
699                    }
700                    Some(HeldOut::Unknown { reason }) => unknown(reason),
701                    _ => unknown("held-out count missing or invalid"),
702                }
703            },
704        ),
705        Clause::AllSlices { all_slices } => {
706            let slices: Vec<_> = b
707                .cohorts
708                .iter()
709                .filter(|c| c.name != "all")
710                .map(|s| SliceResult {
711                    slice: s.name.clone(),
712                    result: metric_clause(all_slices, gate, b, c, &s.name),
713                })
714                .collect();
715            let combined = slices
716                .iter()
717                .find(|s| matches!(s.result, ClauseOutcome::Fail { .. }))
718                .or_else(|| {
719                    slices
720                        .iter()
721                        .find(|s| matches!(s.result, ClauseOutcome::Unknown { .. }))
722                })
723                .map(|s| s.result.clone())
724                .unwrap_or_else(|| {
725                    if slices.is_empty() {
726                        unknown("no declared slices")
727                    } else {
728                        pass("every declared slice passes")
729                    }
730                });
731            ClauseResult {
732                clause: label,
733                result: combined,
734                slices,
735            }
736        }
737    }
738}
739
740#[cfg(test)]
741mod tests {
742    use super::*;
743    use std::cmp::Ordering::{Equal, Greater, Less};
744
745    fn cmp(l: &[f64], t: &str, r: &[f64]) -> std::cmp::Ordering {
746        let mut lhs: Vec<_> = l.iter().map(|v| shortest(*v).unwrap()).collect();
747        lhs.push(exact(Decimal::parse(t).unwrap()));
748        let rhs: Vec<_> = r.iter().map(|v| shortest(*v).unwrap()).collect();
749        exact_sum_cmp(&lhs, &rhs)
750    }
751
752    #[test]
753    fn non_finite_values_are_refused_not_read() {
754        for v in [f64::NAN, -f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
755            assert_eq!(shortest(v).err().as_deref(), Some("non-finite value"));
756        }
757    }
758
759    #[test]
760    fn exact_sums_over_signs_and_the_binary64_range() {
761        assert_eq!(cmp(&[0.2], "0.1", &[0.3]), Equal);
762        assert_eq!(cmp(&[0.7], "0.2", &[0.9]), Equal);
763        assert_eq!(cmp(&[-0.3], "0.1", &[-0.2]), Equal);
764        assert_eq!(cmp(&[-0.0], "0", &[0.0]), Equal);
765        assert_eq!(cmp(&[f64::MAX], "1", &[f64::MAX]), Greater);
766        assert_eq!(cmp(&[5e-324], "0", &[1e-323]), Less);
767        assert_eq!(cmp(&[-f64::MAX], "0.000000001", &[f64::MIN_POSITIVE]), Less);
768        assert_eq!(cmp(&[9.999_999_999], "0.000000001", &[10.0]), Equal);
769    }
770}