Skip to main content

rustev_eval/
integrity.rs

1//! Per-run selection preconditions (spec 065). Counts are integers, never rates.
2use rustev_contract::Document;
3use rustev_contract::eval_report::MetricValue;
4use serde::{Deserialize, Serialize};
5
6use crate::config::EvaluatorConfig;
7use crate::host_run::{HostOutcome, HostRunInputs};
8use crate::report::Evaluated;
9use crate::scores::{ScoreOutcome, score_ok};
10use crate::scoring::ScorerKind;
11use crate::selection::{ClauseOutcome, ClauseResult};
12
13/// Optional, inclusive per-run bounds, on both sides of a selection.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
15#[serde(deny_unknown_fields)]
16pub struct Integrity {
17    #[serde(
18        default,
19        skip_serializing_if = "Option::is_none",
20        deserialize_with = "present"
21    )]
22    // Absent or an integer; the parser refuses `null`.
23    #[schemars(with = "u64")]
24    pub max_invalid: Option<u64>,
25    #[serde(
26        default,
27        skip_serializing_if = "Option::is_none",
28        deserialize_with = "present"
29    )]
30    #[schemars(with = "u64")]
31    pub max_upstream_failures: Option<u64>,
32}
33
34pub(crate) fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
35where
36    D: serde::Deserializer<'de>,
37    T: Deserialize<'de>,
38{
39    T::deserialize(deserializer).map(Some)
40}
41
42impl Integrity {
43    pub fn check(&self) -> Result<(), String> {
44        if self.max_invalid.is_none() && self.max_upstream_failures.is_none() {
45            return Err("integrity needs at least one bound".into());
46        }
47        if [self.max_invalid, self.max_upstream_failures]
48            .into_iter()
49            .flatten()
50            .any(|n| n > 1_000_000)
51        {
52            return Err("integrity bounds must be integers in [0, 1000000]".into());
53        }
54        Ok(())
55    }
56}
57
58/// Counts from one run, with the document identities that determine them.
59/// An error is an unestablished count, never zero. Callers must verify the
60/// enclosing set's bindings before using these counts for comparison.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct IntegrityCounts {
63    pub invalid: Result<u64, String>,
64    pub upstream_failures: Result<u64, String>,
65    pub sources: Vec<String>,
66    pub host_asserted: bool,
67}
68
69/// The cases of a Rustev-evaluated run that 3.2.2 counts as upstream
70/// failures; spec 074 (3.2.1) excuses exactly these.
71pub(crate) fn evaluated_upstream_cases(run: &Evaluated) -> std::collections::BTreeSet<String> {
72    run.detail
73        .cases
74        .iter()
75        .filter(|c| {
76            matches!(
77                c.outcome.as_str(),
78                "abstention:backend_unavailable"
79                    | "abstention:invalid_backend_output"
80                    | "abstention:deadline_exceeded"
81            ) || (c.outcome == "incomparable"
82                && c.reason.as_deref() == Some("historical-runtime-failure"))
83        })
84        .map(|c| c.case.clone())
85        .collect()
86}
87
88/// The cases of a host run that 3.2.4 counts: every `failed` outcome.
89pub(crate) fn host_upstream_cases(run: &HostRunInputs<'_>) -> std::collections::BTreeSet<String> {
90    run.record
91        .cases
92        .iter()
93        .filter(|c| matches!(c.outcome, HostOutcome::Failed(_)))
94        .map(|c| c.case.clone())
95        .collect()
96}
97
98/// Read a Rustev-evaluated run's verified report and detail. A scorer without
99/// a standalone rubric count cannot be reconstructed from an agreement's
100/// joint exclusions, so its count is unestablished (065, 3.2.5).
101pub fn evaluated_counts(run: &Evaluated) -> IntegrityCounts {
102    let invalid = (|| {
103        let d = run.config.declarations().ok_or("no declared scorer")?;
104        if d.scorers.is_empty() {
105            return Err("no declared scorer".into());
106        }
107        let mut largest = 0;
108        for scorer in d.scorers {
109            let metrics: Vec<_> = d
110                .rubric_metrics
111                .iter()
112                .filter(|m| m.scorer == scorer.id)
113                .collect();
114            if metrics.is_empty() {
115                return Err(format!("{}: no per-scorer count", scorer.id));
116            }
117            let mut scorer_count = None;
118            for metric in metrics {
119                let name = format!(
120                    "{}rubric/{}",
121                    if scorer.kind == ScorerKind::Model {
122                        "model/"
123                    } else {
124                        ""
125                    },
126                    metric.name
127                );
128                let value = run
129                    .report
130                    .metrics
131                    .iter()
132                    .find(|m| m.name == name)
133                    .ok_or_else(|| format!("{name}: report metric missing"))?;
134                let count = run
135                    .detail
136                    .count(&name)
137                    .ok_or_else(|| format!("{name}: detail count missing"))?;
138                if matches!(&value.value, MetricValue::Unknown { reason } if reason == "scores-missing")
139                    || count.breakdown.contains_key("scores-missing")
140                {
141                    return Err(format!("{}: scores-missing", scorer.id));
142                }
143                let n = count
144                    .breakdown
145                    .iter()
146                    .filter(|(reason, _)| reason.starts_with("unscored:"))
147                    .try_fold(0u64, |sum, (_, n)| sum.checked_add(*n))
148                    .ok_or("unscored count overflow")?;
149                if scorer_count.is_some_and(|previous| previous != n) {
150                    return Err(format!("{}: inconsistent per-scorer counts", scorer.id));
151                }
152                scorer_count = Some(n);
153                largest = largest.max(n);
154            }
155        }
156        Ok(largest)
157    })();
158    let upstream_failures = Ok(evaluated_upstream_cases(run).len() as u64);
159    IntegrityCounts {
160        invalid,
161        upstream_failures,
162        sources: vec![
163            format!("report:{}", run.detail.report),
164            format!(
165                "detail:{}",
166                run.detail
167                    .record_digest()
168                    .expect("verified detail serializes")
169            ),
170        ],
171        host_asserted: false,
172    }
173}
174
175/// Read a verified host run's answered-case scores and failed outcomes.
176/// Missing scores, including for a run with no answered cases, remain unknown.
177pub fn host_counts(config: &EvaluatorConfig, run: &HostRunInputs<'_>) -> IntegrityCounts {
178    let invalid = (|| {
179        let d = config.declarations().ok_or("no declared scorer")?;
180        if d.scorers.is_empty() {
181            return Err("no declared scorer".into());
182        }
183        let mut largest = 0;
184        for scorer in d.scorers {
185            let scores = run
186                .scores
187                .iter()
188                .find(|s| s.scorer == *scorer)
189                .ok_or_else(|| format!("{}: scores-missing", scorer.id))?;
190            let mut count = 0;
191            for case in run
192                .record
193                .cases
194                .iter()
195                .filter(|c| c.outcome == HostOutcome::Answered)
196            {
197                let entry = scores
198                    .entries
199                    .iter()
200                    .find(|e| e.case == case.case)
201                    .ok_or_else(|| format!("{}: case score missing", case.case))?;
202                if !matches!(entry.outcome, ScoreOutcome::Score(v) if score_ok(&scorer.output, v)) {
203                    count += 1;
204                }
205            }
206            largest = largest.max(count);
207        }
208        Ok(largest)
209    })();
210    let mut sources = vec![format!(
211        "host-run:{}",
212        run.record
213            .record_digest()
214            .expect("verified host run serializes")
215    )];
216    sources.extend(run.scores.iter().map(|s| {
217        format!(
218            "scores:{}",
219            s.record_digest().expect("verified scores serialize")
220        )
221    }));
222    IntegrityCounts {
223        invalid,
224        upstream_failures: Ok(host_upstream_cases(run).len() as u64),
225        sources,
226        host_asserted: true,
227    }
228}
229
230pub(crate) fn entry(
231    side: &str,
232    run: usize,
233    bounds: &Integrity,
234    counts: IntegrityCounts,
235) -> ClauseResult {
236    let mut reasons = vec![];
237    let mut breach = false;
238    for (name, limit, count) in [
239        ("invalid", bounds.max_invalid, counts.invalid),
240        (
241            "upstream-failures",
242            bounds.max_upstream_failures,
243            counts.upstream_failures,
244        ),
245    ] {
246        if let Some(limit) = limit {
247            reasons.push(match count {
248                Ok(count) if count <= limit => format!("{name}: count={count}, limit={limit}"),
249                Ok(count) => {
250                    breach = true;
251                    format!("{name}-exceeded: count={count}, limit={limit}")
252                }
253                Err(reason) => {
254                    breach = true;
255                    format!("{name}-uncountable: {reason}, limit={limit}")
256                }
257            });
258        }
259    }
260    reasons.push(format!("sources=[{}]", counts.sources.join(", ")));
261    if counts.host_asserted {
262        reasons.push("assertion: \"host-asserted\"".into());
263    }
264    let reason = reasons.join("; ");
265    ClauseResult {
266        clause: format!("{side}.runs[{run}].integrity"),
267        result: if breach {
268            ClauseOutcome::Unknown { reason }
269        } else {
270            ClauseOutcome::Pass { reason }
271        },
272        slices: vec![],
273        cases: None,
274    }
275}
276
277pub(crate) fn breached(clauses: &[ClauseResult]) -> bool {
278    clauses.iter().any(|c| {
279        c.clause.ends_with(".integrity") && matches!(c.result, ClauseOutcome::Unknown { .. })
280    })
281}