behavior-contracts 0.1.2

Language-neutral IR runtime core (expression evaluation, template rendering, execution plan, canonical serialization) shared across DSL implementations. Passes the dsl-contracts conformance vectors byte-for-byte.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! conformance.rs — dsl-contracts conformance kit Rust runner.
//!
//!   cargo run --bin conformance
//!
//! Loads ../conformance/vectors/*.json, runs each vector through the reference
//! primitives, compares to expect, and tallies pass/fail. exit 0 if all pass,
//! exit 1 on any fail, exit 2 on a spec-version mismatch (pre-flight fail-closed).

use std::path::{Path, PathBuf};
use std::process::exit;

use behavior_contracts::canonical::{
    canonical_json, canonical_value, py_float_repr, CanonicalFailure,
};
use behavior_contracts::codec::{decode_value, encode_value};
use behavior_contracts::expr::{evaluate as evaluate_expression, ExprFailure};
use behavior_contracts::plan::{
    run_plan, ExecOutcome, ExecutionPlanSpec, OpSpec, PlanFailure, RelationKind,
};
use behavior_contracts::template::{render_template, TemplateFailure};
use behavior_contracts::value::{deep_equals, Value};
use behavior_contracts::SpecVersions;

use serde_json::Value as J;

fn vectors_dir() -> PathBuf {
    if let Ok(env) = std::env::var("DSL_CONTRACTS_VECTORS") {
        return PathBuf::from(env);
    }
    // this file: <crate>/src/bin/conformance.rs ; CARGO_MANIFEST_DIR = <crate> = dsl-contracts/rust
    let manifest = env!("CARGO_MANIFEST_DIR");
    Path::new(manifest)
        .parent()
        .unwrap()
        .join("conformance")
        .join("vectors")
}

fn load_json(dir: &Path, file: &str) -> J {
    let raw = std::fs::read_to_string(dir.join(file))
        .unwrap_or_else(|e| panic!("cannot read {file}: {e}"));
    serde_json::from_str(&raw).unwrap_or_else(|e| panic!("cannot parse {file}: {e}"))
}

struct Tally {
    passed: u32,
    failed: u32,
}

fn line(ok: bool, name: &str, detail: &str) {
    if ok {
        println!("  \u{2713} {name}");
    } else {
        println!("  \u{2717} {name}");
        if !detail.is_empty() {
            println!("      {detail}");
        }
    }
}

fn bump(t: &mut Tally, ok: bool) {
    if ok {
        t.passed += 1;
    } else {
        t.failed += 1;
    }
}

// ── pre-flight version sweep (PROTOCOL §5) ───────────────────────────────────
fn preflight(dir: &Path) -> std::collections::HashMap<&'static str, J> {
    let specs: [(&str, &str, &str, i64); 4] = [
        (
            "expression.json",
            "expression",
            "exprVersion",
            SpecVersions::EXPRESSION,
        ),
        (
            "template.json",
            "template",
            "templateVersion",
            SpecVersions::TEMPLATE,
        ),
        ("plan.json", "plan", "planVersion", SpecVersions::PLAN),
        (
            "canonical.json",
            "canonical",
            "canonicalVersion",
            SpecVersions::CANONICAL,
        ),
    ];
    let loaded: Vec<(&str, &str, i64, J)> = specs
        .iter()
        .map(|(f, suite, vk, want)| (*suite, *vk, *want, load_json(dir, f)))
        .collect();
    let mismatches: Vec<(&str, i64, i64)> = loaded
        .iter()
        .filter_map(|(suite, vk, want, doc)| {
            let got = doc.get(*vk).and_then(|v| v.as_i64()).unwrap_or(-1);
            if got != *want {
                Some((*suite, got, *want))
            } else {
                None
            }
        })
        .collect();
    if !mismatches.is_empty() {
        for (suite, got, want) in &mismatches {
            eprintln!("FAIL-CLOSED: {suite} suite version {got} != supported {want}.");
        }
        eprintln!(
            "Refusing to run: {} suite version mismatch(es). No vectors executed.",
            mismatches.len()
        );
        exit(2);
    }
    loaded
        .into_iter()
        .map(|(suite, _, _, doc)| (suite, doc))
        .collect()
}

fn as_scope(v: Option<&J>) -> Vec<(String, Value)> {
    match v {
        Some(J::Object(o)) => o
            .iter()
            .map(|(k, val)| (k.clone(), decode_value(val).expect("decode scope")))
            .collect(),
        _ => Vec::new(),
    }
}

