behavior-contracts 0.6.0

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Unit tests over the public COMMON API + a conformance-runner smoke test.

use behavior_contracts::{
    assert_portable, assert_portable_component_graph, canonical_json, canonical_value,
    decode_value, deep_equals, evaluate_expression, py_float_repr, render_template, run_behavior,
    run_plan, validate_envelope, ComponentExec, ExecOutcome, OpSpec, Value,
};
use serde_json::json;

fn scope(pairs: &[(&str, Value)]) -> Vec<(String, Value)> {
    pairs
        .iter()
        .map(|(k, v)| (k.to_string(), v.clone()))
        .collect()
}

// ── expression ───────────────────────────────────────────────────────────────
#[test]
fn expr_int_add_checked() {
    let r = evaluate_expression(&json!({"add": [1, 2]}), &[]).unwrap();
    assert!(matches!(r, Value::Int(3)));
}

#[test]
fn expr_i64_overflow_is_failure_not_panic() {
    // i64::MAX + 1 via {int:"…"} literals
    let e = evaluate_expression(
        &json!({"add": [{"int": "9223372036854775807"}, {"int": "1"}]}),
        &[],
    )
    .unwrap_err();
    assert_eq!(e.code.as_str(), "INT_OVERFLOW");
}

#[test]
fn expr_int_literal_beyond_i64_is_failure() {
    let e = evaluate_expression(&json!({"int": "99999999999999999999999"}), &[]).unwrap_err();
    assert_eq!(e.code.as_str(), "INT_OVERFLOW");
}

#[test]
fn expr_mod_sign_follows_dividend() {
    // -7 % 2 == -1 (truncated). Confirms Rust `%` semantics match the spec.
    let r = evaluate_expression(&json!({"mod": [{"int": "-7"}, {"int": "2"}]}), &[]).unwrap();
    assert!(matches!(r, Value::Int(-1)), "got {r:?}");
    let r2 = evaluate_expression(&json!({"mod": [{"int": "7"}, {"int": "-2"}]}), &[]).unwrap();
    assert!(matches!(r2, Value::Int(1)), "got {r2:?}");
}

#[test]
fn expr_div_always_float() {
    let r = evaluate_expression(&json!({"div": [6, 2]}), &[]).unwrap();
    match r {
        Value::Float(f) => assert_eq!(f, 3.0),
        other => panic!("expected float, got {other:?}"),
    }
}

#[test]
fn expr_div_by_zero_is_nan_or_inf() {
    let e = evaluate_expression(&json!({"div": [1, 0]}), &[]).unwrap_err();
    assert_eq!(e.code.as_str(), "NAN_OR_INF");
}

#[test]
fn expr_precision_loss_widening() {
    // |int| > 2^53 widened to float in div → PRECISION_LOSS
    let e =
        evaluate_expression(&json!({"div": [{"int": "9007199254740993"}, 1]}), &[]).unwrap_err();
    assert_eq!(e.code.as_str(), "PRECISION_LOSS");
}

#[test]
fn expr_string_compare_code_point_order() {
    // 'Z'(0x5A) < 'a'(0x61)
    let r = evaluate_expression(&json!({"lt": ["Z", "a"]}), &[]).unwrap();
    assert!(matches!(r, Value::Bool(true)));
}

#[test]
fn expr_ref_and_short_circuit() {
    let s = scope(&[("x", Value::Obj(vec![("n".into(), Value::Int(5))]))]);
    let r = evaluate_expression(&json!({"ref": ["x", "n"]}), &s).unwrap();
    assert!(matches!(r, Value::Int(5)));
    // and short-circuits: right side would be UNKNOWN_BINDING but is not evaluated
    let r2 = evaluate_expression(&json!({"and": [false, {"ref": ["nope"]}]}), &[]).unwrap();
    assert!(matches!(r2, Value::Bool(false)));
}

#[test]
fn expr_unknown_op_fail_closed() {
    let e = evaluate_expression(&json!({"frobnicate": [1]}), &[]).unwrap_err();
    assert_eq!(e.code.as_str(), "UNKNOWN_OP");
}

// ── template ─────────────────────────────────────────────────────────────────
#[test]
fn template_strict_and_stringify() {
    let p = scope(&[("n", Value::Int(42)), ("flag", Value::Bool(true))]);
    assert_eq!(render_template("N#{n}", &p).unwrap(), "N#42");
    assert_eq!(render_template("F#{flag}", &p).unwrap(), "F#True");
}

#[test]
fn template_missing_key_is_failure_not_empty() {
    let e = render_template("USER#{userId}", &[]).unwrap_err();
    assert_eq!(e.code.as_str(), "UNBOUND_PARAM");
}

