1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
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 pub max_invalid: Option<u64>,
23 #[serde(
24 default,
25 skip_serializing_if = "Option::is_none",
26 deserialize_with = "present"
27 )]
28 pub max_upstream_failures: Option<u64>,
29}
30
31pub(crate) fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
32where
33 D: serde::Deserializer<'de>,
34 T: Deserialize<'de>,
35{
36 T::deserialize(deserializer).map(Some)
37}
38
39impl Integrity {
40 pub fn check(&self) -> Result<(), String> {
41 if self.max_invalid.is_none() && self.max_upstream_failures.is_none() {
42 return Err("integrity needs at least one bound".into());
43 }
44 if [self.max_invalid, self.max_upstream_failures]
45 .into_iter()
46 .flatten()
47 .any(|n| n > 1_000_000)
48 {
49 return Err("integrity bounds must be integers in [0, 1000000]".into());
50 }
51 Ok(())
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct IntegrityCounts {
60 pub invalid: Result<u64, String>,
61 pub upstream_failures: Result<u64, String>,
62 pub sources: Vec<String>,
63 pub host_asserted: bool,
64}
65
66pub fn evaluated_counts(run: &Evaluated) -> IntegrityCounts {
70 let invalid = (|| {
71 let d = run.config.declarations().ok_or("no declared scorer")?;
72 if d.scorers.is_empty() {
73 return Err("no declared scorer".into());
74 }
75 let mut largest = 0;
76 for scorer in d.scorers {
77 let metrics: Vec<_> = d
78 .rubric_metrics
79 .iter()
80 .filter(|m| m.scorer == scorer.id)
81 .collect();
82 if metrics.is_empty() {
83 return Err(format!("{}: no per-scorer count", scorer.id));
84 }
85 let mut scorer_count = None;
86 for metric in metrics {
87 let name = format!(
88 "{}rubric/{}",
89 if scorer.kind == ScorerKind::Model {
90 "model/"
91 } else {
92 ""
93 },
94 metric.name
95 );
96 let value = run
97 .report
98 .metrics
99 .iter()
100 .find(|m| m.name == name)
101 .ok_or_else(|| format!("{name}: report metric missing"))?;
102 let count = run
103 .detail
104 .count(&name)
105 .ok_or_else(|| format!("{name}: detail count missing"))?;
106 if matches!(&value.value, MetricValue::Unknown { reason } if reason == "scores-missing")
107 || count.breakdown.contains_key("scores-missing")
108 {
109 return Err(format!("{}: scores-missing", scorer.id));
110 }
111 let n = count
112 .breakdown
113 .iter()
114 .filter(|(reason, _)| reason.starts_with("unscored:"))
115 .try_fold(0u64, |sum, (_, n)| sum.checked_add(*n))
116 .ok_or("unscored count overflow")?;
117 if scorer_count.is_some_and(|previous| previous != n) {
118 return Err(format!("{}: inconsistent per-scorer counts", scorer.id));
119 }
120 scorer_count = Some(n);
121 largest = largest.max(n);
122 }
123 }
124 Ok(largest)
125 })();
126 let upstream_failures = Ok(run
127 .detail
128 .cases
129 .iter()
130 .filter(|c| {
131 matches!(
132 c.outcome.as_str(),
133 "abstention:backend_unavailable"
134 | "abstention:invalid_backend_output"
135 | "abstention:deadline_exceeded"
136 ) || (c.outcome == "incomparable"
137 && c.reason.as_deref() == Some("historical-runtime-failure"))
138 })
139 .count() as u64);
140 IntegrityCounts {
141 invalid,
142 upstream_failures,
143 sources: vec![
144 format!("report:{}", run.detail.report),
145 format!(
146 "detail:{}",
147 run.detail
148 .record_digest()
149 .expect("verified detail serializes")
150 ),
151 ],
152 host_asserted: false,
153 }
154}
155
156pub fn host_counts(config: &EvaluatorConfig, run: &HostRunInputs<'_>) -> IntegrityCounts {
159 let invalid = (|| {
160 let d = config.declarations().ok_or("no declared scorer")?;
161 if d.scorers.is_empty() {
162 return Err("no declared scorer".into());
163 }
164 let mut largest = 0;
165 for scorer in d.scorers {
166 let scores = run
167 .scores
168 .iter()
169 .find(|s| s.scorer == *scorer)
170 .ok_or_else(|| format!("{}: scores-missing", scorer.id))?;
171 let mut count = 0;
172 for case in run
173 .record
174 .cases
175 .iter()
176 .filter(|c| c.outcome == HostOutcome::Answered)
177 {
178 let entry = scores
179 .entries
180 .iter()
181 .find(|e| e.case == case.case)
182 .ok_or_else(|| format!("{}: case score missing", case.case))?;
183 if !matches!(entry.outcome, ScoreOutcome::Score(v) if score_ok(&scorer.output, v)) {
184 count += 1;
185 }
186 }
187 largest = largest.max(count);
188 }
189 Ok(largest)
190 })();
191 let mut sources = vec![format!(
192 "host-run:{}",
193 run.record
194 .record_digest()
195 .expect("verified host run serializes")
196 )];
197 sources.extend(run.scores.iter().map(|s| {
198 format!(
199 "scores:{}",
200 s.record_digest().expect("verified scores serialize")
201 )
202 }));
203 IntegrityCounts {
204 invalid,
205 upstream_failures: Ok(run
206 .record
207 .cases
208 .iter()
209 .filter(|c| matches!(c.outcome, HostOutcome::Failed(_)))
210 .count() as u64),
211 sources,
212 host_asserted: true,
213 }
214}
215
216pub(crate) fn entry(
217 side: &str,
218 run: usize,
219 bounds: &Integrity,
220 counts: IntegrityCounts,
221) -> ClauseResult {
222 let mut reasons = vec![];
223 let mut breach = false;
224 for (name, limit, count) in [
225 ("invalid", bounds.max_invalid, counts.invalid),
226 (
227 "upstream-failures",
228 bounds.max_upstream_failures,
229 counts.upstream_failures,
230 ),
231 ] {
232 if let Some(limit) = limit {
233 reasons.push(match count {
234 Ok(count) if count <= limit => format!("{name}: count={count}, limit={limit}"),
235 Ok(count) => {
236 breach = true;
237 format!("{name}-exceeded: count={count}, limit={limit}")
238 }
239 Err(reason) => {
240 breach = true;
241 format!("{name}-uncountable: {reason}, limit={limit}")
242 }
243 });
244 }
245 }
246 reasons.push(format!("sources=[{}]", counts.sources.join(", ")));
247 if counts.host_asserted {
248 reasons.push("assertion: \"host-asserted\"".into());
249 }
250 let reason = reasons.join("; ");
251 ClauseResult {
252 clause: format!("{side}.runs[{run}].integrity"),
253 result: if breach {
254 ClauseOutcome::Unknown { reason }
255 } else {
256 ClauseOutcome::Pass { reason }
257 },
258 slices: vec![],
259 cases: None,
260 }
261}
262
263pub(crate) fn breached(clauses: &[ClauseResult]) -> bool {
264 clauses.iter().any(|c| {
265 c.clause.ends_with(".integrity") && matches!(c.result, ClauseOutcome::Unknown { .. })
266 })
267}