// ── expression ───────────────────────────────────────────────────────────────
fn run_expression(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\nexpression.json (v{}) — {} vectors",
        doc["exprVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let scope = as_scope(v.get("scope"));
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());
        match evaluate_expression(&v["expr"], &scope) {
            Ok(result) => {
                if let Some(exp) = expect.get("value") {
                    let want = decode_value(exp).expect("decode expect.value");
                    ok = deep_equals(&result, &want);
                    if !ok {
                        detail = format!("expected value {}, got {}", exp, encode_value(&result));
                    }
                } else {
                    detail = format!("expected Failure({}), got a value", expect["failure"]);
                }
            }
            Err(e) => {
                let e: ExprFailure = e;
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code.as_str() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code.as_str());
                    }
                } else {
                    detail = format!("expected a value, got Failure({})", e.code.as_str());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── template ─────────────────────────────────────────────────────────────────
fn run_template(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\ntemplate.json (v{}) — {} vectors",
        doc["templateVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let tmpl = v["template"].as_str().unwrap();
        let params: Vec<(String, Value)> = v["params"]
            .as_object()
            .unwrap()
            .iter()
            .map(|(k, val)| (k.clone(), decode_value(val).expect("decode param")))
            .collect();
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());
        match render_template(tmpl, &params) {
            Ok(out) => {
                if let Some(exp) = expect.get("ok").and_then(|x| x.as_str()) {
                    ok = out == exp;
                    if !ok {
                        detail = format!("expected {exp:?}, got {out:?}");
                    }
                } else {
                    detail = format!("expected Failure({}), got {out:?}", expect["failure"]);
                }
            }
            Err(e) => {
                let e: TemplateFailure = e;
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code.as_str() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code.as_str());
                    }
                } else {
                    detail = format!("expected value, got Failure({})", e.code.as_str());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── canonical ────────────────────────────────────────────────────────────────
fn run_canonical(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\ncanonical.json (v{}) — {} vectors",
        doc["canonicalVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let kind = v["kind"].as_str().unwrap();
        let expect = &v["expect"];
        let val = decode_value(&v["value"]).expect("decode value");
        let (mut ok, mut detail) = (false, String::new());
        let result: Result<String, CanonicalFailure> = match kind {
            "canonicalValue" => canonical_value(&val),
            "canonicalJson" => canonical_json(&val),
            "floatRepr" => match &val {
                Value::Float(f) => py_float_repr(*f),
                other => panic!("floatRepr expects a float, got {}", other.type_name()),
            },
            other => panic!("unknown kind: {other}"),
        };
        match result {
            Ok(out) => {
                if let Some(exp) = expect.get("ok").and_then(|x| x.as_str()) {
                    ok = out == exp;
                    if !ok {
                        detail = format!("expected {exp:?}, got {out:?}");
                    }
                } else {
                    detail = format!("expected Failure({}), got {out:?}", expect["failure"]);
                }
            }
            Err(e) => {
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code.as_str() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code.as_str());
                    }
                } else {
                    detail = format!("expected value, got Failure({})", e.code.as_str());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

// ── plan ─────────────────────────────────────────────────────────────────────
fn parse_op(o: &J) -> OpSpec {
    let relation_kind = o
        .get("relationKind")
        .and_then(|r| r.as_str())
        .map(|s| match s {
            "connection" => RelationKind::Connection,
            _ => RelationKind::Single,
        });
    OpSpec {
        id: o["id"].as_str().unwrap().to_string(),
        parent: o.get("parent").and_then(|p| p.as_u64()).map(|p| p as usize),
        bind_field: o
            .get("bindField")
            .and_then(|b| b.as_str())
            .map(|s| s.to_string()),
        relation_kind,
        policy: o
            .get("policy")
            .and_then(|p| p.as_str())
            .map(|s| s.to_string()),
    }
}

fn parse_plan(p: &J) -> Option<ExecutionPlanSpec> {
    if p.is_null() {
        return None;
    }
    let groups = p["groups"]
        .as_array()
        .unwrap()
        .iter()
        .map(|g| {
            g.as_array()
                .unwrap()
                .iter()
                .map(|i| i.as_u64().unwrap() as usize)
                .collect()
        })
        .collect();
    let concurrency = p.get("concurrency").and_then(|c| c.as_i64()).unwrap_or(1);
    Some(ExecutionPlanSpec {
        groups,
        concurrency,
    })
}

fn same_set(a: &[String], b: &[J]) -> bool {
    let mut sa: Vec<&str> = a.iter().map(|s| s.as_str()).collect();
    let mut sb: Vec<&str> = b.iter().map(|s| s.as_str().unwrap()).collect();
    sa.sort_unstable();
    sb.sort_unstable();
    sa == sb
}

fn run_plan_suite(t: &mut Tally, doc: &J) {
    let vectors = doc["vectors"].as_array().unwrap();
    println!(
        "\nplan.json (v{}) — {} vectors",
        doc["planVersion"],
        vectors.len()
    );
    for v in vectors {
        let name = v["name"].as_str().unwrap_or("?");
        let plan = parse_plan(v.get("plan").unwrap_or(&J::Null));
        let ops: Vec<OpSpec> = v["ops"].as_array().unwrap().iter().map(parse_op).collect();
        let exec_map = v["exec"].as_object().unwrap();
        let expect = &v["expect"];
        let (mut ok, mut detail) = (false, String::new());

        let exec = |op: &OpSpec, _bound: Option<&Value>| -> ExecOutcome {
            let o = exec_map
                .get(&op.id)
                .unwrap_or_else(|| panic!("no mock outcome for op '{}'", op.id));
            if let Some(okv) = o.get("ok") {
                ExecOutcome::Ok(decode_value(okv).expect("decode exec.ok"))
            } else {
                ExecOutcome::Error(o["error"].as_str().unwrap_or("").to_string())
            }
        };

        match run_plan(plan.as_ref(), &ops, exec) {
            Ok(res) => {
                if let Some(f) = expect.get("failure") {
                    detail = format!("expected Failure({f}), got a full run");
                } else {
                    let tree = Value::Obj(res.final_tree());
                    let exp_tree_pairs: Vec<(String, Value)> = expect["tree"]
                        .as_object()
                        .unwrap()
                        .iter()
                        .map(|(k, val)| (k.clone(), decode_value(val).expect("decode expect.tree")))
                        .collect();
                    let exp_tree = Value::Obj(exp_tree_pairs);
                    let got_c = canonical_json(&tree).expect("canonical tree");
                    let want_c = canonical_json(&exp_tree).expect("canonical exp tree");
                    let tree_ok = got_c == want_c;
                    let exec_ok = same_set(&res.executed, expect["executed"].as_array().unwrap());
                    let skip_ok = same_set(&res.skipped, expect["skipped"].as_array().unwrap());
                    ok = tree_ok && exec_ok && skip_ok;
                    if !ok {
                        let mut parts = Vec::new();
                        if !tree_ok {
                            parts.push(format!("tree {got_c} != {want_c}"));
                        }
                        if !exec_ok {
                            parts.push(format!(
                                "executed {:?} != {}",
                                res.executed, expect["executed"]
                            ));
                        }
                        if !skip_ok {
                            parts.push(format!(
                                "skipped {:?} != {}",
                                res.skipped, expect["skipped"]
                            ));
                        }
                        detail = parts.join("; ");
                    }
                }
            }
            Err(e) => {
                let e: PlanFailure = e;
                if let Some(f) = expect.get("failure").and_then(|f| f.as_str()) {
                    ok = e.code.as_str() == f;
                    if !ok {
                        detail = format!("expected Failure({f}), got Failure({})", e.code.as_str());
                    }
                } else {
                    detail = format!("expected a full run, got Failure({})", e.code.as_str());
                }
            }
        }
        line(ok, name, &detail);
        bump(t, ok);
    }
}

fn main() {
    println!("dsl-contracts conformance kit — Rust runner");
    let dir = vectors_dir();
    let docs = preflight(&dir); // STEP 1: fail-closed pre-flight

    let mut t = Tally {
        passed: 0,
        failed: 0,
    };
    run_expression(&mut t, &docs["expression"]);
    run_template(&mut t, &docs["template"]);
    run_plan_suite(&mut t, &docs["plan"]);
    run_canonical(&mut t, &docs["canonical"]);

    let total = t.passed + t.failed;
    println!(
        "\n{} passed, {} failed / {total} vectors across 4 suites",
        t.passed, t.failed
    );
    exit(if t.failed > 0 { 1 } else { 0 });
}