interplane.Get Omega
Read in your language

interplane-mv

INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.

Brought by drakestapleton

branch main Branches Tags History

interplane-mv / adapters / aien / tests / t4_corpus.rs

401 lines · 16420 bytes Raw Blame History
1//! T4 runner (bench/PROTOCOL-0.3.md section 2): the AIEN subset of the 0.3 corpus through the real
2//! `Pipeline` and `AienAuthority`.
3//!
4//! The subset and the translation of each fixture onto the adapter come from
5//! `interplane_conformance::subset`, the code behind `interplane-corpus subset --plans aien` (the rule
6//! is normative text in spec/CORE.md, "Adapter subsets"); the list must equal `t4_subset` of
7//! `conformance/TRUST-DIGEST.txt`. Every fixture in the subset runs. One the adapter cannot run is
8//! a FAIL, never a skip (a panic inside a case is caught and reported as that case's FAIL).
9//! Injection cases use the injection judgement of the conformance runners (violations,
10//! content_derived, injected_intents). Approval cases are judged against the fixture's own expected
11//! rows (A-AIEN): every observed record and every continuation row (outcome, stage, reason; message
12//! text excluded) must equal the mock's. Set `T4_OUT=<path>` to write the verdict JSON.
13use interplane_adapter_aien::*;
14use interplane_core::*;
15use interplane_crossveil::{CallContext, ObservedRecord, Pipeline, RuntimeAuthority};
16use interplane_lenshift::DialectRegistry;
17use serde_json::{json, Value};
18use std::cell::RefCell;
19use std::collections::HashSet;
20use std::panic::{catch_unwind, AssertUnwindSafe};
21use std::rc::Rc;
22
23type Requests = Rc<RefCell<Vec<(String, String, String)>>>;
24type Executed = Rc<RefCell<HashSet<String>>>;
25
26const EFFECTS: [&str; 4] = ["append_note", "write_file", "delete_file", "send_email"];
27
28fn repo() -> std::path::PathBuf {
29 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
30}
31
32/// The real adapter, recording every decided request and every executed id for the judge.
33struct Rec {
34 inner: AienShared,
35 requests: Requests,
36 executed: Executed,
37}
38
39impl RuntimeAuthority for Rec {
40 fn runtime_id(&self) -> &str {
41 RUNTIME_ID
42 }
43 fn decide(&mut self, req: &CapabilityRequest, ctx: &CallContext) -> Decision {
44 let args = serde_json::to_string(&req.arguments).unwrap_or_default();
45 self.requests.borrow_mut().push((
46 req.request_id.as_str().to_string(),
47 req.capability.clone(),
48 args,
49 ));
50 self.inner.decide(req, ctx)
51 }
52 fn execute(
53 &mut self,
54 req: &CapabilityRequest,
55 decision: &Decision,
56 ctx: &CallContext,
57 ) -> ToolResult {
58 self.executed
59 .borrow_mut()
60 .insert(req.request_id.as_str().to_string());
61 self.inner.execute(req, decision, ctx)
62 }
63 fn catalog(&self) -> Catalog {
64 self.inner.catalog()
65 }
66}
67
68fn plans() -> Vec<Value> {
69 let corpus = interplane_conformance::subset::Corpus::new(&repo());
70 let table = corpus
71 .load_table()
72 .expect("conformance/adapter-translation.json");
73 let plans = corpus.plans("aien", &table).expect("the T4 plans");
74 plans.iter().map(|p| p.to_value()).collect()
75}
76
77fn frozen(key: &str) -> Vec<String> {
78 let text = std::fs::read_to_string(repo().join("conformance/TRUST-DIGEST.txt")).unwrap();
79 text.lines()
80 .find_map(|l| l.strip_prefix(&format!("{key}: ")))
81 .map(|v| {
82 v.split(',')
83 .filter(|s| !s.is_empty())
84 .map(String::from)
85 .collect()
86 })
87 .unwrap_or_default()
88}
89
90/// `YYYY-MM-DDTHH:MM:SSZ` to epoch seconds (days-from-civil), the form AIEN's grant expiry takes.
91fn epoch(s: &str) -> u64 {
92 let n = |a: usize, b: usize| s[a..b].parse::<i64>().unwrap_or(0);
93 let (y, m, d) = (n(0, 4), n(5, 7), n(8, 10));
94 let y = if m <= 2 { y - 1 } else { y };
95 let era = y.div_euclid(400);
96 let yoe = y - era * 400;
97 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
98 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
99 let days = era * 146097 + doe - 719468;
100 (days * 86400 + n(11, 13) * 3600 + n(14, 16) * 60 + n(17, 19)) as u64
101}
102
103fn key_eq(got: &Value, want: &Value, keys: &[&str]) -> Vec<String> {
104 keys.iter()
105 .filter(|k| got[**k] != want[**k])
106 .map(|k| format!("{k}: {} != {}", got[*k], want[*k]))
107 .collect()
108}
109
110fn build<'a>(rec: &'a mut Rec, shared: &AienShared, case: &str) -> Pipeline<'a> {
111 let table = shared.with(|a| a.mapping_table(false));
112 let mut p = Pipeline::new(
113 DialectRegistry::with_defaults(),
114 table,
115 rec,
116 Limits::default(),
117 RequestLedger::new(),
118 );
119 p.message_prefix = format!("m-{case}");
120 p
121}
122
123fn run(plan: &Value) -> Value {
124 let ws = tempfile::tempdir().unwrap();
125 std::fs::write(ws.path().join("notes.txt"), "hello from the workspace\n").unwrap();
126 let shared = AienShared::new(AienAuthority::new(ws.path()).unwrap());
127 let (requests, executed): (Requests, Executed) = Default::default();
128 let mut rec = Rec {
129 inner: shared.clone(),
130 requests: requests.clone(),
131 executed: executed.clone(),
132 };
133 let trace = plan["trace_id"].as_str().unwrap().to_string();
134 let case = plan["case"].as_str().unwrap().to_string();
135 let mut p = build(&mut rec, &shared, &case);
136 let (mut observed, mut intents, mut continuations): (Vec<ObservedRecord>, u64, Vec<Value>) =
137 (vec![], 0, vec![]);
138 let mut minted: std::collections::HashMap<String, String> = Default::default();
139 let note = |p: &Pipeline<'_>,
140 o: &ObservedRecord,
141 minted: &mut std::collections::HashMap<String, String>| {
142 if let Some(rid) = &o.request_id {
143 if let Some(pa) = p.pending_approval(&trace, rid) {
144 minted.insert(rid.clone(), pa.approval_id);
145 }
146 }
147 };
148 let (mut envelopes, mut approval_rows) = (0u64, vec![]);
149 for (ix, step) in plan["steps"].as_array().unwrap().iter().enumerate() {
150 if let Some(h) = step.get("host_input") {
151 if let Ok(r) = serde_json::from_value::<InputRecord>(h["input"].clone()) {
152 let _ = p.register_input(r);
153 }
154 } else if step.get("restart").is_some() {
155 drop(p);
156 p = build(&mut rec, &shared, &case);
157 } else if let Some(env) = step.get("envelope") {
158 envelopes += 1;
159 let (_, o) = p.admit_value(env);
160 note(&p, &o, &mut minted);
161 observed.push(o);
162 } else if step.get("approve").is_some() || step.get("cancel").is_some() {
163 let kind = if step.get("approve").is_some() {
164 "approve"
165 } else {
166 "cancel"
167 };
168 let a = &step[kind];
169 let rid = a["request_id"].as_str().unwrap_or("").to_string();
170 let tr = a["trace_id"].as_str().unwrap_or(&trace).to_string();
171 let out = if kind == "cancel" {
172 p.cancel_approval(&tr, &rid)
173 } else {
174 let now = a["now"].as_str().unwrap_or("2026-01-01T00:00:00Z");
175 let aid = match a["approval_id"]["minted_for"].as_str() {
176 Some(r) => minted
177 .get(r)
178 .cloned()
179 .unwrap_or(format!("mock-approval-{r}")),
180 None => a["approval_id"]["literal"]
181 .as_str()
182 .unwrap_or("")
183 .to_string(),
184 };
185 let pend = p.pending_approval(&tr, &rid);
186 let (mut dv, dg) = match &pend {
187 Some(pa) => {
188 let exp = plan["expires_at"]
189 .as_str()
190 .map_or(epoch(now) + 86400, epoch);
191 let grant = shared
192 .with(|x| x.issue_approval(&pa.capability_request, exp))
193 .expect("host issues a grant for the pending request");
194 // The case's synthetic `now` is also the adapter's clock, which
195 // sovereign-core #260 checks again at commit.
196 let t = epoch(now);
197 let d = shared.with(|x| {
198 x.set_clock(std::sync::Arc::new(move || t));
199 x.present_approval(&pa.capability_request, &grant, t)
200 });
201 let dg = match a.get("arguments") {
202 Some(args) => {
203 let mut c = pa.capability_request.clone();
204 c.arguments = args.as_object().cloned().unwrap_or_default();
205 interplane_crossveil::capability_request_digest(&c)
206 }
207 None => pa.request_digest.clone(),
208 };
209 (serde_json::to_value(&d).unwrap(), dg)
210 }
211 None => (
212 json!({"kind": "decision", "request_id": rid, "decision": "authorized",
213 "capability": null, "authority": {"runtime": "aien", "policy_engine": "aien.effects"},
214 "approval": {"approval_id": ""}}),
215 digest(&Value::Null),
216 ),
217 };
218 dv["approval"]["approval_id"] = json!(aid);
219 if let Some(d) = a.get("decision") {
220 dv["decision"] = d.clone();
221 }
222 if let Some(r) = a.get("decision_request_id") {
223 dv["request_id"] = r.clone();
224 }
225 let d: Decision = serde_json::from_value(dv).expect("continuation decision");
226 let out = p.continue_approval(&tr, &rid, &d, &dg, now);
227 shared.with(|x| x.discard_unexecuted(&rid));
228 out
229 };
230 let stage = p
231 .pending_approval(&tr, &rid)
232 .map_or(Value::Null, |e| json!(e.state.name()));
233 continuations.push(match out {
234 Ok((r, o)) => {
235 let msg = r
236 .error
237 .as_ref()
238 .map_or(Value::Null, |e| json!(e.message.clone()));
239 observed.push(o);
240 json!({"step": ix, "kind": kind, "request_id": rid, "outcome": "resolved",
241 "stage": stage, "reason": null, "message": msg})
242 }
243 Err(e) => json!({"step": ix, "kind": kind, "request_id": rid, "outcome": "refused",
244 "stage": stage, "reason": e.as_str(), "message": null}),
245 });
246 } else {
247 let d = step["dialect"].as_str().unwrap();
248 let out = p.run_turn(
249 d,
250 step["model"].as_str().unwrap_or(""),
251 &step["input"],
252 &trace,
253 step["turn"].as_u64().unwrap_or(0),
254 );
255 intents += out.intents.len() as u64;
256 for o in &out.records {
257 note(&p, o, &mut minted);
258 }
259 observed.extend(out.records);
260 }
261 }
262 drop(p);
263 let mut problems: Vec<String> = vec![];
264 let mut row = json!({});
265 if plan["kind"] == "injection" {
266 let cap = plan["target"]["capability"].as_str().unwrap();
267 let needle = plan["target"]["argument_contains"].as_str().unwrap();
268 let reqs = requests.borrow();
269 let hit = |r: &&(String, String, String)| {
270 r.1 == cap && !needle.is_empty() && r.2.contains(needle)
271 };
272 let injected = reqs.iter().filter(hit).count();
273 let violations = reqs
274 .iter()
275 .filter(hit)
276 .filter(|r| EFFECTS.contains(&r.1.as_str()) && executed.borrow().contains(&r.0))
277 .count();
278 let derived = (reqs.len() as u64).saturating_sub(intents + envelopes);
279 row["injection"] = json!({"injected_intents": injected, "violations": violations, "content_derived": derived});
280 let decisions: std::collections::BTreeSet<String> = observed
281 .iter()
282 .filter(|o| {
283 o.request_id
284 .as_ref()
285 .is_some_and(|id| reqs.iter().filter(hit).any(|r| &r.0 == id))
286 })
287 .filter_map(|o| o.decision.clone())
288 .collect();
289 row["injected_decisions"] = json!(decisions);
290 if injected == 0 {
291 problems.push("the injected intent never reached the runtime (vacuous case)".into());
292 }
293 if violations > 0 {
294 problems.push(format!(
295 "{violations} effect(s) executed for the injected intent"
296 ));
297 }
298 if derived > 0 {
299 problems.push(format!("{derived} intent(s) derived from content"));
300 }
301 } else {
302 let want = plan["expected"]["observed"].as_array().unwrap();
303 let got: Vec<Value> = observed
304 .iter()
305 .map(|o| serde_json::to_value(o).unwrap())
306 .collect();
307 if want.len() != got.len() {
308 problems.push(format!("observed count {} != {}", got.len(), want.len()));
309 }
310 for (i, (g, w)) in got.iter().zip(want).enumerate() {
311 for m in key_eq(
312 g,
313 w,
314 &[
315 "request_id",
316 "stage",
317 "decision",
318 "status",
319 "error_code",
320 "decide_invoked",
321 "execute_invoked",
322 ],
323 ) {
324 problems.push(format!("observed[{i}].{m}"));
325 }
326 }
327 let wc = plan["expected"]["continuations"].as_array().unwrap();
328 if wc.len() != continuations.len() {
329 problems.push(format!(
330 "continuations {} != {}",
331 continuations.len(),
332 wc.len()
333 ));
334 }
335 for (i, (g, w)) in continuations.iter().zip(wc).enumerate() {
336 for m in key_eq(
337 g,
338 w,
339 &["step", "kind", "request_id", "outcome", "stage", "reason"],
340 ) {
341 problems.push(format!("continuations[{i}].{m}"));
342 }
343 }
344 approval_rows = continuations.clone();
345 }
346 row["effects_executed"] = json!(executed.borrow().len());
347 row["observed"] = serde_json::to_value(&observed).unwrap();
348 row["continuations"] = json!(approval_rows);
349 row["pass"] = json!(problems.is_empty());
350 row["problems"] = json!(problems);
351 row
352}
353
354#[test]
355fn t4_subset_runs_and_every_case_passes() {
356 let plans = plans();
357 let names: Vec<String> = plans
358 .iter()
359 .map(|p| p["name"].as_str().unwrap().to_string())
360 .collect();
361 assert_eq!(
362 names,
363 frozen("t4_subset"),
364 "computed T4 subset differs from conformance/TRUST-DIGEST.txt"
365 );
366 assert!(!names.is_empty());
367 let mut rows = serde_json::Map::new();
368 for plan in &plans {
369 let name = plan["name"].as_str().unwrap().to_string();
370 let row = catch_unwind(AssertUnwindSafe(|| run(plan))).unwrap_or_else(|e| {
371 let m = e
372 .downcast_ref::<String>()
373 .cloned()
374 .or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string()))
375 .unwrap_or_default();
376 json!({"pass": false, "problems": [format!("runner could not run it: {m}")]})
377 });
378 rows.insert(name, row);
379 }
380 let failed: Vec<&String> = rows
381 .iter()
382 .filter(|(_, r)| r["pass"] != true)
383 .map(|(n, _)| n)
384 .collect();
385 let sum = |k: &str| -> u64 {
386 rows.values()
387 .filter_map(|r| r["injection"][k].as_u64())
388 .sum()
389 };
390 let summary = json!({"system": "T4", "cases": rows.len(), "passed": rows.len() - failed.len(), "failed": failed,
391 "violations": sum("violations"), "content_derived": sum("content_derived")});
392 if let Ok(out) = std::env::var("T4_OUT") {
393 let doc = json!({"summary": summary, "rows": rows});
394 std::fs::write(out, serde_json::to_string_pretty(&doc).unwrap() + "\n").unwrap();
395 }
396 println!("T4: {summary}");
397 for n in &failed {
398 println!("FAIL {n}: {}", rows[*n]["problems"]);
399 }
400 assert!(failed.is_empty(), "T4 failures: {failed:?}");
401}