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