Skip to main content

lean_ctx/core/eval_ab/
arm_study.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Pure four-arm analysis of externally supplied observations.
3//!
4//! This is not evidence of temporal preregistration,
5//! authenticated measurements, blind review, model execution or customer savings.
6//!
7//! What is analysed is bounded before anything is computed: the two documents by
8//! their bytes, the protocol by its task count and bootstrap iterations, the
9//! observations by their rows, and the whole analysis by the number of resample
10//! draws it would make. An input over a bound is refused — nothing is truncated,
11//! and neither the seed nor a statistic is changed to make it fit.
12
13use std::collections::BTreeMap;
14use std::fmt;
15
16use serde::{Deserialize, Deserializer, Serialize};
17
18use super::model::{ObservationOrigin, ProviderExchange};
19use super::report::AbReport;
20
21pub const PROTOCOL_KIND: &str = "lean-ctx.arm-study-protocol";
22pub const OBSERVATIONS_KIND: &str = "lean-ctx.arm-study-observations";
23pub const REPORT_KIND: &str = "lean-ctx.arm-study-report";
24pub const SCHEMA_VERSION: u32 = 1;
25pub const MIN_TASKS: usize = 10;
26
27/// The largest protocol and observations documents that are parsed at all.
28pub const MAX_PROTOCOL_BYTES: usize = 1024 * 1024;
29pub const MAX_OBSERVATIONS_BYTES: usize = 16 * 1024 * 1024;
30pub const MAX_PROVIDER_REPORT_BYTES: usize = 16 * 1024 * 1024;
31pub const MAX_TASKS: usize = 1_000;
32pub const MAX_BOOTSTRAP_ITERS: usize = 10_000;
33pub const MAX_EVIDENCE_RECEIPTS: usize = 64;
34/// Every interval resamples `tasks` values `bootstrap_iters` times; a report has
35/// `INTERVALS` of them. Their product is the work of an analysis.
36pub const MAX_BOOTSTRAP_DRAWS: u64 = 200_000_000;
37/// An UPPER bound: four arms × six metrics, and three arms × four contrasts.
38/// A real report makes at most 34 (two arms have no sync bytes), fewer when a
39/// provider reported no cache reads; the budget is deliberately the larger number.
40const INTERVALS: u64 = 4 * 6 + 3 * 4;
41
42/// How [`ArmSummary::latency_ms_p95`] is taken.
43pub const P95_RULE: &str = "nearest_rank";
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
46#[serde(rename_all = "snake_case", deny_unknown_fields)]
47pub enum Arm {
48    UnchangedAgent,
49    Community,
50    Team,
51    Company,
52}
53
54pub const ALL: [Arm; 4] = [Arm::UnchangedAgent, Arm::Community, Arm::Team, Arm::Company];
55
56impl Arm {
57    pub fn label(self) -> &'static str {
58        match self {
59            Self::UnchangedAgent => "unchanged_agent",
60            Self::Community => "community",
61            Self::Team => "team",
62            Self::Company => "company",
63        }
64    }
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize)]
68#[serde(deny_unknown_fields)]
69pub struct Protocol {
70    schema_version: u32,
71    kind: String,
72    study_id: String,
73    tasks: Vec<RegisteredTask>,
74    bootstrap_iters: usize,
75    bootstrap_seed: u64,
76    // In-process provenance only: not accepted from or emitted onto the wire.
77    #[serde(skip)]
78    parsed_sha256: Option<String>,
79}
80
81impl Protocol {
82    /// The number of registered tasks.
83    pub fn task_count(&self) -> usize {
84        self.tasks.len()
85    }
86
87    /// The resamples every interval of this study asks for.
88    pub fn bootstrap_iters(&self) -> usize {
89        self.bootstrap_iters
90    }
91
92    /// The resample draws a whole analysis of this protocol makes, or `None`
93    /// when that number does not fit — which is over every budget.
94    pub fn bootstrap_draws(&self) -> Option<u64> {
95        u64::try_from(self.tasks.len())
96            .ok()?
97            .checked_mul(u64::try_from(self.bootstrap_iters).ok()?)?
98            .checked_mul(INTERVALS)
99    }
100
101    /// The bounds of this protocol alone, read from it and changing nothing.
102    fn admit(&self) -> Result<(), Refusal> {
103        if self.tasks.len() > MAX_TASKS {
104            return Err(Refusal::Budget { what: "tasks" });
105        }
106        if self.bootstrap_iters > MAX_BOOTSTRAP_ITERS {
107            return Err(Refusal::Budget {
108                what: "bootstrap_iters",
109            });
110        }
111        if self
112            .bootstrap_draws()
113            .is_none_or(|draws| draws > MAX_BOOTSTRAP_DRAWS)
114        {
115            return Err(Refusal::Budget {
116                what: "bootstrap_draws",
117            });
118        }
119        Ok(())
120    }
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
124#[serde(deny_unknown_fields)]
125pub struct RegisteredTask {
126    pub task_id: String,
127    pub statement_sha256: String,
128    pub rubric_sha256: String,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132#[serde(deny_unknown_fields)]
133pub struct Observations {
134    pub schema_version: u32,
135    pub kind: String,
136    pub protocol_sha256: String,
137    pub observations: Vec<Observation>,
138}
139
140// deserialize_with has no Default: missing keys refuse, explicit null is None.
141fn required_nullable<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
142    Option::<u64>::deserialize(d)
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
146#[serde(deny_unknown_fields)]
147pub struct Observation {
148    pub task_id: String,
149    pub arm: Arm,
150    pub acl_version: String,
151    pub model_fingerprint: String,
152    pub rated_blind: bool,
153    pub correctness: f64,
154    pub latency_ms: u64,
155    pub tokens_input: u64,
156    pub tokens_output: u64,
157    #[serde(deserialize_with = "required_nullable")]
158    pub provider_cache_read_tokens: Option<u64>,
159    #[serde(deserialize_with = "required_nullable")]
160    pub sync_bytes: Option<u64>,
161    pub evidence_receipts: Vec<String>,
162    /// Optional, operator-supplied provenance. Not provider authentication or
163    /// proof of the deployment arm, blindness or model consumption.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub provider_observation: Option<ProviderObservation>,
166}
167
168/// An A/B condition is selected explicitly and never mapped to a deployment arm.
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case", deny_unknown_fields)]
171pub enum ProviderCondition {
172    Baseline,
173    LeanCtx,
174}
175
176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(deny_unknown_fields)]
178pub struct ProviderObservation {
179    pub task_id: String,
180    pub arm: Arm,
181    pub condition: ProviderCondition,
182    pub model_fingerprint: String,
183    pub exchange: ProviderExchange,
184}
185
186/// Classification of supplied metadata, not authenticated measurements. These
187/// counts have no confidence interval or claim of provider-subset power.
188#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(deny_unknown_fields)]
190pub struct ProviderProvenance {
191    pub current_reported: usize,
192    pub replayed: usize,
193    pub observed_partial: usize,
194    pub unattributed: usize,
195}
196
197#[derive(Debug, Clone, Serialize, Deserialize)]
198#[serde(deny_unknown_fields)]
199pub struct MetricSummary {
200    pub n: usize,
201    pub median: f64,
202    pub ci_low: f64,
203    pub ci_high: f64,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
207#[serde(deny_unknown_fields)]
208pub struct ArmSummary {
209    pub arm: Arm,
210    pub correctness: MetricSummary,
211    pub latency_ms: MetricSummary,
212    /// The 95th percentile of the arm's latencies by nearest rank: the value at
213    /// rank `ceil(0.95 × n)` of the ascending values. An observed value, with no
214    /// interval. It is not `latency_ms.ci_high`, which bounds the MEDIAN.
215    pub latency_ms_p95: f64,
216    pub tokens_input: MetricSummary,
217    pub tokens_output: MetricSummary,
218    pub provider_cache_read_tokens: Option<MetricSummary>,
219    pub sync_bytes: Option<MetricSummary>,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub provider_provenance: Option<ProviderProvenance>,
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(deny_unknown_fields)]
226pub struct Contrast {
227    pub arm: Arm,
228    pub metric: String,
229    pub n: usize,
230    pub median_delta: f64,
231    pub ci_low: f64,
232    pub ci_high: f64,
233}
234
235#[derive(Debug, Clone, Serialize, Deserialize)]
236#[serde(deny_unknown_fields)]
237pub struct ArmStudyReport {
238    pub schema_version: u32,
239    pub kind: String,
240    pub study_id: String,
241    pub protocol_sha256: String,
242    pub tasks: usize,
243    pub powered: bool,
244    pub p95_rule: String,
245    pub acl_version_by_task: BTreeMap<String, String>,
246    pub arms: Vec<ArmSummary>,
247    pub contrasts: Vec<Contrast>,
248}
249
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub enum Refusal {
252    Parse,
253    /// An input is larger than this analysis admits; `what` names the bound.
254    Budget {
255        what: &'static str,
256    },
257    ProtocolSchema,
258    ObservationSchema,
259    TaskCount,
260    TaskId {
261        task: String,
262    },
263    TaskDigest {
264        task: String,
265    },
266    Bootstrap,
267    ProtocolBinding,
268    UnknownTask {
269        task: String,
270        arm: Arm,
271    },
272    Duplicate {
273        task: String,
274        arm: Arm,
275    },
276    Missing {
277        task: String,
278        arm: Arm,
279    },
280    Acl {
281        task: String,
282        arm: Arm,
283    },
284    Model {
285        task: String,
286        arm: Arm,
287    },
288    Blind {
289        task: String,
290        arm: Arm,
291    },
292    Correctness {
293        task: String,
294        arm: Arm,
295    },
296    Evidence {
297        task: String,
298        arm: Arm,
299    },
300    Sync {
301        task: String,
302        arm: Arm,
303    },
304    Provider {
305        task: String,
306        arm: Arm,
307        what: &'static str,
308    },
309}
310
311impl fmt::Display for Refusal {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        // Only rule identity and the affected task/arm, never a measured value.
314        write!(f, "{self:?}")
315    }
316}
317
318impl std::error::Error for Refusal {}
319
320fn provider_refusal(task: &str, arm: Arm, what: &'static str) -> Refusal {
321    Refusal::Provider {
322        task: task.into(),
323        arm,
324        what,
325    }
326}
327
328fn exchange_is_valid(exchange: &ProviderExchange) -> bool {
329    bare_digest_is_valid(&exchange.request_body_sha256)
330        && bare_digest_is_valid(&exchange.response_body_sha256)
331        && exchange
332            .usage
333            .as_ref()
334            .is_none_or(super::model::ProviderUsage::is_well_formed)
335}
336
337/// Pure handoff for an explicit producer: select one existing report's task and
338/// A/B condition, then serialize the result in an observation. The CLI can load
339/// an optional explicit A/B file; it never discovers one. `arm` is a caller declaration, not
340/// something the A/B report proves; copied metadata remains operator supplied.
341pub fn resolve_provider_observation(
342    report: &AbReport,
343    task_id: &str,
344    arm: Arm,
345    condition: ProviderCondition,
346) -> Result<ProviderObservation, Refusal> {
347    if report.records.len() > MAX_TASKS || report.provider_exchanges.len() > MAX_TASKS {
348        return Err(Refusal::Budget {
349            what: "provider report tasks",
350        });
351    }
352    if report.kind != super::report::REPORT_KIND
353        || report.schema_version != super::report::REPORT_SCHEMA_VERSION
354    {
355        return Err(provider_refusal(task_id, arm, "report schema"));
356    }
357    let mut records = report
358        .records
359        .iter()
360        .filter(|record| record.task_id == task_id);
361    if records.next().is_none() || records.next().is_some() {
362        return Err(provider_refusal(task_id, arm, "unique task record"));
363    }
364    let mut exchanges = report
365        .provider_exchanges
366        .iter()
367        .filter(|entry| entry.task_id == task_id);
368    let entry = exchanges
369        .next()
370        .ok_or_else(|| provider_refusal(task_id, arm, "unique task exchange"))?;
371    if exchanges.next().is_some() {
372        return Err(provider_refusal(task_id, arm, "unique task exchange"));
373    }
374    let exchange = match condition {
375        ProviderCondition::Baseline => entry.baseline.as_ref(),
376        ProviderCondition::LeanCtx => entry.lean_ctx.as_ref(),
377    }
378    .ok_or_else(|| provider_refusal(task_id, arm, "selected condition"))?;
379    if !exchange_is_valid(exchange) {
380        return Err(provider_refusal(task_id, arm, "exchange evidence"));
381    }
382    Ok(ProviderObservation {
383        task_id: task_id.into(),
384        arm,
385        condition,
386        model_fingerprint: report.model.digest(),
387        exchange: exchange.clone(),
388    })
389}
390
391fn validate_provider_observation(row: &Observation) -> Result<(), Refusal> {
392    let Some(provider) = &row.provider_observation else {
393        return Ok(());
394    };
395    if provider.task_id != row.task_id
396        || provider.arm != row.arm
397        || provider.model_fingerprint != row.model_fingerprint
398        || !bare_digest_is_valid(&provider.model_fingerprint)
399        || !exchange_is_valid(&provider.exchange)
400    {
401        return Err(provider_refusal(&row.task_id, row.arm, "row binding"));
402    }
403    let usage = provider.exchange.usage.as_ref();
404    if usage
405        .and_then(|u| u.input_tokens)
406        .is_some_and(|n| n != row.tokens_input)
407        || usage
408            .and_then(|u| u.output_tokens)
409            .is_some_and(|n| n != row.tokens_output)
410        || usage.and_then(|u| u.cached_input_tokens) != row.provider_cache_read_tokens
411    {
412        return Err(provider_refusal(&row.task_id, row.arm, "reported counters"));
413    }
414    Ok(())
415}
416
417fn provider_provenance(rows: &[&Observation]) -> Option<ProviderProvenance> {
418    if rows.iter().all(|row| row.provider_observation.is_none()) {
419        return None;
420    }
421    let mut counts = ProviderProvenance::default();
422    for row in rows {
423        match row.provider_observation.as_ref().map(|p| &p.exchange) {
424            None => counts.unattributed += 1,
425            Some(exchange) if exchange.origin == ObservationOrigin::Replayed => {
426                counts.replayed += 1;
427            }
428            Some(exchange)
429                if exchange.usage.as_ref().is_some_and(|usage| {
430                    usage.input_tokens.is_some() && usage.output_tokens.is_some()
431                }) =>
432            {
433                counts.current_reported += 1;
434            }
435            Some(_) => counts.observed_partial += 1,
436        }
437    }
438    Some(counts)
439}
440
441/// An explicitly supplied raw report or signed v1 artifact. The selected type
442/// decodes the ORIGINAL bytes, retaining known-field duplicate rejection. ROOT
443/// checks are closed; unconsumed historical nesting keeps its existing tolerance.
444pub fn parse_provider_report(bytes: &[u8]) -> Result<AbReport, Refusal> {
445    if bytes.len() > MAX_PROVIDER_REPORT_BYTES {
446        return Err(Refusal::Budget {
447            what: "provider report bytes",
448        });
449    }
450    let root: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| Refusal::Parse)?;
451    let object = root.as_object().ok_or(Refusal::Parse)?;
452    match object.get("kind").and_then(serde_json::Value::as_str) {
453        Some(super::report::REPORT_KIND) => {
454            let report: AbReport = serde_json::from_slice(bytes).map_err(|_| Refusal::Parse)?;
455            validate_provider_report_shape(&report, &root)?;
456            Ok(report)
457        }
458        Some("lean-ctx.eval-ab-artifact") => {
459            let artifact: super::artifact::SignedAbReportV1 =
460                serde_json::from_slice(bytes).map_err(|_| Refusal::Parse)?;
461            if object.keys().any(|key| {
462                !matches!(
463                    key.as_str(),
464                    "schema_version"
465                        | "kind"
466                        | "created_at"
467                        | "lean_ctx_version"
468                        | "agent_id"
469                        | "determinism_digest"
470                        | "verdict"
471                        | "report"
472                        | "signer_public_key"
473                        | "signature"
474                )
475            }) {
476                return Err(Refusal::Parse);
477            }
478            if artifact.schema_version != 1 || artifact.kind != "lean-ctx.eval-ab-artifact" {
479                return Err(provider_refusal("", Arm::UnchangedAgent, "artifact schema"));
480            }
481            validate_provider_report_shape(
482                &artifact.report,
483                object.get("report").ok_or(Refusal::Parse)?,
484            )?;
485            // Announced-key integrity/internal consistency only: this is not
486            // enrolled identity, provider/model use or study authentication.
487            // Verification covers canonical typed fields, not every raw byte or
488            // ignored historical nested field; known exchanges are included.
489            if artifact.verdict != artifact.report.verdict || !artifact.verify().ok() {
490                return Err(provider_refusal(
491                    "",
492                    Arm::UnchangedAgent,
493                    "artifact integrity",
494                ));
495            }
496            Ok(artifact.report)
497        }
498        _ => Err(provider_refusal("", Arm::UnchangedAgent, "report kind")),
499    }
500}
501
502fn validate_provider_report_shape(
503    report: &AbReport,
504    root: &serde_json::Value,
505) -> Result<(), Refusal> {
506    let object = root.as_object().ok_or(Refusal::Parse)?;
507    if object.keys().any(|key| {
508        !matches!(
509            key.as_str(),
510            "schema_version"
511                | "kind"
512                | "created_at"
513                | "lean_ctx_version"
514                | "suite"
515                | "budget_tokens"
516                | "model"
517                | "records"
518                | "stats"
519                | "verdict"
520                | "evidence_tier"
521                | "power"
522                | "provider_exchanges"
523        )
524    }) {
525        return Err(Refusal::Parse);
526    }
527    if report.kind != super::report::REPORT_KIND
528        || report.schema_version != super::report::REPORT_SCHEMA_VERSION
529    {
530        return Err(provider_refusal("", Arm::UnchangedAgent, "report schema"));
531    }
532    if report.records.len() > MAX_TASKS || report.provider_exchanges.len() > MAX_TASKS {
533        return Err(Refusal::Budget {
534            what: "provider report tasks",
535        });
536    }
537    Ok(())
538}
539
540/// Attach operator-declared provenance to one arm only. Every pending row is
541/// resolved and checked before any input is changed; an error leaves it intact.
542pub fn attach_provider_observations(
543    observations: &mut Observations,
544    report: &AbReport,
545    arm: Arm,
546    condition: ProviderCondition,
547) -> Result<(), Refusal> {
548    if observations.observations.len() > ALL.len() * MAX_TASKS {
549        return Err(Refusal::Budget {
550            what: "observation rows",
551        });
552    }
553    if report.records.len() > MAX_TASKS || report.provider_exchanges.len() > MAX_TASKS {
554        return Err(Refusal::Budget {
555            what: "provider report tasks",
556        });
557    }
558    let mut seen = std::collections::BTreeSet::new();
559    let mut pending = Vec::new();
560    for (index, row) in observations.observations.iter().enumerate() {
561        if row.arm != arm {
562            continue;
563        }
564        if !seen.insert(row.task_id.as_str()) {
565            return Err(provider_refusal(&row.task_id, arm, "unique selected row"));
566        }
567        let resolved = resolve_provider_observation(report, &row.task_id, arm, condition)?;
568        if row
569            .provider_observation
570            .as_ref()
571            .is_some_and(|existing| existing != &resolved)
572        {
573            return Err(provider_refusal(&row.task_id, arm, "existing provenance"));
574        }
575        let mut checked = row.clone();
576        checked.provider_observation = Some(resolved.clone());
577        validate_provider_observation(&checked)?;
578        pending.push((index, resolved));
579    }
580    if pending.is_empty() {
581        return Err(provider_refusal("", arm, "selected arm rows"));
582    }
583    for (index, resolved) in pending {
584        observations.observations[index].provider_observation = Some(resolved);
585    }
586    Ok(())
587}
588
589pub fn parse_protocol(bytes: &[u8]) -> Result<(Protocol, String), Refusal> {
590    if bytes.len() > MAX_PROTOCOL_BYTES {
591        return Err(Refusal::Budget {
592            what: "protocol bytes",
593        });
594    }
595    let mut protocol: Protocol = serde_json::from_slice(bytes).map_err(|_| Refusal::Parse)?;
596    protocol.admit()?;
597    let digest = super::sha256_hex(bytes);
598    protocol.parsed_sha256 = Some(digest.clone());
599    Ok((protocol, digest))
600}
601
602pub fn parse_observations(bytes: &[u8]) -> Result<Observations, Refusal> {
603    if bytes.len() > MAX_OBSERVATIONS_BYTES {
604        return Err(Refusal::Budget {
605            what: "observations bytes",
606        });
607    }
608    serde_json::from_slice(bytes).map_err(|_| Refusal::Parse)
609}
610
611fn digest_is_valid(value: &str) -> bool {
612    value
613        .strip_prefix("sha256:")
614        .is_some_and(bare_digest_is_valid)
615}
616
617fn bare_digest_is_valid(hex: &str) -> bool {
618    hex.len() == 64
619        && hex
620            .bytes()
621            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
622}
623
624fn median(values: &mut [f64]) -> f64 {
625    values.sort_by(f64::total_cmp);
626    let mid = values.len() / 2;
627    if values.len().is_multiple_of(2) {
628        f64::midpoint(values[mid - 1], values[mid])
629    } else {
630        values[mid]
631    }
632}
633
634/// Nearest rank: the value at rank `ceil(0.95 × n)` (1-based) of the ascending
635/// values. `values` is never empty here: every arm has one row per task and a
636/// study has at least [`MIN_TASKS`].
637fn p95_nearest_rank(mut values: Vec<f64>) -> f64 {
638    values.sort_by(f64::total_cmp);
639    let rank = (values.len() * 95).div_ceil(100).max(1);
640    values[rank - 1]
641}
642
643fn summarize(mut values: Vec<f64>, protocol: &Protocol) -> MetricSummary {
644    let (ci_low, ci_high) = super::report::bootstrap_ci_with(
645        &values,
646        protocol.bootstrap_iters,
647        protocol.bootstrap_seed,
648        median,
649    );
650    MetricSummary {
651        n: values.len(),
652        median: median(&mut values),
653        ci_low,
654        ci_high,
655    }
656}
657
658const METRICS: [&str; 4] = ["correctness", "latency_ms", "tokens_input", "tokens_output"];
659
660fn metric(row: &Observation, index: usize) -> f64 {
661    match index {
662        0 => row.correctness,
663        1 => row.latency_ms as f64,
664        2 => row.tokens_input as f64,
665        _ => row.tokens_output as f64,
666    }
667}
668
669pub fn analyze(
670    protocol: &Protocol,
671    protocol_sha256: &str,
672    observations: &Observations,
673) -> Result<ArmStudyReport, Refusal> {
674    // Resources first, from read-only facts of the inputs: a protocol that did
675    // not come through `parse_protocol` is bounded here all the same, and no row
676    // is looked at before the rows are known to be at most four per task.
677    protocol.admit()?;
678    if observations.observations.len() > protocol.tasks.len().saturating_mul(ALL.len()) {
679        return Err(Refusal::Budget {
680            what: "observation rows",
681        });
682    }
683    if protocol.schema_version != SCHEMA_VERSION || protocol.kind != PROTOCOL_KIND {
684        return Err(Refusal::ProtocolSchema);
685    }
686    if observations.schema_version != SCHEMA_VERSION || observations.kind != OBSERVATIONS_KIND {
687        return Err(Refusal::ObservationSchema);
688    }
689    if protocol.tasks.len() < MIN_TASKS {
690        return Err(Refusal::TaskCount);
691    }
692    let mut tasks = BTreeMap::new();
693    for task in &protocol.tasks {
694        if tasks.insert(task.task_id.as_str(), task).is_some() {
695            return Err(Refusal::TaskId {
696                task: task.task_id.clone(),
697            });
698        }
699        if !digest_is_valid(&task.statement_sha256) || !digest_is_valid(&task.rubric_sha256) {
700            return Err(Refusal::TaskDigest {
701                task: task.task_id.clone(),
702            });
703        }
704    }
705    if protocol.bootstrap_iters == 0 {
706        return Err(Refusal::Bootstrap);
707    }
708    if protocol.parsed_sha256.as_deref() != Some(protocol_sha256)
709        || observations.protocol_sha256 != protocol_sha256
710    {
711        return Err(Refusal::ProtocolBinding);
712    }
713    let mut rows = BTreeMap::new();
714    for row in &observations.observations {
715        let task = row.task_id.clone();
716        let arm = row.arm;
717        if !tasks.contains_key(row.task_id.as_str()) {
718            return Err(Refusal::UnknownTask { task, arm });
719        }
720        if rows.insert((row.task_id.as_str(), arm), row).is_some() {
721            return Err(Refusal::Duplicate { task, arm });
722        }
723        if !row.rated_blind {
724            return Err(Refusal::Blind { task, arm });
725        }
726        if !row.correctness.is_finite() || !(0.0..=1.0).contains(&row.correctness) {
727            return Err(Refusal::Correctness { task, arm });
728        }
729        if row.evidence_receipts.is_empty()
730            || row.evidence_receipts.len() > MAX_EVIDENCE_RECEIPTS
731            || !row.evidence_receipts.iter().all(|s| digest_is_valid(s))
732        {
733            return Err(Refusal::Evidence { task, arm });
734        }
735        if row.sync_bytes.is_some() != matches!(arm, Arm::Team | Arm::Company) {
736            return Err(Refusal::Sync { task, arm });
737        }
738        validate_provider_observation(row)?;
739    }
740    let mut acl_version_by_task = BTreeMap::new();
741    for &task in tasks.keys() {
742        let mut first: Option<&Observation> = None;
743        for arm in ALL {
744            let row = rows.get(&(task, arm)).ok_or_else(|| Refusal::Missing {
745                task: task.into(),
746                arm,
747            })?;
748            if row.model_fingerprint.is_empty()
749                || first.is_some_and(|base| base.model_fingerprint != row.model_fingerprint)
750            {
751                return Err(Refusal::Model {
752                    task: task.into(),
753                    arm,
754                });
755            }
756            if first.is_some_and(|base| base.acl_version != row.acl_version) {
757                return Err(Refusal::Acl {
758                    task: task.into(),
759                    arm,
760                });
761            }
762            first = Some(row);
763        }
764        // All four rows are present, so this lookup is proven above.
765        acl_version_by_task.insert(
766            task.into(),
767            rows[&(task, Arm::UnchangedAgent)].acl_version.clone(),
768        );
769    }
770    let mut arms = Vec::new();
771    let mut contrasts = Vec::new();
772    for arm in ALL {
773        let arm_rows: Vec<_> = tasks.keys().map(|&task| rows[&(task, arm)]).collect();
774        let values =
775            |index| -> Vec<f64> { arm_rows.iter().map(|row| metric(row, index)).collect() };
776        let nullable = |select: fn(&Observation) -> Option<u64>| {
777            arm_rows
778                .iter()
779                .map(|row| select(row).map(|v| v as f64))
780                .collect::<Option<Vec<_>>>()
781                .map(|values| summarize(values, protocol))
782        };
783        arms.push(ArmSummary {
784            arm,
785            correctness: summarize(values(0), protocol),
786            latency_ms: summarize(values(1), protocol),
787            latency_ms_p95: p95_nearest_rank(values(1)),
788            tokens_input: summarize(values(2), protocol),
789            tokens_output: summarize(values(3), protocol),
790            provider_cache_read_tokens: nullable(|row| row.provider_cache_read_tokens),
791            sync_bytes: nullable(|row| row.sync_bytes),
792            provider_provenance: provider_provenance(&arm_rows),
793        });
794        if arm != Arm::UnchangedAgent {
795            for (index, name) in METRICS.iter().enumerate() {
796                let deltas = tasks
797                    .keys()
798                    .map(|&task| {
799                        metric(rows[&(task, arm)], index)
800                            - metric(rows[&(task, Arm::UnchangedAgent)], index)
801                    })
802                    .collect();
803                let summary = summarize(deltas, protocol);
804                contrasts.push(Contrast {
805                    arm,
806                    metric: (*name).into(),
807                    n: summary.n,
808                    median_delta: summary.median,
809                    ci_low: summary.ci_low,
810                    ci_high: summary.ci_high,
811                });
812            }
813        }
814    }
815    Ok(ArmStudyReport {
816        schema_version: SCHEMA_VERSION,
817        kind: REPORT_KIND.into(),
818        study_id: protocol.study_id.clone(),
819        protocol_sha256: protocol_sha256.into(),
820        tasks: tasks.len(),
821        powered: tasks.len() >= super::report::MIN_POWERED_PAIRS,
822        p95_rule: P95_RULE.into(),
823        acl_version_by_task,
824        arms,
825        contrasts,
826    })
827}
828
829impl ArmStudyReport {
830    pub fn to_json(&self) -> String {
831        serde_json::to_string(self).unwrap_or_default()
832    }
833
834    pub fn render(&self) -> String {
835        use std::fmt::Write;
836        let mut out = format!(
837            "{} tasks, powered: {}\n",
838            self.tasks,
839            if self.powered { "yes" } else { "no" }
840        );
841        out.push_str("arm metric n median ci_low ci_high\n");
842        for arm in &self.arms {
843            for (name, summary) in [
844                ("correctness", Some(&arm.correctness)),
845                ("latency_ms", Some(&arm.latency_ms)),
846                ("tokens_input", Some(&arm.tokens_input)),
847                ("tokens_output", Some(&arm.tokens_output)),
848                (
849                    "provider_cache_read_tokens",
850                    arm.provider_cache_read_tokens.as_ref(),
851                ),
852                ("sync_bytes", arm.sync_bytes.as_ref()),
853            ] {
854                if let Some(s) = summary {
855                    let _ = writeln!(
856                        out,
857                        "{} {} {} {} {} {}",
858                        arm.arm.label(),
859                        name,
860                        s.n,
861                        s.median,
862                        s.ci_low,
863                        s.ci_high
864                    );
865                }
866            }
867        }
868        let _ = writeln!(out, "arm latency_ms_p95 ({})", self.p95_rule);
869        for arm in &self.arms {
870            let _ = writeln!(out, "{} {}", arm.arm.label(), arm.latency_ms_p95);
871        }
872        if self
873            .arms
874            .iter()
875            .any(|arm| arm.provider_provenance.is_some())
876        {
877            out.push_str(
878                "Metrics are externally supplied; provenance is declared local metadata, not authenticated.\n\
879                 Provider counts have no claim of subset power; study power is for all tasks.\n\
880                 arm provider_provenance current_reported replayed observed_partial unattributed\n",
881            );
882            for arm in &self.arms {
883                if let Some(p) = &arm.provider_provenance {
884                    let _ = writeln!(
885                        out,
886                        "{} provider_provenance {} {} {} {}",
887                        arm.arm.label(),
888                        p.current_reported,
889                        p.replayed,
890                        p.observed_partial,
891                        p.unattributed
892                    );
893                }
894            }
895        }
896        out.push_str("arm metric n median_delta ci_low ci_high\n");
897        for c in &self.contrasts {
898            let _ = writeln!(
899                out,
900                "{} {} {} {} {} {}",
901                c.arm.label(),
902                c.metric,
903                c.n,
904                c.median_delta,
905                c.ci_low,
906                c.ci_high
907            );
908        }
909        out
910    }
911}
912
913#[cfg(test)]
914#[path = "arm_study_tests.rs"]
915mod tests;