Skip to main content

vela_protocol/analysis/
independence.rs

1//! Independence as a DERIVED predicate — never a stored or asserted flag.
2//!
3//! Two evaluations are not independent because two names appear. They may
4//! share a model, a prompt template, code, data, a parent run, or one
5//! binary compiled twice. This module owns the two derivations:
6//!
7//! - [`independence_from_attachments`] — the gate's judgment over matched
8//!   verifier attachments (the G1 clause plus the monoculture demotion,
9//!   lifted verbatim from `derive_gate_status`, which now calls it);
10//! - [`independence_from_receipt`] — the landing-time judgment over a
11//!   receipt's verifier runs, its declared `independence_basis`, and its
12//!   lineage layer, feeding `PolicyContext.independence_satisfied`.
13//!
14//! Both are fail-closed and monotonic: missing lineage never counts as
15//! diversity, a declared coupling defeats independence, and the outcome
16//! can only refuse — it never upgrades anything a stricter check refused.
17//! The receipt-side predicate reads producer-DECLARED inputs, so it is a
18//! policy lever (what the signed policy may auto-admit), never gate truth:
19//! the gate's independence stays derived from attachments.
20
21use serde::{Deserialize, Serialize};
22
23use super::verifier_attachment::VerifierAttachment;
24use crate::objects::receipt_v1::{IndependenceBasis, ReceiptLineage};
25
26/// The derived judgment. Mirrors `GateOutcome`: satisfied iff `reasons`
27/// is empty, so every refusal is inspectable.
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct IndependenceOutcome {
30    pub satisfied: bool,
31    pub reasons: Vec<String>,
32}
33
34impl IndependenceOutcome {
35    fn from_reasons(reasons: Vec<String>) -> Self {
36        IndependenceOutcome {
37            satisfied: reasons.is_empty(),
38            reasons,
39        }
40    }
41}
42
43/// Attachment-level independence: the G1 clause plus the monoculture
44/// demotion, as one pure function of `(claim_digest, attachments)`.
45/// Extracted from `derive_gate_status` (which calls this); the reason
46/// strings are unchanged so existing vectors and callers see identical
47/// judgments.
48#[must_use]
49pub fn independence_from_attachments(
50    current_claim_digest: &str,
51    attachments: &[VerifierAttachment],
52) -> IndependenceOutcome {
53    let matched: Vec<&VerifierAttachment> = attachments
54        .iter()
55        .filter(|a| a.is_passing_match(current_claim_digest))
56        .collect();
57    let mut reasons = Vec::new();
58
59    // Monoculture observation: when the matched set agrees but every run
60    // names the SAME implementation, say so — N runs of one binary are
61    // replication, not implementation diversity.
62    let impls: std::collections::HashSet<&str> = matched
63        .iter()
64        .map(|a| a.implementation_id.as_str())
65        .filter(|s| !s.is_empty())
66        .collect();
67    if matched.len() >= 2 && impls.len() == 1 {
68        reasons.push(format!(
69            "monoculture: {} matched run(s) all from implementation '{}' — independent implementations would strengthen this",
70            matched.len(),
71            impls.iter().next().unwrap()
72        ));
73    }
74
75    // G1-L: matched attachments sharing a declared lineage coupling tag
76    // (`model:` / `code:` / `data:` / `run:`) are one failure domain
77    // regardless of method/solver diversity. Producer-declared, so a
78    // missing declaration is invisible here — G1's positive requirements
79    // below remain the floor.
80    let mut tag_owners: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
81    for a in &matched {
82        let unique: std::collections::BTreeSet<&str> =
83            a.lineage_couplings.iter().map(String::as_str).collect();
84        for t in unique {
85            *tag_owners.entry(t).or_insert(0) += 1;
86        }
87    }
88    let shared: Vec<&str> = tag_owners
89        .iter()
90        .filter(|(_, n)| **n >= 2)
91        .map(|(t, _)| *t)
92        .collect();
93    if !shared.is_empty() {
94        reasons.push(format!(
95            "G1-L: matched attachments share failure domain [{}]",
96            shared.join(", ")
97        ));
98    }
99
100    // G1 independence: >=2 matched attachments by different method/solver,
101    // with at least one declaring independence (one-directional; mutual is a
102    // hash circularity over the content-addressed id).
103    if matched.len() < 2 {
104        reasons.push(format!(
105            "G1: need >=2 matched independent attachments, have {}",
106            matched.len()
107        ));
108    } else {
109        let distinct_methods: std::collections::BTreeSet<_> = matched
110            .iter()
111            .map(|a| (a.verifier_method, a.solver_id.as_str()))
112            .collect();
113        if distinct_methods.len() < 2 {
114            reasons.push(
115                "G1: >=2 attachments but all share one method/solver (not independent)".to_string(),
116            );
117        } else {
118            let ids: std::collections::BTreeSet<&str> =
119                matched.iter().map(|a| a.id.as_str()).collect();
120            let declares_independence = matched.iter().any(|a| {
121                a.independent_of
122                    .iter()
123                    .any(|other| other != &a.id && ids.contains(other.as_str()))
124            });
125            if !declares_independence {
126                reasons.push(
127                    "G1: attachments do not declare independence (independent_of)".to_string(),
128                );
129            }
130        }
131    }
132
133    IndependenceOutcome::from_reasons(reasons)
134}
135
136/// A borrowed view of one receipt verifier run — the three fields the
137/// predicate reads. `vela-cli`'s landing type maps into this so the
138/// derivation lives here, below every caller.
139#[derive(Debug, Clone, Copy)]
140pub struct ReceiptRunView<'a> {
141    pub method: &'a str,
142    pub solver: &'a str,
143    pub outcome: &'a str,
144}
145
146/// Receipt-level independence, derived from what the receipt actually
147/// carries. Fail-closed rules, each with an inspectable reason:
148///
149/// 1. fewer than two passing verifier runs — nothing to be independent;
150/// 2. all passing runs share one `(method, solver)` — one failure domain;
151/// 3. no `independence_basis` declared — missing lineage is not diversity;
152/// 4. `known_couplings` non-empty — a declared coupling defeats the claim;
153/// 5. no `declared_independent_of` — the declaration requirement, the
154///    receipt-side mirror of G1's `independent_of`;
155/// 6. the receipt declares independence from its own lineage parent — a
156///    self-contradiction lineage makes visible.
157#[must_use]
158pub fn independence_from_receipt(
159    runs: &[ReceiptRunView<'_>],
160    basis: Option<&IndependenceBasis>,
161    lineage: Option<&ReceiptLineage>,
162) -> IndependenceOutcome {
163    let mut reasons = Vec::new();
164
165    let passing: Vec<&ReceiptRunView> = runs
166        .iter()
167        .filter(|r| r.outcome.eq_ignore_ascii_case("pass"))
168        .collect();
169    if passing.len() < 2 {
170        reasons.push(format!(
171            "need >=2 passing verifier runs, have {}",
172            passing.len()
173        ));
174    } else {
175        let distinct: std::collections::BTreeSet<(&str, &str)> =
176            passing.iter().map(|r| (r.method, r.solver)).collect();
177        if distinct.len() < 2 {
178            reasons
179                .push("all passing runs share one method/solver (one failure domain)".to_string());
180        }
181    }
182
183    match basis {
184        None => {
185            reasons.push(
186                "no independence_basis declared (missing lineage never counts as diversity)"
187                    .to_string(),
188            );
189        }
190        Some(b) => {
191            if !b.known_couplings.is_empty() {
192                reasons.push(format!(
193                    "declared couplings defeat independence: [{}]",
194                    b.known_couplings.join(", ")
195                ));
196            }
197            if b.declared_independent_of.is_empty() {
198                reasons.push(
199                    "no declared_independent_of (independence must be declared, not implied)"
200                        .to_string(),
201                );
202            } else if let Some(lin) = lineage {
203                let contradiction: Vec<&str> = b
204                    .declared_independent_of
205                    .iter()
206                    .filter(|d| lin.parents.contains(d) || lin.derived_from.contains(d))
207                    .map(String::as_str)
208                    .collect();
209                if !contradiction.is_empty() {
210                    reasons.push(format!(
211                        "declares independence from its own lineage parent(s): [{}]",
212                        contradiction.join(", ")
213                    ));
214                }
215            }
216        }
217    }
218
219    IndependenceOutcome::from_reasons(reasons)
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    fn run<'a>(method: &'a str, solver: &'a str, outcome: &'a str) -> ReceiptRunView<'a> {
227        ReceiptRunView {
228            method,
229            solver,
230            outcome,
231        }
232    }
233
234    fn diverse_basis() -> IndependenceBasis {
235        IndependenceBasis {
236            method_family: "exact".to_string(),
237            declared_independent_of: vec!["vva_other".to_string()],
238            ..IndependenceBasis::default()
239        }
240    }
241
242    #[test]
243    fn bare_receipt_is_not_independent() {
244        let out = independence_from_receipt(&[], None, None);
245        assert!(!out.satisfied);
246        assert!(out.reasons.iter().any(|r| r.contains(">=2 passing")));
247        assert!(
248            out.reasons
249                .iter()
250                .any(|r| r.contains("no independence_basis"))
251        );
252    }
253
254    #[test]
255    fn one_failure_domain_is_not_independent() {
256        let runs = [
257            run("sidon_exact", "vela-verify", "pass"),
258            run("sidon_exact", "vela-verify", "pass"),
259        ];
260        let out = independence_from_receipt(&runs, Some(&diverse_basis()), None);
261        assert!(!out.satisfied);
262        assert!(out.reasons.iter().any(|r| r.contains("one failure domain")));
263    }
264
265    #[test]
266    fn declared_coupling_defeats_independence() {
267        let runs = [
268            run("sidon_exact", "vela-verify", "pass"),
269            run("sat", "kissat", "pass"),
270        ];
271        let mut basis = diverse_basis();
272        basis.known_couplings = vec!["model:claude-fable-5".to_string()];
273        let out = independence_from_receipt(&runs, Some(&basis), None);
274        assert!(!out.satisfied);
275        assert!(out.reasons.iter().any(|r| r.contains("couplings")));
276    }
277
278    #[test]
279    fn diverse_and_declared_is_independent() {
280        let runs = [
281            run("sidon_exact", "vela-verify", "pass"),
282            run("sat", "kissat", "pass"),
283        ];
284        let out = independence_from_receipt(&runs, Some(&diverse_basis()), None);
285        assert!(out.satisfied, "refused for: {:?}", out.reasons);
286    }
287
288    #[test]
289    fn independence_from_own_parent_is_a_contradiction() {
290        let runs = [
291            run("sidon_exact", "vela-verify", "pass"),
292            run("sat", "kissat", "pass"),
293        ];
294        let lineage = ReceiptLineage {
295            parents: vec!["vva_other".to_string()],
296            ..ReceiptLineage::default()
297        };
298        let out = independence_from_receipt(&runs, Some(&diverse_basis()), Some(&lineage));
299        assert!(!out.satisfied);
300        assert!(out.reasons.iter().any(|r| r.contains("own lineage parent")));
301    }
302
303    #[test]
304    fn failing_runs_never_count() {
305        let runs = [
306            run("sidon_exact", "vela-verify", "pass"),
307            run("sat", "kissat", "fail"),
308        ];
309        let out = independence_from_receipt(&runs, Some(&diverse_basis()), None);
310        assert!(!out.satisfied);
311    }
312}