Skip to main content

vela_protocol/analysis/
inspect_adapter.rs

1//! Inspect-AI eval log → verifier attachment (`vva_`).
2//!
3//! The first external attachment *source* beyond the built-in frozen verifier
4//! (vela-verify) and the Lean kernel. It closes the receipt boundary's demo
5//! case: an [Inspect-AI](https://inspect.aisi.org.uk/) eval log — a task run
6//! against a scorer — becomes a content-addressed [`VerifierAttachment`] bound
7//! to the exact claim the target finding asserts.
8//!
9//! ## Evidence, not a verdict — by construction
10//!
11//! An Inspect eval is an *evaluation harness*, often with a model-graded
12//! scorer. It is NOT a frozen exact verifier. This adapter therefore never
13//! self-certifies:
14//!
15//! - The attachment's [`VerifierMethod`] is [`VerifierMethod::EvalHarness`], a
16//!   method distinct from `ComputationalSearch`/`LeanKernel`, so the gate's G1
17//!   independence sees it as its own kind of evidence.
18//! - [`MethodIntegrity`] is left at the default `Unattested`. The exact-lane
19//!   auto-admit predicate requires `Sound` on every matched attachment, so an
20//!   Inspect attachment can NEVER auto-admit a finding — a human must clear it,
21//!   exactly the "attested by CI, never reproduced" posture of the CI-proof
22//!   source.
23//! - Adversarial probes are populated ONLY from samples the log itself marks
24//!   adversarial (`metadata.adversarial == true`). A plain accuracy eval with
25//!   no adversarial sample yields an attachment with no probe, which fails the
26//!   gate's G3 on its own — it records the check, it does not verify the claim.
27//!
28//! A lone Inspect attachment fails G1 (needs >=2 matched independent). The gate
29//! (G1-G5) and the human key still decide. Not every Inspect score is
30//! admissible verification; the frontier policy decides what a passing
31//! `eval_harness` attachment is worth.
32//!
33//! ## The log shape it reads
34//!
35//! Inspect's `.eval` logs are archives, but Inspect also emits/serializes the
36//! same `EvalLog` as JSON (`inspect log dump`, the older `.json` writer). This
37//! parser is tolerant: it reads the fields it needs and ignores the rest, so
38//! it survives Inspect's schema evolution.
39//!
40//! ```jsonc
41//! {
42//!   "status": "success",
43//!   "eval": { "task": "erdos_sidon_bound", "model": "openai/gpt-4o",
44//!             "dataset": {"name": "sidon-a17"}, "scorers": [{"name": "match"}] },
45//!   "results": { "total_samples": 1, "completed_samples": 1,
46//!                "scores": [{"name": "match", "scorer": "match",
47//!                            "metrics": {"accuracy": {"value": 1.0}}}] },
48//!   "samples": [{"id": "s1", "score": {"value": 1.0},
49//!                "metadata": {"adversarial": true}}]
50//! }
51//! ```
52
53use crate::verifier_attachment::{
54    AdversarialProbe, AttachmentDraft, AttachmentOutcome, MatchToClaim, ProbeKind, ProbeResult,
55    VerifierMethod,
56};
57use serde::Deserialize;
58
59/// The threshold below which a headline eval score is treated as a fail. An
60/// exact-match single-sample task passes at 1.0; a caller can loosen it.
61pub const DEFAULT_PASS_THRESHOLD: f64 = 1.0;
62
63/// The minimal Inspect `EvalLog` shape this adapter reads. Every field is
64/// optional/tolerant so an evolving Inspect schema still parses.
65#[derive(Debug, Clone, Deserialize)]
66pub struct InspectLog {
67    #[serde(default)]
68    pub status: String,
69    #[serde(default)]
70    pub eval: InspectEvalSpec,
71    #[serde(default)]
72    pub results: InspectResults,
73    #[serde(default)]
74    pub samples: Vec<InspectSample>,
75}
76
77#[derive(Debug, Clone, Default, Deserialize)]
78pub struct InspectEvalSpec {
79    #[serde(default)]
80    pub task: String,
81    #[serde(default)]
82    pub model: String,
83    #[serde(default)]
84    pub dataset: InspectDataset,
85    #[serde(default)]
86    pub scorers: Vec<InspectScorer>,
87}
88
89#[derive(Debug, Clone, Default, Deserialize)]
90pub struct InspectDataset {
91    #[serde(default)]
92    pub name: String,
93}
94
95#[derive(Debug, Clone, Default, Deserialize)]
96pub struct InspectScorer {
97    #[serde(default)]
98    pub name: String,
99}
100
101#[derive(Debug, Clone, Default, Deserialize)]
102pub struct InspectResults {
103    #[serde(default)]
104    pub total_samples: u64,
105    #[serde(default)]
106    pub completed_samples: u64,
107    #[serde(default)]
108    pub scores: Vec<InspectScore>,
109}
110
111#[derive(Debug, Clone, Default, Deserialize)]
112pub struct InspectScore {
113    #[serde(default)]
114    pub name: String,
115    #[serde(default)]
116    pub scorer: String,
117    #[serde(default)]
118    pub metrics: std::collections::BTreeMap<String, InspectMetric>,
119}
120
121#[derive(Debug, Clone, Default, Deserialize)]
122pub struct InspectMetric {
123    #[serde(default)]
124    pub value: f64,
125}
126
127#[derive(Debug, Clone, Default, Deserialize)]
128pub struct InspectSample {
129    #[serde(default)]
130    pub id: serde_json::Value,
131    #[serde(default)]
132    pub score: InspectSampleScore,
133    #[serde(default)]
134    pub metadata: std::collections::BTreeMap<String, serde_json::Value>,
135}
136
137#[derive(Debug, Clone, Default, Deserialize)]
138pub struct InspectSampleScore {
139    #[serde(default)]
140    pub value: f64,
141}
142
143impl InspectLog {
144    /// The scorer name — the tool that produced the judgment. Prefers the
145    /// results score's `scorer`, then its `name`, then the eval's declared
146    /// scorer. `"scorer"` is the neutral fallback.
147    #[must_use]
148    pub fn scorer_name(&self) -> String {
149        self.results
150            .scores
151            .first()
152            .map(|s| {
153                if !s.scorer.is_empty() {
154                    s.scorer.clone()
155                } else {
156                    s.name.clone()
157                }
158            })
159            .filter(|s| !s.is_empty())
160            .or_else(|| {
161                self.eval
162                    .scorers
163                    .first()
164                    .map(|s| s.name.clone())
165                    .filter(|s| !s.is_empty())
166            })
167            .unwrap_or_else(|| "scorer".to_string())
168    }
169
170    /// The headline metric value: the first score's `accuracy`, else its first
171    /// metric, else `0.0`. This is what `--threshold` compares against.
172    #[must_use]
173    pub fn headline_value(&self) -> f64 {
174        let Some(score) = self.results.scores.first() else {
175            return 0.0;
176        };
177        if let Some(acc) = score.metrics.get("accuracy") {
178            return acc.value;
179        }
180        score
181            .metrics
182            .values()
183            .next()
184            .map(|m| m.value)
185            .unwrap_or(0.0)
186    }
187}
188
189/// Build an [`AttachmentDraft`] from a parsed Inspect log, bound to `target`
190/// and `claim_digest`. `threshold` is the headline-metric floor for `Passed`
191/// ([`DEFAULT_PASS_THRESHOLD`] is exact-match at 1.0).
192///
193/// The draft is intentionally `Unattested` (the caller must NOT promote it to
194/// `Sound`): an eval harness is evidence, not a frozen verifier.
195///
196/// `source_ref` names where the log came from (a path or uri), carried in the
197/// attachment note for provenance.
198pub fn draft_from_log(
199    log: &InspectLog,
200    target: &str,
201    claim_digest: String,
202    threshold: f64,
203    source_ref: &str,
204) -> Result<AttachmentDraft, String> {
205    let scorer = log.scorer_name();
206    let value = log.headline_value();
207    let status_ok = log.status.is_empty() || log.status == "success";
208    let complete = log.results.total_samples == 0
209        || log.results.completed_samples >= log.results.total_samples;
210    let passed = status_ok && complete && value >= threshold;
211
212    // Adversarial probes ONLY from samples the log marks adversarial. A passing
213    // adversarial sample survived the probe; a failing one refuted the claim.
214    // No adversarial sample => no probe (the attachment then fails G3 alone).
215    let mut adversarial_probes = Vec::new();
216    for s in &log.samples {
217        let is_adv = s
218            .metadata
219            .get("adversarial")
220            .and_then(serde_json::Value::as_bool)
221            .unwrap_or(false);
222        if !is_adv {
223            continue;
224        }
225        let survived = s.score.value >= threshold;
226        adversarial_probes.push(AdversarialProbe {
227            kind: ProbeKind::CounterexampleSearch,
228            result: if survived {
229                ProbeResult::Survived
230            } else {
231                ProbeResult::Refuted
232            },
233            note: format!("inspect adversarial sample {}", sample_id(&s.id)),
234            evidence_root: String::new(),
235        });
236    }
237
238    let model = if log.eval.model.is_empty() {
239        "unknown-model".to_string()
240    } else {
241        log.eval.model.clone()
242    };
243    let task = if log.eval.task.is_empty() {
244        "inspect-task".to_string()
245    } else {
246        log.eval.task.clone()
247    };
248
249    Ok(AttachmentDraft {
250        target: target.to_string(),
251        claim_digest,
252        verifier_method: VerifierMethod::EvalHarness,
253        // The tool that produced the check: Inspect + the scorer. Distinct from
254        // a frozen solver id, so G1 treats it as its own method/solver.
255        solver_id: format!("inspect:{scorer}"),
256        independent_of: Vec::new(),
257        match_to_claim: MatchToClaim {
258            matches: true,
259            checker_actor: format!("inspect:{task}"),
260        },
261        adversarial_probes,
262        outcome: if passed {
263            AttachmentOutcome::Passed
264        } else {
265            AttachmentOutcome::Failed
266        },
267        verifier_actor: format!("inspect:{model}"),
268        note: format!(
269            "Inspect-AI eval `{task}` (model {model}, scorer {scorer}, score {value:.3} \
270             vs threshold {threshold:.3}); source {source_ref}. Evidence only — eval harness, \
271             method_integrity unattested; does not by itself verify the claim."
272        ),
273    })
274}
275
276/// Parse a raw Inspect log JSON string into [`InspectLog`].
277pub fn parse_log(json: &str) -> Result<InspectLog, String> {
278    serde_json::from_str(json).map_err(|e| format!("parse Inspect eval log JSON: {e}"))
279}
280
281fn sample_id(v: &serde_json::Value) -> String {
282    match v {
283        serde_json::Value::String(s) => s.clone(),
284        serde_json::Value::Number(n) => n.to_string(),
285        serde_json::Value::Null => "?".to_string(),
286        other => other.to_string(),
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    use crate::verifier_attachment::{
294        AttachmentOutcome, GateStatus, MethodIntegrity, VerifierAttachment, claim_digest,
295        derive_gate_status,
296    };
297
298    const SAMPLE: &str = r#"{
299        "status": "success",
300        "eval": {
301            "task": "erdos_sidon_bound",
302            "model": "openai/gpt-4o",
303            "dataset": {"name": "sidon-a17"},
304            "scorers": [{"name": "match"}]
305        },
306        "results": {
307            "total_samples": 1,
308            "completed_samples": 1,
309            "scores": [{"name": "match", "scorer": "match",
310                        "metrics": {"accuracy": {"value": 1.0}}}]
311        },
312        "samples": [{"id": "s1", "score": {"value": 1.0},
313                     "metadata": {"adversarial": true}}]
314    }"#;
315
316    #[test]
317    fn parses_and_builds_a_passing_unattested_attachment() {
318        let log = parse_log(SAMPLE).unwrap();
319        let digest = claim_digest("a Sidon set of size 33 in [0,256]");
320        let draft =
321            draft_from_log(&log, "vf_0123456789abcdef", digest.clone(), 1.0, "run.json").unwrap();
322        let att = VerifierAttachment::build(draft).unwrap();
323        // Evidence, not a verdict: method is EvalHarness, integrity Unattested.
324        assert_eq!(att.verifier_method, VerifierMethod::EvalHarness);
325        assert_eq!(att.method_integrity, MethodIntegrity::Unattested);
326        assert_eq!(att.outcome, AttachmentOutcome::Passed);
327        assert_eq!(att.solver_id, "inspect:match");
328        assert!(att.claim_digest == digest);
329        // One adversarial sample => one surviving probe.
330        assert_eq!(att.adversarial_probes.len(), 1);
331        assert_eq!(att.adversarial_probes[0].result, ProbeResult::Survived);
332        // Content-addressed id holds.
333        att.verify().unwrap();
334    }
335
336    #[test]
337    fn deterministic_id_from_a_fixed_log() {
338        let log = parse_log(SAMPLE).unwrap();
339        let digest = claim_digest("claim X");
340        let a = VerifierAttachment::build(
341            draft_from_log(&log, "vf_0123456789abcdef", digest.clone(), 1.0, "run.json").unwrap(),
342        )
343        .unwrap();
344        let b = VerifierAttachment::build(
345            draft_from_log(&log, "vf_0123456789abcdef", digest, 1.0, "run.json").unwrap(),
346        )
347        .unwrap();
348        assert_eq!(a.id, b.id, "same log + target + digest => same vva_ id");
349    }
350
351    #[test]
352    fn a_lone_inspect_attachment_does_not_verify() {
353        // The doctrine: a single eval-harness attachment is evidence, never a
354        // verdict. It fails G1 (needs >=2 matched independent) on its own.
355        let log = parse_log(SAMPLE).unwrap();
356        let digest = claim_digest("claim X");
357        let att = VerifierAttachment::build(
358            draft_from_log(&log, "vf_0123456789abcdef", digest.clone(), 1.0, "run.json").unwrap(),
359        )
360        .unwrap();
361        let outcome = derive_gate_status(&digest, &[att]);
362        assert_eq!(outcome.status, GateStatus::NeedsVerification);
363        assert!(outcome.reasons.iter().any(|r| r.starts_with("G1")));
364    }
365
366    #[test]
367    fn failing_score_yields_a_failed_attachment() {
368        let json = SAMPLE.replace("\"value\": 1.0", "\"value\": 0.5");
369        let log = parse_log(&json).unwrap();
370        let digest = claim_digest("claim X");
371        let draft = draft_from_log(&log, "vf_0123456789abcdef", digest, 1.0, "run.json").unwrap();
372        assert_eq!(draft.outcome, AttachmentOutcome::Failed);
373    }
374
375    #[test]
376    fn adversarial_failure_becomes_a_refuting_probe() {
377        // A failing adversarial sample refutes: the probe drives Refuted, so an
378        // eval that finds a counterexample cannot be spun as support.
379        let json = r#"{
380            "status": "success",
381            "eval": {"task": "t", "model": "m", "scorers": [{"name": "match"}]},
382            "results": {"total_samples": 1, "completed_samples": 1,
383                        "scores": [{"scorer": "match", "metrics": {"accuracy": {"value": 1.0}}}]},
384            "samples": [{"id": 1, "score": {"value": 0.0}, "metadata": {"adversarial": true}}]
385        }"#;
386        let log = parse_log(json).unwrap();
387        let digest = claim_digest("claim X");
388        let draft = draft_from_log(&log, "vf_0123456789abcdef", digest, 1.0, "run.json").unwrap();
389        assert_eq!(draft.adversarial_probes.len(), 1);
390        assert_eq!(draft.adversarial_probes[0].result, ProbeResult::Refuted);
391    }
392
393    #[test]
394    fn tolerates_a_minimal_log() {
395        // Only the fields the adapter needs; everything else absent.
396        let json = r#"{"eval": {"task": "t"}, "results": {"scores": []}}"#;
397        let log = parse_log(json).unwrap();
398        let digest = claim_digest("claim X");
399        let draft = draft_from_log(&log, "vf_0123456789abcdef", digest, 1.0, "run.json").unwrap();
400        // No score => headline 0.0 => Failed, and no probe.
401        assert_eq!(draft.outcome, AttachmentOutcome::Failed);
402        assert!(draft.adversarial_probes.is_empty());
403        assert_eq!(draft.solver_id, "inspect:scorer");
404    }
405}