#[test]
fn template_null_param_is_failure() {
    let p = scope(&[("userId", Value::Null)]);
    let e = render_template("USER#{userId}", &p).unwrap_err();
    assert_eq!(e.code.as_str(), "UNBOUND_PARAM");
}

#[test]
fn template_empty_braces_are_literal() {
    assert_eq!(render_template("a{}b", &[]).unwrap(), "a{}b");
}

// ── canonical ────────────────────────────────────────────────────────────────
#[test]
fn canonical_top_level_sort_only() {
    let v = decode_value(&json!({"b": {"y": "1", "x": "2"}, "a": "0"})).unwrap();
    assert_eq!(
        canonical_value(&v).unwrap(),
        "{\"a\":\"0\",\"b\":{\"y\":\"1\",\"x\":\"2\"}}"
    );
}

#[test]
fn canonical_json_all_levels_sort() {
    let v = decode_value(&json!({"outer": {"y": "1", "x": "2"}})).unwrap();
    assert_eq!(
        canonical_json(&v).unwrap(),
        "{\"outer\":{\"x\":\"2\",\"y\":\"1\"}}"
    );
}

#[test]
fn canonical_astral_key_sort_code_point() {
    // U+E000 () must sort before U+10000 (𐀀) by code point.
    let v = decode_value(&json!({"\u{10000}": "astral", "\u{E000}": "bmp"})).unwrap();
    assert_eq!(
        canonical_value(&v).unwrap(),
        "{\"\u{E000}\":\"bmp\",\"\u{10000}\":\"astral\"}"
    );
}

#[test]
fn canonical_int_float_distinct() {
    assert_eq!(canonical_json(&Value::Int(1)).unwrap(), "1");
    assert_eq!(canonical_json(&Value::Float(1.0)).unwrap(), "1.0");
}

#[test]
fn canonical_nan_inf_failure() {
    assert_eq!(
        py_float_repr(f64::NAN).unwrap_err().code.as_str(),
        "NAN_OR_INF"
    );
    assert_eq!(
        py_float_repr(f64::INFINITY).unwrap_err().code.as_str(),
        "NAN_OR_INF"
    );
}

// ── py_float_repr edge cases (pinned to CPython repr) ─────────────────────────
#[test]
fn py_float_repr_matches_cpython() {
    let cases: &[(f64, &str)] = &[
        (0.1, "0.1"),
        (1e16, "1e+16"),
        (-0.0, "-0.0"),
        (0.0, "0.0"),
        (9999000000000000.0, "9999000000000000.0"),
        (5e-324, "5e-324"),
        (1.7976931348623157e308, "1.7976931348623157e+308"),
        (1.0, "1.0"),
        (1e-5, "1e-05"),
        (0.0001, "0.0001"),
        (3.5048, "3.5048"),
        (1.25e30, "1.25e+30"),
    ];
    for (f, want) in cases {
        assert_eq!(py_float_repr(*f).unwrap(), *want, "py_float_repr({f})");
    }
}

// ── plan ─────────────────────────────────────────────────────────────────────
#[test]
fn plan_null_binding_skip_propagates() {
    let ops = vec![
        OpSpec {
            id: "root".into(),
            parent: None,
            bind_field: None,
            relation_kind: None,
            policy: None,
        },
        OpSpec {
            id: "child".into(),
            parent: Some(0),
            bind_field: Some("next".into()),
            relation_kind: None,
            policy: None,
        },
    ];
    // root returns an object with no "next" field → child skipped
    let res = run_plan(None, &ops, |op, _| {
        if op.id == "root" {
            ExecOutcome::Ok(Value::Obj(vec![("x".into(), Value::Int(1))]))
        } else {
            ExecOutcome::Ok(Value::Null)
        }
    })
    .unwrap();
    assert_eq!(res.executed, vec!["root".to_string()]);
    assert_eq!(res.skipped, vec!["child".to_string()]);
}

#[test]
fn plan_fail_policy_raises() {
    let ops = vec![OpSpec {
        id: "a".into(),
        parent: None,
        bind_field: None,
        relation_kind: None,
        policy: None,
    }];
    let e = run_plan(None, &ops, |_, _| ExecOutcome::Error("boom".into())).unwrap_err();
    assert_eq!(e.code.as_str(), "OP_FAILED");
}

#[test]
fn plan_unknown_policy_fail_closed() {
    let ops = vec![OpSpec {
        id: "a".into(),
        parent: None,
        bind_field: None,
        relation_kind: None,
        policy: Some("wat".into()),
    }];
    let e = run_plan(None, &ops, |_, _| ExecOutcome::Ok(Value::Null)).unwrap_err();
    assert_eq!(e.code.as_str(), "UNKNOWN_POLICY");
}

