Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat(causal/v0.5): wire PyWhy backdoor identification into certify_action (#51)

Fabio Rovai9ba1c885a525
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bdac7d93..6c5e52eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
### Added
+- **Causal (v0.5): `certify_action` × PyWhy integration.** Wires the #48 PyWhy scaffold into the live `certify_action` path. New `ActionFrame.identification_mode` field (`Structural` | `DoCalculusBackdoor`, default `Structural` for back-compat) selects which identifiability proof to attempt. New helper `build_causal_dag(graph, target_iris)` extracts a causal DAG from the loaded RDF graph: nodes = target IRIs + their one-hop structural neighbours (same slice CIVeX already hashes); edges = `rdfs:subClassOf` / `rdfs:subPropertyOf` / `rdfs:domain` / `rdfs:range` triples among slice members (treated as cause → effect); plus a synthetic `__utility__` sink downstream of every node. When `DoCalculusBackdoor` is requested AND the `causal-pywhy` Cargo feature is enabled, the verifier calls `civex_pywhy::run_pywhy_backdoor` and on success stamps the certificate's `identification_proof` with DoWhy's adjustment estimand + tags assumptions with `"do_calculus_backdoor"`. On any failure path (Python unavailable / DoWhy unavailable / DoWhy runtime error / target unidentifiable) the verifier **silently falls back to the structural proxy** and records the reason in assumptions as `"do_calculus_unavailable:<kind>"`. When the feature is off, the marker is `"do_calculus_unavailable:feature_disabled"`. The certificate's `identification_proof` field is never empty regardless of branch taken. MCP tool `onto_certify_action` gains `identification_mode: Option<String>` accepting `"structural"` (default) or `"do_calculus_backdoor"`. Two new integration tests in `tests/civex_test.rs`: `structural_mode_records_structural_only_assumption` (back-compat) and `do_calculus_mode_falls_back_to_structural_when_feature_disabled` (verifies the fallback path doesn't crash and records the marker). All 9 civex integration tests pass in both default and `causal-pywhy` build configurations; clippy clean across `--lib --tests --examples` in both configs.
- **Causal: PyWhy/DoWhy backdoor identification subprocess scaffold (#48).** Scaffolds the Causal flagship's substantive v0.5 work without pulling Python into the default build. New optional Cargo feature `causal-pywhy` (off by default) enables a `src/civex_pywhy.rs` module that wraps DoWhy v0.13 as a subprocess — same pattern as `src/plan_classical.rs` does for Fast Downward. The wrapper embeds a self-contained Python driver (`PYWHY_PYTHON_DRIVER`) that reads `{nodes, edges, treatment, outcome}` from stdin, builds a `networkx` DiGraph, runs DoWhy's `identify_effect` for backdoor adjustment, and emits `{identifiable, adjustment_set, estimand_expression}` to stdout. Per the May 2026 roadmap memo: **Pearl–Shpitser ID is not ported to Rust** — DoWhy is a 15-year-stable Python implementation, so we wrap it. Honest behaviour when Python or DoWhy is missing: structured errors with `kind = "python_unavailable"` / `"pywhy_unavailable"` / `"dowhy_runtime_failed"` that the caller (eventually `certify_action` in v0.5) dispatches on to fall back to the structural proxy. Binary resolution order: explicit `python_override` → `PYTHON_BIN` env var → `python3` on PATH. **NOT yet integrated into `certify_action`** — the structural proxy (`"structural_only"` assumption) remains the only identifier in shipped certificates; integration tracks as the v0.5 ship. 9 unit tests cover parser cases (identifiable, unidentifiable, both error kinds, invalid JSON), python resolver (override + default + env var), embedded-driver sanity check, and `python_unavailable` behaviour on missing binary. Zero additional Rust dependencies — the entire feature is embedded Python + subprocess plumbing.
- **Dynamics: non-deterministic outcomes for ActionSchema (#49).** `ActionSchema` gains an additive `outcomes: Vec<Outcome>` field. Each `Outcome` carries a categorical `probability` in `[0, 1]`, its own `effects: Vec<EffectSpec>` list, and an optional human-readable `label` (e.g. `"success"` / `"degraded"` / `"failure"`). When `outcomes` is non-empty, `apply()` samples one outcome and executes its effects; the deterministic `effects` field is ignored. When empty (the default), the schema behaves exactly as before — full back-compat with v0.4 base. Probabilities are validated: the sum must equal `1.0 ± 1e-6` or `apply()` returns an error; negative probabilities are also rejected. Sampling uses an inline xorshift64 PRNG keyed by a seed — **zero new dependencies**, no `rand`/`fastrand` pulled in. New method `ActionSchema::apply_with_seed(graph, db, bindings, seed)` exposes the seed for reproducible sampling; the default `apply()` derives a seed from `SystemTime::now()`. `ApplyResult` gains `sampled_outcome: Option<usize>` and `sampled_outcome_label: Option<String>` so callers can see which branch fired. `onto_action_apply` gains an optional `seed: Option<u64>` parameter — pass it when you need reproducible runs (CIVeX certification, replay-from-audit-log, controlled experiments). Tests (4 new): `nondeterministic_apply_with_seed_is_reproducible`, `nondeterministic_apply_distribution_matches_probabilities` (1000-call smoke check that a 70/30 split lands within `[0.60, 0.80]`), `nondeterministic_apply_rejects_invalid_probability_sum`, `deterministic_schema_still_works_when_outcomes_is_empty` (back-compat).
- **Planner: `onto_plan_classical` — Fast Downward subprocess wrap (#50).** Optional convenience tool that completes the LLM-Modulo Planner pipeline (`compile_pddl` → `classical` → IRI-bind client-side → `validate`). Per the LLM-Modulo convention, the classical solver is still client-side — this wrapper exists so a caller who *does* have Fast Downward installed locally can ask the server to run it for them rather than shelling out themselves. Honest behaviour when Fast Downward is missing: returns a structured `binary_unavailable` error with installation guidance, never falls back to a silent stub. Binary resolution order: explicit `fast_downward_bin` parameter → `FAST_DOWNWARD_BIN` env var → `fast-downward.py` on PATH. Returns the raw `sas_plan` content (preserved verbatim) plus a parsed `operators: [{name, args}]` list and the `; cost = N (...)` footer extracted separately. Search strategy is configurable (default `"lama-first"`; pass `"astar(lmcut())"` etc.). Reads the highest-numbered `sas_plan.N` variant when satisficing search emits multiple plans. New module `src/plan_classical.rs` with 7 unit tests covering parse cases (three-operator plan with cost footer, blank-line + comment skipping, empty input, zero-arg operators) and resolver / error behaviour (explicit override, default fallback, `binary_unavailable` on missing binary). New MCP tool `onto_plan_classical` + `OntoPlanClassicalInput`.
diff --git a/examples/three_layer_pipeline.rs b/examples/three_layer_pipeline.rs
index b4aa2ee7..e02025a2 100644
--- a/examples/three_layer_pipeline.rs
+++ b/examples/three_layer_pipeline.rs
@@ -254,6 +254,7 @@ fn main() -> anyhow::Result<()> {
allow_experiment: false,
alpha: 0.05,
action_schema_name: Some(schema.name.clone()),
+ identification_mode: open_ontologies::civex::IdentificationMode::Structural,
};
let cert = certify_action(&db, &graph, &frame)?;
println!(
diff --git a/src/civex.rs b/src/civex.rs
index 1b4d3283..693bb766 100644
--- a/src/civex.rs
+++ b/src/civex.rs
@@ -104,6 +104,34 @@ pub struct ActionFrame {
/// trail explicit about which Dynamics action was gated.
#[serde(default)]
pub action_schema_name: Option<String>,
+ /// Identification mode (#48, v0.5). Defaults to [`IdentificationMode::Structural`]
+ /// for back-compat with v0.4 behaviour. When set to
+ /// [`IdentificationMode::DoCalculusBackdoor`] *and* the `causal-pywhy`
+ /// Cargo feature is enabled *and* the PyWhy subprocess succeeds, the
+ /// certificate's `identification_proof` and `assumptions` carry the
+ /// real backdoor-adjustment result. On any failure path
+ /// (python_unavailable / pywhy_unavailable / dowhy_runtime_failed) the
+ /// verifier silently falls back to the structural proxy and adds a
+ /// `do_calculus_unavailable:<reason>` marker to assumptions so the
+ /// audit trail is honest about what happened.
+ #[serde(default)]
+ pub identification_mode: IdentificationMode,
+}
+
+/// Which identifiability proof CIVeX should attempt. Set on
+/// [`ActionFrame::identification_mode`].
+#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum IdentificationMode {
+ /// v0.4 default: structural-dependency closure + bounded blast radius.
+ /// Always works; assumption recorded as `"structural_only"`.
+ #[default]
+ Structural,
+ /// v0.5 mode: invoke `civex_pywhy::run_pywhy_backdoor` on a DAG built
+ /// from the structural slice, ask DoWhy for a backdoor adjustment set.
+ /// Falls back to `Structural` on any failure (Python missing, DoWhy
+ /// missing, runtime error), with the reason recorded in assumptions.
+ DoCalculusBackdoor,
}
fn default_alpha() -> f64 {
@@ -239,7 +267,9 @@ pub fn certify_action(
// ── Step 6: triage ──────────────────────────────────────────────────────
let mut rationale_parts: Vec<String> = Vec::new();
- let mut assumptions: Vec<String> = vec!["structural_only".to_string()];
+ // The identification assumption is appended by `derive_identification_proof`
+ // below; start the list with only the reversibility / schema-name flags.
+ let mut assumptions: Vec<String> = Vec::new();
if frame.reversible {
assumptions.push("reversible".to_string());
} else {
@@ -287,11 +317,11 @@ pub fn certify_action(
Verdict::Abstain
};
- let identification_proof = format!(
- "structural-dependency closure of {} target IRI(s) has bounded blast radius of {} triples",
- frame.target_iris.len(),
- cost_triples
- );
+ // Identification proof: structural by default; do-calculus when requested
+ // and the `causal-pywhy` feature is enabled and PyWhy succeeds.
+ let (identification_proof, identification_assumption) =
+ derive_identification_proof(graph, frame, cost_triples);
+ assumptions.push(identification_assumption);
let certificate = Certificate {
verdict,
@@ -393,6 +423,157 @@ fn z_from_alpha(alpha: f64) -> f64 {
}
}
+/// Compute the certificate's `identification_proof` string and the assumption
+/// label that accompanies it. Branches on [`ActionFrame::identification_mode`]:
+///
+/// - [`IdentificationMode::Structural`] (default, always available): returns
+/// the v0.4 sentence + `"structural_only"`.
+/// - [`IdentificationMode::DoCalculusBackdoor`]: attempts a PyWhy subprocess
+/// when the `causal-pywhy` feature is on. On success, returns DoWhy's
+/// adjustment estimand + `"do_calculus_backdoor"`. On any failure, falls
+/// back to the structural sentence + `"do_calculus_unavailable:<kind>"`.
+/// When the feature is off, falls back to the structural sentence +
+/// `"do_calculus_unavailable:feature_disabled"`.
+fn derive_identification_proof(
+ graph: &Arc<GraphStore>,
+ frame: &ActionFrame,
+ cost_triples: u64,
+) -> (String, String) {
+ let structural_sentence = format!(
+ "structural-dependency closure of {} target IRI(s) has bounded blast radius of {} triples",
+ frame.target_iris.len(),
+ cost_triples
+ );
+ match frame.identification_mode {
+ IdentificationMode::Structural => (structural_sentence, "structural_only".to_string()),
+ IdentificationMode::DoCalculusBackdoor => {
+ attempt_do_calculus_backdoor(graph, frame, &structural_sentence)
+ }
+ }
+}
+
+#[cfg(feature = "causal-pywhy")]
+fn attempt_do_calculus_backdoor(
+ graph: &Arc<GraphStore>,
+ frame: &ActionFrame,
+ structural_sentence: &str,
+) -> (String, String) {
+ let (nodes, edges, treatment, outcome) = build_causal_dag(graph, &frame.target_iris);
+ let input = crate::civex_pywhy::PyWhyInput {
+ nodes: &nodes,
+ edges: &edges,
+ treatment: &treatment,
+ outcome: &outcome,
+ };
+ match crate::civex_pywhy::run_pywhy_backdoor(&input, None) {
+ Ok(est) if est.identifiable => {
+ let proof = format!(
+ "do_calculus_backdoor: P({}|do({})) identified via adjustment set {:?}; estimand: {}",
+ outcome, treatment, est.adjustment_set, est.estimand_expression
+ );
+ (proof, "do_calculus_backdoor".to_string())
+ }
+ Ok(_) => (
+ structural_sentence.to_string(),
+ "do_calculus_unavailable:unidentifiable".to_string(),
+ ),
+ Err(e) => {
+ let reason = e
+ .to_string()
+ .split(':')
+ .next()
+ .unwrap_or("runtime_failed")
+ .to_string();
+ (
+ structural_sentence.to_string(),
+ format!("do_calculus_unavailable:{}", reason),
+ )
+ }
+ }
+}
+
+#[cfg(not(feature = "causal-pywhy"))]
+fn attempt_do_calculus_backdoor(
+ _graph: &Arc<GraphStore>,
+ _frame: &ActionFrame,
+ structural_sentence: &str,
+) -> (String, String) {
+ (
+ structural_sentence.to_string(),
+ "do_calculus_unavailable:feature_disabled".to_string(),
+ )
+}
+
+/// Build a causal DAG suitable for PyWhy from the loaded graph + a set of
+/// target IRIs (#48, v0.5). Nodes are the target IRIs plus their one-hop
+/// structural neighbours (the same slice CIVeX hashes into `slice_hash`).
+/// Edges are derived from `rdfs:subClassOf` / `rdfs:subPropertyOf` /
+/// `rdfs:domain` / `rdfs:range` triples observed in the graph that connect
+/// two nodes in the slice. A synthetic `__utility__` sink node is added
+/// downstream of every other node, modelling "every structural variable
+/// in the slice could influence the utility metric."
+///
+/// Returns `(nodes, edges, treatment, outcome)` ready for
+/// [`crate::civex_pywhy::PyWhyInput`].
+#[allow(dead_code)] // referenced under `causal-pywhy` feature only
+fn build_causal_dag(
+ graph: &Arc<GraphStore>,
+ target_iris: &[String],
+) -> (Vec<String>, Vec<(String, String)>, String, String) {
+ use std::collections::BTreeSet;
+
+ let mut nodes: BTreeSet<String> = BTreeSet::new();
+ for iri in target_iris {
+ nodes.insert(iri.clone());
+ }
+ let deps = collect_dependency_iris(graph, target_iris);
+ for d in deps {
+ nodes.insert(d);
+ }
+
+ // Pull subclass / subproperty / domain / range edges among the slice.
+ let nodes_vec: Vec<String> = nodes.iter().cloned().collect();
+ let edge_predicates = [
+ "http://www.w3.org/2000/01/rdf-schema#subClassOf",
+ "http://www.w3.org/2000/01/rdf-schema#subPropertyOf",
+ "http://www.w3.org/2000/01/rdf-schema#domain",
+ "http://www.w3.org/2000/01/rdf-schema#range",
+ ];
+ let mut edges: Vec<(String, String)> = Vec::new();
+ for pred in edge_predicates {
+ let q = format!("SELECT ?s ?o WHERE {{ ?s <{}> ?o }} LIMIT 500", pred);
+ if let Ok(json_str) = graph.sparql_select(&q)
+ && let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json_str)
+ && let Some(rows) = parsed["results"].as_array()
+ {
+ for row in rows {
+ if let (Some(s), Some(o)) = (row["s"].as_str(), row["o"].as_str()) {
+ let s = s.trim_matches(|c| c == '<' || c == '>').to_string();
+ let o = o.trim_matches(|c| c == '<' || c == '>').to_string();
+ if nodes.contains(&s) && nodes.contains(&o) {
+ // Edges in DoWhy point "cause → effect"; subClassOf
+ // says s is-a o, so structurally o influences s.
+ edges.push((o, s));
+ }
+ }
+ }
+ }
+ }
+
+ // Synthetic utility outcome — every structural node could influence it.
+ let utility_node = "__utility__".to_string();
+ for n in &nodes_vec {
+ edges.push((n.clone(), utility_node.clone()));
+ }
+ nodes.insert(utility_node.clone());
+
+ let treatment = target_iris
+ .first()
+ .cloned()
+ .unwrap_or_else(|| "__none__".to_string());
+ (nodes.into_iter().collect(), edges, treatment, utility_node)
+}
+
/// Collect IRIs structurally dependent on the action's target IRIs. The scaffold
/// uses one-hop closure (subjects/objects of any triple referencing a target).
/// A production version would walk the full subclass + property-domain/range
diff --git a/src/inputs.rs b/src/inputs.rs
index 1d741a3c..4d39b0ce 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -582,6 +582,13 @@ pub struct OntoCertifyActionInput {
/// about which action was certified.
#[serde(default)]
pub action_schema_name: Option<String>,
+ /// Identification mode (#48, v0.5). One of `"structural"` (default,
+ /// the v0.4 behaviour) or `"do_calculus_backdoor"`. The latter only
+ /// takes effect when the server was built with the `causal-pywhy`
+ /// Cargo feature; otherwise the verifier silently falls back to
+ /// structural identification and records the reason in assumptions.
+ #[serde(default)]
+ pub identification_mode: Option<String>,
}
fn default_utility_metric() -> String {
diff --git a/src/server.rs b/src/server.rs
index 5e526a01..a820718b 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -953,6 +953,10 @@ impl OpenOntologiesServer {
allow_experiment: input.allow_experiment,
alpha: input.alpha,
action_schema_name: input.action_schema_name,
+ identification_mode: match input.identification_mode.as_deref() {
+ Some("do_calculus_backdoor") => crate::civex::IdentificationMode::DoCalculusBackdoor,
+ _ => crate::civex::IdentificationMode::Structural,
+ },
};
match crate::civex::certify_action(&self.db, &self.graph, &frame) {
Ok(result) => serde_json::to_string(&result)
diff --git a/tests/civex_test.rs b/tests/civex_test.rs
index 73c1411a..61136ed3 100644
--- a/tests/civex_test.rs
+++ b/tests/civex_test.rs
@@ -42,6 +42,7 @@ fn base_frame() -> ActionFrame {
allow_experiment: false,
alpha: 0.05,
action_schema_name: None,
+ identification_mode: open_ontologies::civex::IdentificationMode::Structural,
}
}
@@ -158,6 +159,59 @@ fn reversible_with_experiment_authorisation_returns_experiment() {
assert!(result.certificate.rationale.contains("EXPERIMENT"));
}
+#[test]
+fn structural_mode_records_structural_only_assumption() {
+ // v0.5: when identification_mode = Structural (default), the certificate
+ // carries exactly the v0.4 assumption.
+ let (db, graph) = setup();
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Cat a owl:Class .
+ "#, None).unwrap();
+
+ let frame = base_frame();
+ let result = certify_action(&db, &graph, &frame).expect("certify");
+ let has_structural = result.certificate.assumptions.iter()
+ .any(|a| a == "structural_only");
+ assert!(has_structural, "structural mode should record structural_only assumption; got: {:?}",
+ result.certificate.assumptions);
+ // And NOT a do-calculus assumption.
+ assert!(!result.certificate.assumptions.iter().any(|a| a.starts_with("do_calculus")),
+ "structural mode should NOT record any do_calculus assumption; got: {:?}",
+ result.certificate.assumptions);
+}
+
+#[test]
+fn do_calculus_mode_falls_back_to_structural_when_feature_disabled() {
+ // v0.5: when identification_mode = DoCalculusBackdoor but the
+ // `causal-pywhy` Cargo feature is OFF (the default build configuration),
+ // the verifier silently falls back to structural and records the reason.
+ let (db, graph) = setup();
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Cat a owl:Class .
+ "#, None).unwrap();
+
+ let mut frame = base_frame();
+ frame.identification_mode = open_ontologies::civex::IdentificationMode::DoCalculusBackdoor;
+
+ let result = certify_action(&db, &graph, &frame).expect("certify");
+ // The certificate should still issue a verdict (no panics from fallback).
+ let assumptions = &result.certificate.assumptions;
+
+ // Under the default build, the assumption must be the feature_disabled marker.
+ // Under `causal-pywhy` build, Python or DoWhy may or may not exist; either
+ // way the fallback should NOT crash.
+ let has_do_calculus_marker = assumptions.iter().any(|a| a.starts_with("do_calculus"));
+ assert!(has_do_calculus_marker,
+ "DoCalculusBackdoor mode should record SOME do_calculus_* assumption; got: {:?}",
+ assumptions);
+ // The proof string should be non-empty regardless of branch taken.
+ assert!(!result.certificate.identification_proof.is_empty());
+}
+
#[test]
fn action_schema_name_is_recorded_in_certificate_assumptions() {
// CIVeX × Dynamics integration: passing a Dynamics action schema name
diff --git a/tests/three_layer_integration_test.rs b/tests/three_layer_integration_test.rs
index d68e56cd..a297ddb1 100644
--- a/tests/three_layer_integration_test.rs
+++ b/tests/three_layer_integration_test.rs
@@ -153,6 +153,7 @@ fn civex_certifies_against_dynamics_action_and_records_schema_name() {
allow_experiment: false,
alpha: 0.05,
action_schema_name: Some("add_subclass_edge".to_string()),
+ identification_mode: open_ontologies::civex::IdentificationMode::Structural,
};
let result = certify_action(&db, &graph, &frame).expect("certify");
@@ -228,6 +229,7 @@ fn full_three_layer_pipeline_register_certify_apply() {
allow_experiment: false,
alpha: 0.05,
action_schema_name: Some(schema.name.clone()),
+ identification_mode: open_ontologies::civex::IdentificationMode::Structural,
};
let cert = certify_action(&db, &graph, &frame).expect("certify");
assert_eq!(cert.certificate.verdict, Verdict::Execute);