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    for (b, c) in b.inputs.runs.iter().zip(c.inputs.runs) {
463        let comparable = |e: &crate::report::Evaluated| -> BTreeSet<String> {
464            e.detail
465                .cases
466                .iter()
467                .filter(|c| {
468                    c.outcome.starts_with("proposal:") || c.outcome.starts_with("abstention:")
469                })
470                .map(|c| c.case.clone())
471                .collect()
472        };
473        if comparable(b.evaluated) != comparable(c.evaluated) {
474            return Err("per-run comparable cohorts differ".into());
475        }
476        if b.evaluated
477            .detail
478            .count("candidate_outcome_change")
479            .is_some()
480            || c.evaluated
481                .detail
482                .count("candidate_outcome_change")
483                .is_none()
484        {
485            return Err("run baseline and candidate roles do not hold".into());
486        }
487    }
488    Ok(())
489}
490
491fn metric<'a>(r: &'a RepeatReport, cohort: &str, name: &str) -> Result<&'a MetricReport, String> {
492    let c = r
493        .cohorts
494        .iter()
495        .find(|c| c.name == cohort)
496        .ok_or_else(|| format!("missing cohort {cohort}"))?;
497    if c.status == CohortStatus::BelowMinimum {
498        return Err(format!("{cohort}: below_minimum"));
499    }
500    c.metrics
501        .iter()
502        .find(|m| m.name == name)
503        .ok_or_else(|| format!("metric {name} not reported in {cohort}"))
504}
505fn value(m: &MetricReport, candidate: bool) -> Result<f64, String> {
506    if candidate && observed(&m.name) && m.observation != Some(Observation::Candidate) {
507        return Err(format!(
508            "{}: historical or missing candidate observation",
509            m.name
510        ));
511    }
512    match &m.pooled {
513        FigureDoc::Value(v) if v.is_finite() => Ok(*v),
514        FigureDoc::Unknown(r) => Err(format!("{}: {r}", m.name)),
515        _ => Err("non-finite value".into()),
516    }
517}
518fn band(m: &MetricReport) -> Result<f64, String> {
519    match &m.band {
520        BandDoc::Value { value, .. } if value.is_finite() && *value >= 0.0 => Ok(*value),
521        BandDoc::Unknown(r) => Err(format!("{} band: {r}", m.name)),
522        _ => Err("invalid band".into()),
523    }
524}
525fn metric_clause(
526    clause: &MetricClause,
527    gate: &SelectionGate,
528    b: &RepeatReport,
529    c: &RepeatReport,
530    cohort: &str,
531) -> ClauseOutcome {
532    let compare = || -> Result<bool, String> {
533        let bm = metric(b, cohort, clause.metric())?;
534        let cm = metric(c, cohort, clause.metric())?;
535        let bv = value(bm, false)?;
536        let cv = value(cm, true)?;
537        let tolerance = match clause {
538            MetricClause::NotWorse {
539                within: Within::Absolute(t),
540                ..
541            } => t.to_f64_nearest(),
542            _ => band(bm)?.max(band(cm)?),
543        };
544        let higher = gate.metrics[clause.metric()] == Direction::HigherIsBetter;
545        let better = matches!(clause, MetricClause::Better { .. });
546        let threshold = if higher == better {
547            bv + tolerance
548        } else {
549            bv - tolerance
550        };
551        if !threshold.is_finite() {
552            return Err("non-finite comparison threshold".into());
553        }
554        Ok(match (higher, better) {
555            (true, true) => cv > threshold,
556            (false, true) => cv < threshold,
557            (true, false) => cv >= threshold,
558            (false, false) => cv <= threshold,
559        })
560    };
561    match compare() {
562        Ok(ok) => outcome(ok, &format!("{} in {cohort}", clause.metric())),
563        Err(r) => unknown(r),
564    }
565}
566fn evaluate_clause(
567    label: String,
568    clause: &Clause,
569    gate: &SelectionGate,
570    b: &RepeatReport,
571    c: &RepeatReport,
572) -> ClauseResult {
573    match clause {
574        Clause::Metric(m) => result(label, metric_clause(m, gate, b, c, "all")),
575        Clause::HeldOut { held_out } => result(
576            label,
577            if c.split_role != SplitRole::HeldOut {
578                pass("nothing is held out")
579            } else {
580                match &c.held_out {
581                    Some(HeldOut::Counted(r))
582                        if r.count > 0
583                            && r.plan_count > 0
584                            && r.count <= r.dataset_count
585                            && r.plan_count <= r.dataset_count
586                            && r.dataset_count <= 10_000 =>
587                    {
588                        outcome(
589                            r.count <= held_out.max_evaluations,
590                            "held-out lineage count",
591                        )
592                    }
593                    Some(HeldOut::Unknown { reason }) => unknown(reason),
594                    _ => unknown("held-out count missing or invalid"),
595                }
596            },
597        ),
598        Clause::AllSlices { all_slices } => {
599            let slices: Vec<_> = b
600                .cohorts
601                .iter()
602                .filter(|c| c.name != "all")
603                .map(|s| SliceResult {
604                    slice: s.name.clone(),
605                    result: metric_clause(all_slices, gate, b, c, &s.name),
606                })
607                .collect();
608            let combined = slices
609                .iter()
610                .find(|s| matches!(s.result, ClauseOutcome::Fail { .. }))
611                .or_else(|| {
612                    slices
613                        .iter()
614                        .find(|s| matches!(s.result, ClauseOutcome::Unknown { .. }))
615                })
616                .map(|s| s.result.clone())
617                .unwrap_or_else(|| {
618                    if slices.is_empty() {
619                        unknown("no declared slices")
620                    } else {
621                        pass("every declared slice passes")
622                    }
623                });
624            ClauseResult {
625                clause: label,
626                result: combined,
627                slices,
628            }
629        }
630    }
631}