// ── envelope ─────────────────────────────────────────────────────────────────
#[test]
fn envelope_version_checks() {
    assert!(validate_envelope(&json!({"specVersion": "1.0"}), "1.1", None, None).is_ok());
    assert!(validate_envelope(&json!({"specVersion": "1.1"}), "1.1", None, None).is_ok());
    assert_eq!(
        validate_envelope(&json!({"specVersion": "2.0"}), "1.1", None, None)
            .unwrap_err()
            .code
            .as_str(),
        "UNSUPPORTED_MAJOR"
    );
    assert_eq!(
        validate_envelope(&json!({"specVersion": "1.2"}), "1.1", None, None)
            .unwrap_err()
            .code
            .as_str(),
        "UNSUPPORTED_MINOR"
    );
    assert_eq!(
        validate_envelope(&json!({}), "1.1", None, None)
            .unwrap_err()
            .code
            .as_str(),
        "MISSING_VERSION"
    );
    assert_eq!(
        validate_envelope(&json!({"specVersion": "x"}), "1.1", None, None)
            .unwrap_err()
            .code
            .as_str(),
        "MALFORMED_VERSION"
    );
}

// ── guard ────────────────────────────────────────────────────────────────────
#[test]
fn guard_rejects_non_finite() {
    assert!(assert_portable(&Value::Obj(vec![("x".into(), Value::Float(f64::NAN))])).is_err());
    assert!(assert_portable(&Value::Arr(vec![Value::Int(1), Value::Str("ok".into())])).is_ok());
}

// ── codec / deep_equals ──────────────────────────────────────────────────────
#[test]
fn codec_int_float_distinction() {
    let a = decode_value(&json!(1)).unwrap();
    let b = decode_value(&json!({"float": 1})).unwrap();
    assert!(matches!(a, Value::Int(1)));
    assert!(matches!(b, Value::Float(_)));
    assert!(!deep_equals(&a, &b), "int 1 must not equal float 1.0");
}

// ── behavior (component-graph IR + run_behavior) ─────────────────────────────
struct OneShot {
    ok: Value,
}
impl ComponentExec for OneShot {
    fn exec(
        &mut self,
        component: &str,
        ports: &[(String, Value)],
        _bound: Option<&Value>,
    ) -> Option<ExecOutcome> {
        if component != "GetItem" {
            return None; // unknown component -> UNKNOWN_COMPONENT
        }
        // echo the evaluated PK port back as the outcome
        let pk = ports
            .iter()
            .find(|(k, _)| k == "PK")
            .map(|(_, v)| v.clone())
            .unwrap_or(Value::Null);
        let _ = &self.ok;
        Some(ExecOutcome::Ok(Value::Obj(vec![("echoedPK".into(), pk)])))
    }
}

#[test]
fn behavior_component_ref_wires_port_from_input() {
    let ir = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{
            "name": "get", "inputPorts": {"id": {"type": "string", "required": true}},
            "body": [{"id": "a", "component": "GetItem",
                      "ports": {"PK": {"concat": ["ID#", {"ref": ["id"]}]}}}],
            "output": {"ref": ["a"]},
            "plan": {"groups": [[0]], "concurrency": 1}
        }]
    });
    let mut h = OneShot { ok: Value::Null };
    let out = run_behavior(&ir, &mut h, &scope(&[("id", Value::Str("7".into()))]), None).unwrap();
    assert!(deep_equals(
        &out,
        &Value::Obj(vec![("echoedPK".into(), Value::Str("ID#7".into()))])
    ));
}

#[test]
fn behavior_unknown_component_fails_closed() {
    let ir = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "a", "component": "Nope", "ports": {}}], "output": {"ref": ["a"]}}]
    });
    let mut h = OneShot { ok: Value::Null };
    let err = run_behavior(&ir, &mut h, &[], None).unwrap_err();
    assert_eq!(err.code(), "UNKNOWN_COMPONENT");
}

#[test]
fn behavior_guard_rejects_non_string_component_and_unknown_op() {
    let bad_component = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "a", "component": ["not", "a", "string"], "ports": {}}], "output": null}]
    });
    assert!(assert_portable_component_graph(&bad_component).is_err());

    let unknown_op = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "a", "component": "GetItem", "ports": {"PK": {"bogusOp": [1, 2]}}}],
            "output": null}]
    });
    assert!(assert_portable_component_graph(&unknown_op).is_err());

    let good = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "g", "inputPorts": {},
            "body": [{"id": "a", "component": "GetItem",
                      "ports": {"PK": {"concat": ["ARTICLE#", {"ref": ["articleId"]}]}}}],
            "output": {"ref": ["a"]}}]
    });
    assert!(assert_portable_component_graph(&good).is_ok());
}

