Skip to main content

provable_contracts/lint/
ggplot2_core_gate.rs

1//! PLOT-GG-001 (#6909) inside the `shapes` gate: the validator's half of `ggplot2-core`.
2//!
3//! The extractor ([`crate::ontology::extract::ggplot2_core::apply`]) writes every core row and a
4//! `plot:notProven` edge on each row without its four proofs. This module holds the gate to it:
5//!
6//! - **Positive control** — [`control`] runs the SAME `apply` over one bare planted row, then the declared
7//!   `ggplot2-core` shape over the result: exactly one violation, `maxCount` on `plot:notProven`, on the plant.
8//!   The **negative control** runs it over a fully evidenced row: no result at all. Either miss, or the shape not
9//!   declared while the corpus has core rows, is `not-fired` and the gate declines. Unlike `capability-cells` the
10//!   control does not require the shape ARMED: the shape is unarmed by policy until its sign-off, and the
11//!   control proves the shape can go RED, which arming does not change.
12//! - **Wiring** — [`wiring_holds`]: the nodes the shape flags on `plot:notProven` are exactly the nodes of the
13//!   rows the extractor counted as not proven, armed or not.
14
15use std::collections::{BTreeMap, BTreeSet};
16
17use crate::ontology::extract::ggplot2_core::{self, CoreRow, Evidence, Ggplot2Stats};
18use crate::ontology::rdf::{iri, Graph};
19use crate::ontology::shapes::{self, NodeShape, Report, Severity};
20
21/// The shape's id, as contracts/trueno-viz/ggplot2-ontology-v1.yaml declares it.
22pub const SHAPE: &str = "ggplot2-core";
23
24/// The planted row's name: a `geom_` export no ggplot2 has.
25pub const PLANT_ROW: &str = "geom_ggplot2_core_plant";
26
27/// What `pv lint --gate shapes --format json` reports as `ggplot2_core`.
28#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
29pub struct Ggplot2CoreReport {
30    /// The pinned ggplot2 version.
31    pub ggplot2: Option<String>,
32    /// The core rows, sorted.
33    pub domain: Vec<String>,
34    /// How many `ggplot2-row` contracts are bound to a core row.
35    pub bound: usize,
36    /// Rows with all four proofs.
37    pub proven: Vec<String>,
38    /// Rows without them. Non-empty ⇒ the shape fails when armed.
39    pub not_proven: Vec<String>,
40}
41
42impl From<&Ggplot2Stats> for Ggplot2CoreReport {
43    fn from(s: &Ggplot2Stats) -> Self {
44        Self {
45            ggplot2: s.ggplot2.clone(),
46            domain: s.domain.iter().cloned().collect(),
47            bound: s.bound,
48            proven: s.proven.iter().cloned().collect(),
49            not_proven: s.not_proven.iter().cloned().collect(),
50        }
51    }
52}
53
54fn plant() -> CoreRow {
55    CoreRow {
56        row: 1,
57        name: PLANT_ROW.into(),
58        concept: "Geom".into(),
59        aes: vec!["x".into(), "y".into()],
60    }
61}
62
63fn evidenced(name: &str) -> Evidence {
64    let one = |v: &str| BTreeMap::from([(name.to_string(), v.to_string())]);
65    let many = |v: &str| BTreeMap::from([(name.to_string(), vec![v.to_string()])]);
66    Evidence {
67        contracts: one("plant-contract"),
68        fixtures: many("plant/expected.json"),
69        surface: one("plant/surface.json"),
70        receipts: many("plant/receipt.json"),
71    }
72}
73
74fn run(shape: &NodeShape, version: &str, ev: &Evidence) -> Report {
75    let mut g = Graph::new();
76    ggplot2_core::apply(&mut g, version, &[plant()], ev);
77    shapes::validate(&g, std::slice::from_ref(shape))
78}
79
80fn plant_fires(shapes: &[NodeShape], version: Option<&str>) -> bool {
81    let (Some(shape), Some(version)) = (shapes.iter().find(|s| s.id == SHAPE), version) else {
82        return false;
83    };
84    let bare = run(shape, version, &Evidence::default());
85    let refused = !bare.results.is_empty()
86        && bare.results.iter().all(|r| {
87            r.severity == Severity::Violation
88                && r.focus == iri("plot", PLANT_ROW)
89                && r.component == "maxCount"
90                && r.path.as_deref() == Some(ggplot2_core::plot("notProven").as_str())
91        });
92    refused
93        && run(shape, version, &evidenced(PLANT_ROW))
94            .results
95            .is_empty()
96}
97
98/// Is the `ggplot2-core` shape among the shapes this run grades?
99#[must_use]
100pub fn declared(shapes: &[NodeShape]) -> bool {
101    shapes.iter().any(|s| s.id == SHAPE)
102}
103
104/// `pc_shapes["ggplot2-core"]`, or `None` when the shape is not graded and either no core row exists or the run
105/// is scoped (`--shape`) to another family, which grades no core row.
106#[must_use]
107pub fn control(shapes: &[NodeShape], stats: &Ggplot2Stats, scoped: bool) -> Option<String> {
108    if !declared(shapes) && (scoped || stats.domain.is_empty()) {
109        return None;
110    }
111    let fired = plant_fires(shapes, stats.ggplot2.as_deref());
112    Some(if fired { "fired" } else { "not-fired" }.to_string())
113}
114
115/// The nodes the shape flagged on `plot:notProven` equal the nodes of the rows counted not proven. Only
116/// meaningful when the shape is graded ([`declared`]).
117#[must_use]
118pub fn wiring_holds(report: &Report, stats: &Ggplot2Stats) -> bool {
119    let p = ggplot2_core::plot("notProven");
120    let flagged: BTreeSet<&str> = report
121        .results
122        .iter()
123        .filter(|r| r.shape == SHAPE && r.path.as_deref() == Some(p.as_str()))
124        .map(|r| r.focus.as_str())
125        .collect();
126    let owning: BTreeSet<String> = stats.not_proven.iter().map(|n| iri("plot", n)).collect();
127    flagged == owning.iter().map(String::as_str).collect()
128}
129
130#[cfg(test)]
131#[path = "ggplot2_core_gate_tests.rs"]
132mod tests;