1use 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, CohortReport, CohortStatus, FigureDoc, HeldOut, MetricReport, Observation, SplitRole,
17};
18
19mod case_regressions;
20pub use case_regressions::{CaseList, CaseResults, Regression, UnresolvedCase, stdout_candidates};
21
22pub const SELECTION_GATE: &str = "rustev.selection-gate/1";
23pub const SELECTION: &str = "rustev.selection/1";
24pub const MAX_GATE_ITEMS: usize = 1024;
26pub const MAX_METRIC_NAME: usize = 256;
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct SelectionGate {
31 pub schema: String,
32 pub gate: String,
33 pub per: Per,
34 pub metrics: BTreeMap<String, Direction>,
35 pub min_comparable_coverage: Decimal,
36 pub min_labeled_coverage: Decimal,
37 pub require: Vec<Clause>,
38 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub and_any: Option<Vec<Clause>>,
40 pub rank_by: Vec<String>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 #[serde(deserialize_with = "crate::integrity::present")]
43 pub integrity: Option<crate::integrity::Integrity>,
44}
45crate::doc::eval_document!(SelectionGate, SELECTION_GATE, DESCRIPTOR_V1, ContentDigest);
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum Per {
50 Variant,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(untagged, deny_unknown_fields)]
55pub enum MetricClause {
56 CaseRegressions {
57 metric: String,
58 case_regressions: CaseRegressionLimit,
59 },
60 NotWorse {
61 metric: String,
62 not_worse_than: BaselineTarget,
63 within: Within,
64 },
65 Better {
66 metric: String,
67 better_than: BaselineTarget,
68 },
69}
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum BaselineTarget {
73 Baseline,
74}
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct CaseRegressionLimit {
78 pub by: AbsoluteDrop,
79 pub at_most: u64,
80}
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct AbsoluteDrop {
84 pub absolute: Decimal,
85}
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "snake_case", deny_unknown_fields)]
88pub enum Within {
89 Noise,
90 Absolute(Decimal),
91}
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(untagged, deny_unknown_fields)]
94pub enum Clause {
95 Metric(MetricClause),
96 AllSlices { all_slices: MetricClause },
97 HeldOut { held_out: HeldOutLimit },
98}
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(deny_unknown_fields)]
101pub struct HeldOutLimit {
102 pub max_evaluations: u64,
103}
104
105impl MetricClause {
106 fn metric(&self) -> &str {
107 match self {
108 Self::NotWorse { metric, .. }
109 | Self::Better { metric, .. }
110 | Self::CaseRegressions { metric, .. } => metric,
111 }
112 }
113}
114impl SelectionGate {
115 pub fn check(&self) -> Result<(), String> {
117 if let Some(integrity) = &self.integrity {
118 integrity.check()?;
119 }
120 if self.schema != SELECTION_GATE || !valid_name(&self.gate) {
121 return Err("wrong schema or invalid gate name".into());
122 }
123 if [self.min_comparable_coverage, self.min_labeled_coverage]
124 .iter()
125 .any(|v| *v < Decimal::ZERO || *v > Decimal::from_i64(1))
126 {
127 return Err("coverage minima must be in [0, 1]".into());
128 }
129 if self.require.is_empty()
130 || self.require.len() > MAX_GATE_ITEMS
131 || self
132 .and_any
133 .as_ref()
134 .is_some_and(|a| a.is_empty() || a.len() > MAX_GATE_ITEMS)
135 || self.metrics.len() > MAX_GATE_ITEMS
136 || self.rank_by.len() > MAX_GATE_ITEMS
137 {
138 return Err("require and present and_any must contain 1 to 1024 clauses; metrics and rank_by at most 1024".into());
139 }
140 if self
141 .metrics
142 .keys()
143 .any(|m| m.is_empty() || m.len() > MAX_METRIC_NAME)
144 {
145 return Err("metric names must contain 1 to 256 bytes".into());
146 }
147 for c in self.require.iter().chain(self.and_any.iter().flatten()) {
148 let m = match c {
149 Clause::Metric(m) | Clause::AllSlices { all_slices: m } => m,
150 Clause::HeldOut { .. } => continue,
151 };
152 if !self.metrics.contains_key(m.metric()) {
153 return Err("clause metric has no declared direction".into());
154 }
155 if let MetricClause::CaseRegressions {
156 case_regressions: limit,
157 ..
158 } = m
159 {
160 if matches!(c, Clause::AllSlices { .. }) {
161 return Err("case-regressions-in-slices".into());
162 }
163 if limit.by.absolute <= Decimal::ZERO || limit.at_most > 1_000_000 {
164 return Err(
165 "case_regressions needs positive by.absolute and at_most in [0, 1000000]"
166 .into(),
167 );
168 }
169 }
170 if let MetricClause::NotWorse {
171 within: Within::Absolute(t),
172 ..
173 } = m
174 && t.is_negative()
175 {
176 return Err("absolute tolerance is negative".into());
177 }
178 }
179 let mut seen = BTreeSet::new();
180 for m in &self.rank_by {
181 if !self.metrics.contains_key(m) || !seen.insert(m) {
182 return Err("rank metrics must have a direction and be unique".into());
183 }
184 }
185 Ok(())
186 }
187}
188
189#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
190#[serde(deny_unknown_fields)]
191pub struct Selection {
192 pub schema: String,
193 pub gate: ContentDigest,
194 pub baseline: ContentDigest,
195 pub candidates: Vec<CandidateSelection>,
196 pub ranked: Vec<String>,
197 pub unranked: Vec<Unranked>,
198}
199crate::doc::eval_document!(Selection, SELECTION, REPLAY_V1);
200
201#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
202#[serde(deny_unknown_fields)]
203pub struct CandidateSelection {
204 pub name: String,
205 pub repeat_report: ContentDigest,
206 pub verdict: Verdict,
207 pub clauses: Vec<ClauseResult>,
208}
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(rename_all = "snake_case", deny_unknown_fields)]
211pub enum Verdict {
212 Qualifies,
213 Rejected { clause: String },
214 Unknown { clause: String },
215}
216#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub struct ClauseResult {
219 pub clause: String,
220 pub result: ClauseOutcome,
221 pub slices: Vec<SliceResult>,
223 #[serde(
224 default,
225 skip_serializing_if = "Option::is_none",
226 deserialize_with = "case_regressions::read_cases"
227 )]
228 pub cases: Option<Option<CaseResults>>,
229}
230#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct SliceResult {
233 pub slice: String,
234 pub result: ClauseOutcome,
235}
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(rename_all = "snake_case", deny_unknown_fields)]
238pub enum ClauseOutcome {
239 Pass { reason: String },
240 Fail { reason: String },
241 Unknown { reason: String },
242}
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244#[serde(deny_unknown_fields)]
245pub struct Unranked {
246 pub name: String,
247 pub reason: String,
248}
249impl Selection {
250 pub fn exit_code(&self) -> u8 {
252 if self
253 .candidates
254 .iter()
255 .any(|c| matches!(c.verdict, Verdict::Unknown { .. }))
256 {
257 12
258 } else if self
259 .candidates
260 .iter()
261 .any(|c| c.verdict == Verdict::Qualifies)
262 {
263 0
264 } else {
265 11
266 }
267 }
268}
269fn pass(s: impl Into<String>) -> ClauseOutcome {
270 ClauseOutcome::Pass { reason: s.into() }
271}
272fn fail(s: impl Into<String>) -> ClauseOutcome {
273 ClauseOutcome::Fail { reason: s.into() }
274}
275fn unknown(s: impl Into<String>) -> ClauseOutcome {
276 ClauseOutcome::Unknown { reason: s.into() }
277}
278fn outcome(ok: bool, s: &str) -> ClauseOutcome {
279 if ok { pass(s) } else { fail(s) }
280}
281fn result(clause: String, result: ClauseOutcome) -> ClauseResult {
282 ClauseResult {
283 clause,
284 result,
285 slices: vec![],
286 cases: None,
287 }
288}
289
290fn clause_metric(clause: &Clause) -> Option<&str> {
292 match clause {
293 Clause::Metric(m) | Clause::AllSlices { all_slices: m } => Some(m.metric()),
294 Clause::HeldOut { .. } => None,
295 }
296}
297
298fn opaque(e: &RepeatEvidence<'_>, metric: &str) -> bool {
301 e.inputs.runs.iter().any(|r| {
302 r.evaluated
303 .config
304 .declarations()
305 .is_some_and(|d| d.metric_names().get(metric).is_some_and(|(_, o)| *o))
306 })
307}
308
309pub fn evaluate_selection(
313 gate: &SelectionGate,
314 baseline: &Baseline,
315 baseline_evidence: &RepeatEvidence<'_>,
316 candidates: &[NamedCandidate<'_>],
317) -> Result<Selection, String> {
318 gate.check()?;
319 SelectionGate::parse(&gate.canonical().map_err(|e| e.to_string())?)
320 .map_err(|e| e.to_string())?;
321 check_names(candidates)?;
322 let base = verify_baseline(baseline, baseline_evidence);
323 let baseline_integrity = gate
324 .integrity
325 .as_ref()
326 .filter(|_| base.is_ok())
327 .map(|bounds| {
328 baseline_evidence
329 .inputs
330 .runs
331 .iter()
332 .enumerate()
333 .map(|(r, run)| {
334 crate::integrity::entry(
335 "baseline",
336 r,
337 bounds,
338 crate::integrity::evaluated_counts(run.evaluated),
339 )
340 })
341 .collect::<Vec<_>>()
342 });
343 let mut decisions = Vec::new();
344 let mut ranks = Vec::new();
345 let mut unranked = Vec::new();
346 for c in candidates {
347 let precondition = base
348 .clone()
349 .and_then(|()| compatible(baseline_evidence, &c.evidence))
350 .and_then(|()| verify(&c.evidence))
351 .and_then(|()| stable(baseline_evidence, &c.evidence));
352 let mut clauses = Vec::new();
353 let mut precondition_reason = precondition.err();
354 clauses.push(result(
355 "preconditions".into(),
356 match &precondition_reason {
357 Some(r) => unknown(r),
358 None => pass("bindings and cohorts verified"),
359 },
360 ));
361 if precondition_reason.is_none()
362 && let Some(bounds) = &gate.integrity
363 {
364 clauses.extend(baseline_integrity.clone().unwrap_or_default());
365 clauses.extend(c.evidence.inputs.runs.iter().enumerate().map(|(r, run)| {
366 crate::integrity::entry(
367 "candidate",
368 r,
369 bounds,
370 crate::integrity::evaluated_counts(run.evaluated),
371 )
372 }));
373 if crate::integrity::breached(&clauses) {
374 precondition_reason = Some("integrity".into());
375 }
376 }
377 if precondition_reason.is_none() {
378 for (side, e) in [("baseline", baseline_evidence), ("candidate", &c.evidence)] {
379 for (r, run) in e.inputs.runs.iter().enumerate() {
380 for (metric, min) in [
381 ("coverage", gate.min_comparable_coverage),
382 ("labeled_proposal_coverage", gate.min_labeled_coverage),
383 ] {
384 let value = match run
385 .evaluated
386 .detail
387 .count(metric)
388 .filter(|v| v.denominator > 0)
389 {
390 None => unknown("coverage has no count or a zero denominator"),
391 Some(v) => outcome(
392 i128::from(v.numerator) * 1_000_000_000
393 >= min.units() * i128::from(v.denominator),
394 "coverage minimum",
395 ),
396 };
397 clauses.push(result(format!("{side}.runs[{r}].{metric}"), value));
398 }
399 }
400 }
401 }
402 let base_side = Side {
403 cohorts: &baseline_evidence.report.cohorts,
404 split_role: baseline_evidence.report.split_role,
405 held_out: baseline_evidence.report.held_out.as_ref(),
406 opaque: &|m: &str| opaque(baseline_evidence, m),
407 host: false,
408 cases: baseline_evidence
409 .inputs
410 .runs
411 .iter()
412 .map(|r| r.cases)
413 .collect(),
414 };
415 let cand_side = Side {
416 cohorts: &c.evidence.report.cohorts,
417 split_role: c.evidence.report.split_role,
418 held_out: c.evidence.report.held_out.as_ref(),
419 opaque: &|m: &str| opaque(&c.evidence, m),
420 host: false,
421 cases: c.evidence.inputs.runs.iter().map(|r| r.cases).collect(),
422 };
423 let (verdict, clauses) = judge(
424 gate,
425 &base_side,
426 &cand_side,
427 precondition_reason.as_deref(),
428 clauses,
429 c.name,
430 &mut ranks,
431 &mut unranked,
432 );
433 decisions.push(CandidateSelection {
434 name: c.name.into(),
435 repeat_report: c
436 .evidence
437 .report
438 .record_digest()
439 .map_err(|e| e.to_string())?,
440 verdict,
441 clauses,
442 });
443 }
444 sort_ranks(gate, &mut ranks);
445 let doc = Selection {
446 schema: SELECTION.into(),
447 gate: gate.id().map_err(|e| e.to_string())?,
448 baseline: baseline.record_digest().map_err(|e| e.to_string())?,
449 candidates: decisions,
450 ranked: ranks.into_iter().map(|(n, _)| n).collect(),
451 unranked,
452 };
453 Selection::parse(&doc.record_canonical().map_err(|e| e.to_string())?).map_err(|e| e.to_string())
454}
455
456pub(crate) struct Side<'a> {
460 pub cohorts: &'a [CohortReport],
461 pub split_role: SplitRole,
462 pub held_out: Option<&'a HeldOut>,
463 pub opaque: &'a dyn Fn(&str) -> bool,
464 pub host: bool,
465 pub cases: Vec<&'a crate::eval_cases::EvalCases>,
466}
467
468#[allow(clippy::too_many_arguments)]
472pub(crate) fn judge(
473 gate: &SelectionGate,
474 base: &Side<'_>,
475 cand: &Side<'_>,
476 precondition_reason: Option<&str>,
477 mut clauses: Vec<ClauseResult>,
478 name: &str,
479 ranks: &mut Vec<(String, Vec<f64>)>,
480 unranked: &mut Vec<Unranked>,
481) -> (Verdict, Vec<ClauseResult>) {
482 for (group, list) in [
483 ("require", gate.require.as_slice()),
484 ("and_any", gate.and_any.as_deref().unwrap_or(&[])),
485 ] {
486 for (i, clause) in list.iter().enumerate() {
487 let label = format!("{group}[{i}]");
488 let opaque_side = clause_metric(clause).and_then(|m| {
489 [("baseline", base), ("candidate", cand)]
490 .into_iter()
491 .find(|(_, e)| (e.opaque)(m))
492 .map(|(side, _)| (side, m))
493 });
494 let mut entry = match (&precondition_reason, opaque_side) {
495 (Some(r), _) => result(label, unknown(format!("precondition: {r}"))),
496 (None, Some((side, m))) => result(
499 label,
500 unknown(format!("the {side}'s `{m}` comes from an opaque scorer")),
501 ),
502 (None, None) => evaluate_clause(label, clause, gate, base, cand),
503 };
504 if matches!(clause, Clause::Metric(MetricClause::CaseRegressions { .. }))
505 && entry.cases.is_none()
506 {
507 entry.cases = Some(None);
508 }
509 clauses.push(entry);
510 }
511 }
512 if let Some(any) = &gate.and_any {
513 let members: Vec<_> = clauses
514 .iter()
515 .filter(|r| r.clause.starts_with("and_any["))
516 .map(|r| &r.result)
517 .collect();
518 debug_assert_eq!(members.len(), any.len());
519 let v = if members
520 .iter()
521 .any(|r| matches!(r, ClauseOutcome::Pass { .. }))
522 {
523 pass("at least one clause passes")
524 } else if members
525 .iter()
526 .all(|r| matches!(r, ClauseOutcome::Fail { .. }))
527 {
528 fail("every clause fails")
529 } else {
530 unknown("no clause passes and at least one is unknown")
531 };
532 clauses.push(result("and_any".into(), v));
533 }
534 let relevant: Vec<_> = clauses
536 .iter()
537 .filter(|r| !r.clause.starts_with("and_any["))
538 .collect();
539 let verdict = if let Some(r) = relevant
540 .iter()
541 .find(|r| matches!(r.result, ClauseOutcome::Fail { .. }))
542 {
543 Verdict::Rejected {
544 clause: r.clause.clone(),
545 }
546 } else if let Some(r) = relevant
547 .iter()
548 .find(|r| matches!(r.result, ClauseOutcome::Unknown { .. }))
549 {
550 let clause = if r.clause == "and_any" {
551 clauses
552 .iter()
553 .find(|r| {
554 r.clause.starts_with("and_any[")
555 && matches!(r.result, ClauseOutcome::Unknown { .. })
556 })
557 .expect("an unknown disjunction has an unknown member")
558 .clause
559 .clone()
560 } else {
561 r.clause.clone()
562 };
563 Verdict::Unknown { clause }
564 } else {
565 Verdict::Qualifies
566 };
567 if verdict == Verdict::Qualifies {
568 let values: Result<Vec<_>, String> = gate
569 .rank_by
570 .iter()
571 .map(|m| {
572 if (cand.opaque)(m) || (base.opaque)(m) {
573 return Err(format!("`{m}` comes from an opaque scorer"));
574 }
575 metric(cand, "all", m).and_then(|m| value(m, true, cand.host))
576 })
577 .collect();
578 match values {
579 Ok(values) => ranks.push((name.to_string(), values)),
580 Err(reason) => unranked.push(Unranked {
581 name: name.into(),
582 reason,
583 }),
584 }
585 }
586 (verdict, clauses)
587}
588
589pub(crate) fn sort_ranks(gate: &SelectionGate, ranks: &mut [(String, Vec<f64>)]) {
592 ranks.sort_by(|(an, av), (bn, bv)| {
593 for ((a, b), m) in av.iter().zip(bv).zip(&gate.rank_by) {
594 let order = a.partial_cmp(b).expect("finite rank values");
596 let order = match gate.metrics[m] {
597 Direction::HigherIsBetter => order.reverse(),
598 Direction::LowerIsBetter => order,
599 };
600 if !order.is_eq() {
601 return order;
602 }
603 }
604 an.as_bytes().cmp(bn.as_bytes())
605 });
606}
607
608fn stable(b: &RepeatEvidence<'_>, c: &RepeatEvidence<'_>) -> Result<(), String> {
609 if b.report.stable_cohort != c.report.stable_cohort {
610 return Err("stable cohorts differ".into());
611 }
612 let live = c.report.source == crate::repeat::Source::Live;
613 for (b, c) in b.inputs.runs.iter().zip(c.inputs.runs) {
614 let comparable = |e: &crate::report::Evaluated| -> BTreeSet<String> {
615 e.detail
616 .cases
617 .iter()
618 .filter(|c| {
619 c.outcome.starts_with("proposal:") || c.outcome.starts_with("abstention:")
620 })
621 .map(|c| c.case.clone())
622 .collect()
623 };
624 if comparable(b.evaluated) != comparable(c.evaluated) {
625 return Err("per-run comparable cohorts differ".into());
626 }
627 if b.evaluated
628 .detail
629 .count("candidate_outcome_change")
630 .is_some()
631 || (!live
632 && c.evaluated
633 .detail
634 .count("candidate_outcome_change")
635 .is_none())
636 {
637 return Err("run baseline and candidate roles do not hold".into());
638 }
639 }
640 Ok(())
641}
642
643fn metric<'a>(r: &Side<'a>, cohort: &str, name: &str) -> Result<&'a MetricReport, String> {
644 let c = r
645 .cohorts
646 .iter()
647 .find(|c| c.name == cohort)
648 .ok_or_else(|| format!("missing cohort {cohort}"))?;
649 if c.status == CohortStatus::BelowMinimum {
650 return Err(format!("{cohort}: below_minimum"));
651 }
652 c.metrics
653 .iter()
654 .find(|m| m.name == name)
655 .ok_or_else(|| format!("metric {name} not reported in {cohort}"))
656}
657fn value(m: &MetricReport, candidate: bool, host: bool) -> Result<f64, String> {
658 let observation = if host {
661 crate::host_repeat::observed(&m.name)
662 } else {
663 observed(&m.name)
664 };
665 if candidate && observation && m.observation != Some(Observation::Candidate) {
666 return Err(format!(
667 "{}: historical or missing candidate observation",
668 m.name
669 ));
670 }
671 match &m.pooled {
672 FigureDoc::Value(v) if v.is_finite() => Ok(*v),
673 FigureDoc::Unknown(r) => Err(format!("{}: {r}", m.name)),
674 _ => Err("non-finite value".into()),
675 }
676}
677fn band(m: &MetricReport) -> Result<f64, String> {
678 match &m.band {
679 BandDoc::Value { value, .. } if value.is_finite() && *value >= 0.0 => Ok(*value),
680 BandDoc::Unknown(r) => Err(format!("{} band: {r}", m.name)),
681 _ => Err("invalid band".into()),
682 }
683}
684struct Exact {
687 negative: bool,
688 digits: Vec<u8>,
689 exponent: i32,
690}
691fn shortest(v: f64) -> Result<Exact, String> {
697 if !v.is_finite() {
698 return Err("non-finite value".into());
699 }
700 let s = format!("{v:e}");
701 let (mantissa, exponent) = s
702 .split_once('e')
703 .ok_or_else(|| format!("no decimal exponent in {s}"))?;
704 let exponent: i32 = exponent
705 .parse()
706 .map_err(|_| format!("invalid decimal exponent in {s}"))?;
707 let (negative, mantissa) = match mantissa.strip_prefix('-') {
708 Some(m) => (true, m),
709 None => (false, mantissa),
710 };
711 let fraction = mantissa.split_once('.').map_or(0, |(_, f)| f.len());
712 let fraction = i32::try_from(fraction).map_err(|_| format!("mantissa too long in {s}"))?;
713 Ok(Exact {
714 negative,
715 digits: mantissa
716 .bytes()
717 .filter(u8::is_ascii_digit)
718 .map(|d| d - b'0')
719 .collect(),
720 exponent: exponent - fraction,
721 })
722}
723fn exact(t: Decimal) -> Exact {
724 Exact {
725 negative: t.is_negative(),
726 digits: t
727 .units()
728 .unsigned_abs()
729 .to_string()
730 .bytes()
731 .map(|d| d - b'0')
732 .collect(),
733 exponent: -i32::try_from(rustev_contract::decimal::SCALE).expect("small scale"),
734 }
735}
736fn exact_sum_cmp(lhs: &[Exact], rhs: &[Exact]) -> std::cmp::Ordering {
739 let terms = lhs
740 .iter()
741 .map(|t| (t, false))
742 .chain(rhs.iter().map(|t| (t, true)));
743 let low = lhs.iter().chain(rhs).map(|t| t.exponent).min().unwrap_or(0);
744 let (mut pos, mut neg) = (Vec::new(), Vec::new());
746 for (t, subtract) in terms {
747 let shift = usize::try_from(t.exponent - low).expect("aligned to the lowest exponent");
748 let mut m = vec![0u8; shift];
749 m.extend(t.digits.iter().rev());
750 add_digits(
751 if t.negative != subtract {
752 &mut neg
753 } else {
754 &mut pos
755 },
756 &m,
757 );
758 }
759 let trim = |v: &mut Vec<u8>| {
760 while v.last() == Some(&0) {
761 v.pop();
762 }
763 };
764 trim(&mut pos);
765 trim(&mut neg);
766 pos.len()
767 .cmp(&neg.len())
768 .then_with(|| pos.iter().rev().cmp(neg.iter().rev()))
769}
770fn add_digits(acc: &mut Vec<u8>, m: &[u8]) {
771 if acc.len() < m.len() {
772 acc.resize(m.len(), 0);
773 }
774 let mut carry = 0;
775 for (i, a) in acc.iter_mut().enumerate() {
776 let sum = *a + m.get(i).copied().unwrap_or(0) + carry;
777 *a = sum % 10;
778 carry = sum / 10;
779 if carry == 0 && i >= m.len() {
780 break;
781 }
782 }
783 if carry > 0 {
784 acc.push(carry);
785 }
786}
787fn metric_clause(
788 clause: &MetricClause,
789 gate: &SelectionGate,
790 b: &Side<'_>,
791 c: &Side<'_>,
792 cohort: &str,
793) -> ClauseOutcome {
794 let compare = || -> Result<bool, String> {
795 let bm = metric(b, cohort, clause.metric())?;
796 let cm = metric(c, cohort, clause.metric())?;
797 let bv = value(bm, false, b.host)?;
798 let cv = value(cm, true, c.host)?;
799 let higher = gate.metrics[clause.metric()] == Direction::HigherIsBetter;
800 let better = matches!(clause, MetricClause::Better { .. });
801 let tolerance = match clause {
807 MetricClause::NotWorse {
808 within: Within::Absolute(t),
809 ..
810 } => exact(*t),
811 _ => shortest(band(bm)?.max(band(cm)?))?,
812 };
813 let (b, c) = (shortest(bv)?, shortest(cv)?);
814 Ok(match (higher, better) {
815 (true, true) => exact_sum_cmp(&[c], &[b, tolerance]).is_gt(),
817 (false, true) => exact_sum_cmp(&[b], &[c, tolerance]).is_gt(),
819 (true, false) => exact_sum_cmp(&[c, tolerance], &[b]).is_ge(),
821 (false, false) => exact_sum_cmp(&[b, tolerance], &[c]).is_ge(),
823 })
824 };
825 match compare() {
826 Ok(ok) => outcome(ok, &format!("{} in {cohort}", clause.metric())),
827 Err(r) => unknown(r),
828 }
829}
830fn evaluate_clause(
831 label: String,
832 clause: &Clause,
833 gate: &SelectionGate,
834 b: &Side<'_>,
835 c: &Side<'_>,
836) -> ClauseResult {
837 match clause {
838 Clause::Metric(MetricClause::CaseRegressions {
839 metric,
840 case_regressions,
841 }) => {
842 case_regressions::evaluate(label, metric, case_regressions, gate.metrics[metric], b, c)
843 }
844 Clause::Metric(m) => result(label, metric_clause(m, gate, b, c, "all")),
845 Clause::HeldOut { held_out } => result(
846 label,
847 if c.split_role != SplitRole::HeldOut {
848 pass("nothing is held out")
849 } else {
850 match c.held_out {
851 Some(HeldOut::Counted(r))
852 if r.count > 0
853 && r.plan_count > 0
854 && r.count <= r.dataset_count
855 && r.plan_count <= r.dataset_count
856 && r.dataset_count <= 10_000 =>
857 {
858 outcome(
859 r.count <= held_out.max_evaluations,
860 "held-out lineage count",
861 )
862 }
863 Some(HeldOut::Unknown { reason }) => unknown(reason),
864 _ => unknown("held-out count missing or invalid"),
865 }
866 },
867 ),
868 Clause::AllSlices { all_slices } => {
869 let slices: Vec<_> = b
870 .cohorts
871 .iter()
872 .filter(|c| c.name != "all")
873 .map(|s| SliceResult {
874 slice: s.name.clone(),
875 result: metric_clause(all_slices, gate, b, c, &s.name),
876 })
877 .collect();
878 let combined = slices
879 .iter()
880 .find(|s| matches!(s.result, ClauseOutcome::Fail { .. }))
881 .or_else(|| {
882 slices
883 .iter()
884 .find(|s| matches!(s.result, ClauseOutcome::Unknown { .. }))
885 })
886 .map(|s| s.result.clone())
887 .unwrap_or_else(|| {
888 if slices.is_empty() {
889 unknown("no declared slices")
890 } else {
891 pass("every declared slice passes")
892 }
893 });
894 ClauseResult {
895 clause: label,
896 result: combined,
897 slices,
898 cases: None,
899 }
900 }
901 }
902}
903
904#[cfg(test)]
905mod tests {
906 use super::*;
907 use std::cmp::Ordering::{Equal, Greater, Less};
908
909 fn cmp(l: &[f64], t: &str, r: &[f64]) -> std::cmp::Ordering {
910 let mut lhs: Vec<_> = l.iter().map(|v| shortest(*v).unwrap()).collect();
911 lhs.push(exact(Decimal::parse(t).unwrap()));
912 let rhs: Vec<_> = r.iter().map(|v| shortest(*v).unwrap()).collect();
913 exact_sum_cmp(&lhs, &rhs)
914 }
915
916 #[test]
917 fn non_finite_values_are_refused_not_read() {
918 for v in [f64::NAN, -f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
919 assert_eq!(shortest(v).err().as_deref(), Some("non-finite value"));
920 }
921 }
922
923 #[test]
924 fn exact_sums_over_signs_and_the_binary64_range() {
925 assert_eq!(cmp(&[0.2], "0.1", &[0.3]), Equal);
926 assert_eq!(cmp(&[0.7], "0.2", &[0.9]), Equal);
927 assert_eq!(cmp(&[-0.3], "0.1", &[-0.2]), Equal);
928 assert_eq!(cmp(&[-0.0], "0", &[0.0]), Equal);
929 assert_eq!(cmp(&[f64::MAX], "1", &[f64::MAX]), Greater);
930 assert_eq!(cmp(&[5e-324], "0", &[1e-323]), Less);
931 assert_eq!(cmp(&[-f64::MAX], "0.000000001", &[f64::MIN_POSITIVE]), Less);
932 assert_eq!(cmp(&[9.999_999_999], "0.000000001", &[10.0]), Equal);
933 }
934}