#[test]
fn behavior_guard_obj_arg_keys_are_data_not_operators() {
    // {obj:{...}} の arg key は data(expression-ir.md §3)。単一 data key の obj 構築や
    // operator と衝突する data key が未知 operator として誤拒否されないこと(bc#24 guard fix)。
    let single_key_obj = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {}, "body": [],
            "output": {"obj": {"posts": {"ref": ["a"]}}}}]
    });
    assert!(assert_portable_component_graph(&single_key_obj).is_ok());

    let colliding_key = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {}, "body": [],
            "output": {"obj": {"add": 1}}}]
    });
    assert!(assert_portable_component_graph(&colliding_key).is_ok());

    // ただし obj の「値」は式として検査される(未知 operator は引き続き fail-closed)。
    let bad_value = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {}, "body": [],
            "output": {"obj": {"k": {"bogusOp": [1]}}}}]
    });
    assert!(assert_portable_component_graph(&bad_value).is_err());
}

#[test]
fn behavior_guard_rejects_static_proto_obj_key() {
    // evaluator は実行時に FORBIDDEN_KEY で拒否する(expression-ir.md §2.3/§8)。
    // guard は静的にも拒否する(defense-in-depth — bc#24 audit fix)。
    let bad = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {}, "body": [],
            "output": {"obj": {"__proto__": 1}}}]
    });
    let err = assert_portable_component_graph(&bad).unwrap_err();
    assert!(err.message.contains("__proto__"), "got: {}", err.message);

    let bad_nested = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "a", "component": "GetItem",
                "ports": {"PK": {"obj": {"__proto__": {"ref": ["x"]}}}}}],
            "output": null}]
    });
    assert!(assert_portable_component_graph(&bad_nested).is_err());
}

#[test]
fn behavior_handler_ctx_carries_node_identity() {
    // behaviorVersion 2: run_behavior calls exec_ctx with {nodeId, component}.
    struct CtxEcho;
    impl ComponentExec for CtxEcho {
        fn exec(
            &mut self,
            component: &str,
            ports: &[(String, Value)],
            bound: Option<&Value>,
        ) -> Option<ExecOutcome> {
            self.exec_ctx("", component, ports, bound)
        }
        fn exec_ctx(
            &mut self,
            node_id: &str,
            component: &str,
            _ports: &[(String, Value)],
            _bound: Option<&Value>,
        ) -> Option<ExecOutcome> {
            Some(ExecOutcome::Ok(Value::Obj(vec![
                ("nodeId".into(), Value::Str(node_id.to_string())),
                ("component".into(), Value::Str(component.to_string())),
            ])))
        }
    }
    let ir = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "a", "component": "GetItem", "ports": {}}], "output": {"ref": ["a"]}}]
    });
    let mut h = CtxEcho;
    let out = run_behavior(&ir, &mut h, &[], None).unwrap();
    assert!(deep_equals(
        &out,
        &Value::Obj(vec![
            ("nodeId".into(), Value::Str("a".into())),
            ("component".into(), Value::Str("GetItem".into())),
        ])
    ));
}

#[test]
fn behavior_guard_accepts_v2_map_fields_and_fail_closes() {
    let good = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "b", "map": {
                "over": {"ref": ["xs"]}, "as": "$t", "component": "BatchGetItem",
                "when": {"ne": [{"ref": ["$t", "role"]}, "none"]},
                "into": "tag", "batched": true,
                "ports": {"PK": {"ref": ["$t", "id"]}}}}],
            "output": {"ref": ["b"]}}]
    });
    assert!(assert_portable_component_graph(&good).is_ok());

    let bad_when = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "b", "map": {
                "over": {"ref": ["xs"]}, "as": "$t", "component": "BatchGetItem",
                "when": {"bogusOp": [1]},
                "ports": {}}}],
            "output": null}]
    });
    assert!(assert_portable_component_graph(&bad_when).is_err());

    let bad_into = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "b", "map": {
                "over": {"ref": ["xs"]}, "as": "$t", "component": "BatchGetItem",
                "into": 42,
                "ports": {}}}],
            "output": null}]
    });
    assert!(assert_portable_component_graph(&bad_into).is_err());

    let bad_batched = json!({
        "irVersion": 1, "exprVersion": 2,
        "components": [{"name": "x", "inputPorts": {},
            "body": [{"id": "b", "map": {
                "over": {"ref": ["xs"]}, "as": "$t", "component": "BatchGetItem",
                "batched": "yes",
                "ports": {}}}],
            "output": null}]
    });
    assert!(assert_portable_component_graph(&bad_batched).is_err());
}