behavior-contracts 0.12.1 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/go/api_test.go ADDED
@@ -0,0 +1,675 @@
1
+ package dslcontracts
2
+
3
+ import (
4
+ "bytes"
5
+ "math"
6
+ "testing"
7
+ )
8
+
9
+ func parse(t *testing.T, s string) JNode {
10
+ t.Helper()
11
+ n, err := ParseJSONOrdered([]byte(s))
12
+ if err != nil {
13
+ t.Fatalf("parse %q: %v", s, err)
14
+ }
15
+ return n
16
+ }
17
+
18
+ func evalStr(t *testing.T, expr string) (Value, error) {
19
+ return EvaluateExpression(parse(t, expr), nil)
20
+ }
21
+
22
+ func exprCode(t *testing.T, expr string) string {
23
+ _, err := evalStr(t, expr)
24
+ if err == nil {
25
+ t.Fatalf("expected failure for %q, got value", expr)
26
+ }
27
+ ef, ok := err.(*ExprFailure)
28
+ if !ok {
29
+ t.Fatalf("expected ExprFailure, got %T", err)
30
+ }
31
+ return ef.Code
32
+ }
33
+
34
+ // ── expression ───────────────────────────────────────────────────────────────
35
+ func TestExprIntAdd(t *testing.T) {
36
+ v, err := evalStr(t, `{"add":[1,2]}`)
37
+ if err != nil || v != int64(3) {
38
+ t.Fatalf("got %v, %v", v, err)
39
+ }
40
+ }
41
+
42
+ func TestExprI64OverflowIsFailure(t *testing.T) {
43
+ if c := exprCode(t, `{"add":[{"int":"9223372036854775807"},{"int":"1"}]}`); c != "INT_OVERFLOW" {
44
+ t.Fatalf("got %s", c)
45
+ }
46
+ }
47
+
48
+ func TestExprIntLiteralBeyondI64(t *testing.T) {
49
+ if c := exprCode(t, `{"int":"99999999999999999999999"}`); c != "INT_OVERFLOW" {
50
+ t.Fatalf("got %s", c)
51
+ }
52
+ }
53
+
54
+ func TestExprModSignFollowsDividend(t *testing.T) {
55
+ // -7 % 2 == -1 (truncated). Confirms Go `%` matches spec.
56
+ v, err := evalStr(t, `{"mod":[{"int":"-7"},{"int":"2"}]}`)
57
+ if err != nil || v != int64(-1) {
58
+ t.Fatalf("-7%%2 got %v, %v (want -1)", v, err)
59
+ }
60
+ v2, _ := evalStr(t, `{"mod":[{"int":"7"},{"int":"-2"}]}`)
61
+ if v2 != int64(1) {
62
+ t.Fatalf("7%%-2 got %v (want 1)", v2)
63
+ }
64
+ }
65
+
66
+ func TestExprDivAlwaysFloat(t *testing.T) {
67
+ v, err := evalStr(t, `{"div":[6,2]}`)
68
+ if err != nil {
69
+ t.Fatal(err)
70
+ }
71
+ if f, ok := v.(float64); !ok || f != 3.0 {
72
+ t.Fatalf("got %v (%T)", v, v)
73
+ }
74
+ }
75
+
76
+ func TestExprDivByZero(t *testing.T) {
77
+ if c := exprCode(t, `{"div":[1,0]}`); c != "NAN_OR_INF" {
78
+ t.Fatalf("got %s", c)
79
+ }
80
+ }
81
+
82
+ func TestExprPrecisionLoss(t *testing.T) {
83
+ if c := exprCode(t, `{"div":[{"int":"9007199254740993"},1]}`); c != "PRECISION_LOSS" {
84
+ t.Fatalf("got %s", c)
85
+ }
86
+ }
87
+
88
+ func TestExprStringCompareCodePoint(t *testing.T) {
89
+ // 'Z'(0x5A) < 'a'(0x61)
90
+ v, err := evalStr(t, `{"lt":["Z","a"]}`)
91
+ if err != nil || v != true {
92
+ t.Fatalf("got %v, %v", v, err)
93
+ }
94
+ }
95
+
96
+ // float の順序比較は IEEE-754 の半順序。NaN は演算結果としては Failure だが、float 入力の束縛
97
+ // としては scope に載る(runner の f64 引数そのまま)。順序付け不能な対では lt/le/gt/ge すべて
98
+ // false = typed-native が直に出す IEEE 演算子と同じ値。
99
+ func nanScope() *Obj {
100
+ s := NewObj()
101
+ s.Set("x", math.NaN())
102
+ s.Set("y", 5.0)
103
+ return s
104
+ }
105
+
106
+ func TestExprNaNIsUnordered(t *testing.T) {
107
+ scope := nanScope()
108
+ for _, op := range []string{"lt", "le", "gt", "ge"} {
109
+ for _, ab := range [][2]string{{"x", "y"}, {"y", "x"}, {"x", "x"}} {
110
+ expr := `{"` + op + `":[{"ref":["` + ab[0] + `"]},{"ref":["` + ab[1] + `"]}]}`
111
+ v, err := EvaluateExpression(parse(t, expr), scope)
112
+ if err != nil || v != false {
113
+ t.Fatalf("%s: got %v, %v (want false)", expr, v, err)
114
+ }
115
+ }
116
+ }
117
+ }
118
+
119
+ func TestExprFiniteFloatsStayTotallyOrdered(t *testing.T) {
120
+ scope := NewObj()
121
+ scope.Set("a", 1.5)
122
+ scope.Set("b", 2.5)
123
+ for expr, want := range map[string]bool{
124
+ `{"lt":[{"ref":["a"]},{"ref":["b"]}]}`: true,
125
+ `{"le":[{"ref":["a"]},{"ref":["a"]}]}`: true,
126
+ `{"ge":[{"ref":["b"]},{"ref":["a"]}]}`: true,
127
+ `{"gt":[{"ref":["a"]},{"ref":["b"]}]}`: false,
128
+ } {
129
+ v, err := EvaluateExpression(parse(t, expr), scope)
130
+ if err != nil || v != want {
131
+ t.Fatalf("%s: got %v, %v (want %v)", expr, v, err, want)
132
+ }
133
+ }
134
+ }
135
+
136
+ // 実行時 eq/ne は IEEE の等価(NaN != NaN)。DeepEquals の「両方 NaN を等しい」は conformance
137
+ // 照合の規則(PROTOCOL §4.1)であって実行時の意味論ではない。
138
+ func TestExprEqNeFollowIEEEOnNaN(t *testing.T) {
139
+ scope := nanScope()
140
+ for expr, want := range map[string]bool{
141
+ `{"eq":[{"ref":["x"]},{"ref":["x"]}]}`: false,
142
+ `{"ne":[{"ref":["x"]},{"ref":["x"]}]}`: true,
143
+ } {
144
+ v, err := EvaluateExpression(parse(t, expr), scope)
145
+ if err != nil || v != want {
146
+ t.Fatalf("%s: got %v, %v (want %v)", expr, v, err, want)
147
+ }
148
+ }
149
+ if !DeepEquals(math.NaN(), math.NaN()) {
150
+ t.Fatal("DeepEquals (the conformance judgment helper) must keep treating both-NaN as equal")
151
+ }
152
+ }
153
+
154
+ // 半順序では ¬(a>b) ≠ (a≤b) — `not(<float 順序比較>)` は比較演算子に畳めない(int は畳める)。
155
+ func TestExprNotGtIsNotLeOnFloats(t *testing.T) {
156
+ scope := nanScope()
157
+ v, err := EvaluateExpression(parse(t, `{"not":[{"gt":[{"ref":["x"]},{"ref":["y"]}]}]}`), scope)
158
+ if err != nil || v != true {
159
+ t.Fatalf("not(gt(NaN,5.0)): got %v, %v (want true)", v, err)
160
+ }
161
+ v, err = EvaluateExpression(parse(t, `{"le":[{"ref":["x"]},{"ref":["y"]}]}`), scope)
162
+ if err != nil || v != false {
163
+ t.Fatalf("le(NaN,5.0): got %v, %v (want false)", v, err)
164
+ }
165
+ }
166
+
167
+ func TestExprAndShortCircuit(t *testing.T) {
168
+ // right side would be UNKNOWN_BINDING but is not evaluated
169
+ v, err := evalStr(t, `{"and":[false,{"ref":["nope"]}]}`)
170
+ if err != nil || v != false {
171
+ t.Fatalf("got %v, %v", v, err)
172
+ }
173
+ }
174
+
175
+ func TestExprUnknownOp(t *testing.T) {
176
+ if c := exprCode(t, `{"frobnicate":[1]}`); c != "UNKNOWN_OP" {
177
+ t.Fatalf("got %s", c)
178
+ }
179
+ }
180
+
181
+ // ── template ─────────────────────────────────────────────────────────────────
182
+ func params(pairs ...interface{}) *Obj {
183
+ o := NewObj()
184
+ for i := 0; i < len(pairs); i += 2 {
185
+ o.Set(pairs[i].(string), pairs[i+1])
186
+ }
187
+ return o
188
+ }
189
+
190
+ func TestTemplateStringify(t *testing.T) {
191
+ got, err := RenderTemplate("N#{n}", params("n", int64(42)))
192
+ if err != nil || got != "N#42" {
193
+ t.Fatalf("got %q, %v", got, err)
194
+ }
195
+ got2, _ := RenderTemplate("F#{flag}", params("flag", true))
196
+ if got2 != "F#True" {
197
+ t.Fatalf("bool stringify got %q (want F#True)", got2)
198
+ }
199
+ }
200
+
201
+ func TestTemplateMissingKeyFailure(t *testing.T) {
202
+ _, err := RenderTemplate("USER#{userId}", NewObj())
203
+ if tf, ok := err.(*TemplateFailure); !ok || tf.Code != "UNBOUND_PARAM" {
204
+ t.Fatalf("got %v", err)
205
+ }
206
+ }
207
+
208
+ func TestTemplateNullParamFailure(t *testing.T) {
209
+ _, err := RenderTemplate("USER#{userId}", params("userId", nil))
210
+ if tf, ok := err.(*TemplateFailure); !ok || tf.Code != "UNBOUND_PARAM" {
211
+ t.Fatalf("got %v", err)
212
+ }
213
+ }
214
+
215
+ func TestTemplateEmptyBracesLiteral(t *testing.T) {
216
+ got, err := RenderTemplate("a{}b", NewObj())
217
+ if err != nil || got != "a{}b" {
218
+ t.Fatalf("got %q, %v", got, err)
219
+ }
220
+ }
221
+
222
+ // ── canonical ────────────────────────────────────────────────────────────────
223
+ func decode(t *testing.T, s string) Value {
224
+ t.Helper()
225
+ v, err := DecodeValue(parse(t, s))
226
+ if err != nil {
227
+ t.Fatalf("decode %q: %v", s, err)
228
+ }
229
+ return v
230
+ }
231
+
232
+ func TestCanonicalTopLevelSortOnly(t *testing.T) {
233
+ v := decode(t, `{"b":{"y":"1","x":"2"},"a":"0"}`)
234
+ got, _ := CanonicalValue(v)
235
+ want := `{"a":"0","b":{"y":"1","x":"2"}}`
236
+ if got != want {
237
+ t.Fatalf("got %s want %s", got, want)
238
+ }
239
+ }
240
+
241
+ func TestCanonicalJSONAllLevels(t *testing.T) {
242
+ v := decode(t, `{"outer":{"y":"1","x":"2"}}`)
243
+ got, _ := CanonicalJSON(v)
244
+ want := `{"outer":{"x":"2","y":"1"}}`
245
+ if got != want {
246
+ t.Fatalf("got %s want %s", got, want)
247
+ }
248
+ }
249
+
250
+ func TestCanonicalAstralKeySort(t *testing.T) {
251
+ // U+E000 must sort before U+10000 by code point.
252
+ v := decode(t, `{"𐀀":"astral","":"bmp"}`)
253
+ got, _ := CanonicalValue(v)
254
+ want := "{\"\":\"bmp\",\"\U00010000\":\"astral\"}"
255
+ if got != want {
256
+ t.Fatalf("got %q want %q", got, want)
257
+ }
258
+ }
259
+
260
+ func TestCanonicalIntFloatDistinct(t *testing.T) {
261
+ i, _ := CanonicalJSON(int64(1))
262
+ f, _ := CanonicalJSON(float64(1.0))
263
+ if i != "1" || f != "1.0" {
264
+ t.Fatalf("int=%s float=%s", i, f)
265
+ }
266
+ }
267
+
268
+ func TestCanonicalNaNInfFailure(t *testing.T) {
269
+ if _, err := PyFloatRepr(math.NaN()); err == nil {
270
+ t.Fatal("NaN should fail")
271
+ }
272
+ if _, err := PyFloatRepr(math.Inf(1)); err == nil {
273
+ t.Fatal("Inf should fail")
274
+ }
275
+ }
276
+
277
+ // py_float_repr edge cases pinned to CPython repr.
278
+ func TestPyFloatReprMatchesCPython(t *testing.T) {
279
+ cases := []struct {
280
+ f float64
281
+ want string
282
+ }{
283
+ {0.1, "0.1"},
284
+ {1e16, "1e+16"},
285
+ {math.Copysign(0, -1), "-0.0"},
286
+ {0.0, "0.0"},
287
+ {9999000000000000.0, "9999000000000000.0"},
288
+ {5e-324, "5e-324"},
289
+ {1.7976931348623157e308, "1.7976931348623157e+308"},
290
+ {1.0, "1.0"},
291
+ {1e-5, "1e-05"},
292
+ {0.0001, "0.0001"},
293
+ {1.25e30, "1.25e+30"},
294
+ }
295
+ for _, c := range cases {
296
+ got, err := PyFloatRepr(c.f)
297
+ if err != nil || got != c.want {
298
+ t.Errorf("PyFloatRepr(%v) = %q, %v; want %q", c.f, got, err, c.want)
299
+ }
300
+ }
301
+ }
302
+
303
+ // ── plan ─────────────────────────────────────────────────────────────────────
304
+ func TestPlanNullBindingSkip(t *testing.T) {
305
+ ops := []OpSpec{
306
+ {ID: "root", Parent: -1},
307
+ {ID: "child", Parent: 0, BindField: "next", HasBindField: true},
308
+ }
309
+ res, err := RunPlan(nil, ops, func(op OpSpec, _ Value) ExecOutcome {
310
+ if op.ID == "root" {
311
+ return OkOutcome(params("x", int64(1)))
312
+ }
313
+ return OkOutcome(nil)
314
+ })
315
+ if err != nil {
316
+ t.Fatal(err)
317
+ }
318
+ if len(res.Executed) != 1 || res.Executed[0] != "root" {
319
+ t.Fatalf("executed %v", res.Executed)
320
+ }
321
+ if len(res.Skipped) != 1 || res.Skipped[0] != "child" {
322
+ t.Fatalf("skipped %v", res.Skipped)
323
+ }
324
+ }
325
+
326
+ func TestPlanFailPolicy(t *testing.T) {
327
+ ops := []OpSpec{{ID: "a", Parent: -1}}
328
+ _, err := RunPlan(nil, ops, func(op OpSpec, _ Value) ExecOutcome { return ErrOutcome("boom") })
329
+ if pf, ok := err.(*PlanFailure); !ok || pf.Code != "OP_FAILED" {
330
+ t.Fatalf("got %v", err)
331
+ }
332
+ }
333
+
334
+ func TestPlanUnknownPolicyEmptyString(t *testing.T) {
335
+ // present-but-empty policy is fail-closed, NOT defaulted to "fail".
336
+ ops := []OpSpec{{ID: "a", Parent: -1, Policy: "", HasPolicy: true}}
337
+ _, err := RunPlan(nil, ops, func(op OpSpec, _ Value) ExecOutcome { return OkOutcome(nil) })
338
+ if pf, ok := err.(*PlanFailure); !ok || pf.Code != "UNKNOWN_POLICY" {
339
+ t.Fatalf("got %v", err)
340
+ }
341
+ }
342
+
343
+ func TestPlanAbsentPolicyDefaultsFail(t *testing.T) {
344
+ // absent policy defaults to "fail": a failing op raises OP_FAILED.
345
+ ops := []OpSpec{{ID: "a", Parent: -1}} // HasPolicy=false
346
+ _, err := RunPlan(nil, ops, func(op OpSpec, _ Value) ExecOutcome { return ErrOutcome("x") })
347
+ if pf, ok := err.(*PlanFailure); !ok || pf.Code != "OP_FAILED" {
348
+ t.Fatalf("got %v", err)
349
+ }
350
+ }
351
+
352
+ // ── envelope ─────────────────────────────────────────────────────────────────
353
+ func TestEnvelopeVersionChecks(t *testing.T) {
354
+ env := func(v string) *Obj { return params("specVersion", v) }
355
+ if err := ValidateEnvelope(env("1.0"), "1.1", "", ""); err != nil {
356
+ t.Fatalf("1.0 should be ok: %v", err)
357
+ }
358
+ if err := ValidateEnvelope(env("2.0"), "1.1", "", ""); err.(*EnvelopeFailure).Code != "UNSUPPORTED_MAJOR" {
359
+ t.Fatalf("got %v", err)
360
+ }
361
+ if err := ValidateEnvelope(env("1.2"), "1.1", "", ""); err.(*EnvelopeFailure).Code != "UNSUPPORTED_MINOR" {
362
+ t.Fatalf("got %v", err)
363
+ }
364
+ if err := ValidateEnvelope(NewObj(), "1.1", "", ""); err.(*EnvelopeFailure).Code != "MISSING_VERSION" {
365
+ t.Fatalf("got %v", err)
366
+ }
367
+ if err := ValidateEnvelope(env("x"), "1.1", "", ""); err.(*EnvelopeFailure).Code != "MALFORMED_VERSION" {
368
+ t.Fatalf("got %v", err)
369
+ }
370
+ }
371
+
372
+ // ── guard ────────────────────────────────────────────────────────────────────
373
+ func TestGuardRejectsNonFinite(t *testing.T) {
374
+ if err := AssertPortable(params("x", math.NaN())); err == nil {
375
+ t.Fatal("NaN should be rejected")
376
+ }
377
+ if err := AssertPortable([]Value{int64(1), "ok"}); err != nil {
378
+ t.Fatalf("clean value rejected: %v", err)
379
+ }
380
+ }
381
+
382
+ // ── codec / deep-equals ──────────────────────────────────────────────────────
383
+ func TestCodecIntFloatDistinction(t *testing.T) {
384
+ a := decode(t, `1`)
385
+ b := decode(t, `{"float":1}`)
386
+ if _, ok := a.(int64); !ok {
387
+ t.Fatalf("bare 1 should be int64, got %T", a)
388
+ }
389
+ if _, ok := b.(float64); !ok {
390
+ t.Fatalf("{float:1} should be float64, got %T", b)
391
+ }
392
+ if DeepEquals(a, b) {
393
+ t.Fatal("int 1 must not equal float 1.0")
394
+ }
395
+ }
396
+
397
+ // ── conformance runner smoke test ─────────────────────────────────────────────
398
+ func TestConformanceRunnerAllPass(t *testing.T) {
399
+ var buf bytes.Buffer
400
+ // vectors live at <repo>/conformance/vectors; this test file is at <repo>/go.
401
+ failed, mismatch := RunConformance("../conformance/vectors", &buf)
402
+ t.Log(buf.String())
403
+ if mismatch {
404
+ t.Fatal("unexpected version mismatch")
405
+ }
406
+ if failed != 0 {
407
+ t.Fatalf("%d vectors failed", failed)
408
+ }
409
+ if !bytes.Contains(buf.Bytes(), []byte("247 passed, 0 failed")) {
410
+ t.Fatalf("expected 247 passed:\n%s", buf.String())
411
+ }
412
+ }
413
+
414
+ // ── behavior (component-graph IR + RunBehavior) ──────────────────────────────
415
+ type echoHandler struct{}
416
+
417
+ func (echoHandler) Exec(component string, ports *Obj, _ Value) (ExecOutcome, bool) {
418
+ if component != "GetItem" {
419
+ return ExecOutcome{}, false // unknown component -> UNKNOWN_COMPONENT
420
+ }
421
+ pk, _ := ports.Get("PK")
422
+ out := NewObj()
423
+ out.Set("echoedPK", pk)
424
+ return OkOutcome(out), true
425
+ }
426
+
427
+ func TestRunBehaviorComponentRef(t *testing.T) {
428
+ ir := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
429
+ {"name":"get","inputPorts":{"id":{"type":"string","required":true}},
430
+ "body":[{"id":"a","component":"GetItem","ports":{"PK":{"concat":["ID#",{"ref":["id"]}]}}}],
431
+ "output":{"ref":["a"]},"plan":{"groups":[[0]],"concurrency":1}}]}`)
432
+ input := NewObj()
433
+ input.Set("id", "7")
434
+ out, err := RunBehavior(ir, echoHandler{}, input, "")
435
+ if err != nil {
436
+ t.Fatalf("unexpected error: %v", err)
437
+ }
438
+ want := NewObj()
439
+ want.Set("echoedPK", "ID#7")
440
+ if !DeepEquals(out, want) {
441
+ t.Fatalf("got %s", EncodeValue(out))
442
+ }
443
+ }
444
+
445
+ func TestRunBehaviorUnknownComponentFailsClosed(t *testing.T) {
446
+ ir := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
447
+ {"name":"x","inputPorts":{},"body":[{"id":"a","component":"Nope","ports":{}}],"output":{"ref":["a"]}}]}`)
448
+ _, err := RunBehavior(ir, echoHandler{}, NewObj(), "")
449
+ bf, ok := err.(*BehaviorFailure)
450
+ if !ok || bf.Code != "UNKNOWN_COMPONENT" {
451
+ t.Fatalf("expected UNKNOWN_COMPONENT, got %v", err)
452
+ }
453
+ }
454
+
455
+ func TestAssertPortableComponentGraph(t *testing.T) {
456
+ badComponent := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
457
+ {"name":"x","inputPorts":{},"body":[{"id":"a","component":["not","string"],"ports":{}}],"output":null}]}`)
458
+ if err := AssertPortableComponentGraph(badComponent); err == nil {
459
+ t.Fatal("expected error for non-string component")
460
+ }
461
+ badOp := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
462
+ {"name":"x","inputPorts":{},"body":[{"id":"a","component":"GetItem","ports":{"PK":{"bogusOp":[1,2]}}}],"output":null}]}`)
463
+ if err := AssertPortableComponentGraph(badOp); err == nil {
464
+ t.Fatal("expected error for unknown operator")
465
+ }
466
+ good := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
467
+ {"name":"g","inputPorts":{},"body":[{"id":"a","component":"GetItem","ports":{"PK":{"concat":["ARTICLE#",{"ref":["articleId"]}]}},"portSchemas":{"PK":{"type":"string","required":true}}}],"output":{"ref":["a"]}}]}`)
468
+ if err := AssertPortableComponentGraph(good); err != nil {
469
+ t.Fatalf("unexpected error for well-formed graph: %v", err)
470
+ }
471
+ }
472
+
473
+ func TestAssertPortableComponentGraphObjArgKeysAreData(t *testing.T) {
474
+ // {obj:{...}} の arg key は data(expression-ir.md §3)。単一 data key の obj 構築や
475
+ // operator と衝突する data key が未知 operator として誤拒否されないこと(bc#24 guard fix)。
476
+ singleKey := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
477
+ {"name":"x","inputPorts":{},"body":[],"output":{"obj":{"posts":{"ref":["a"]}}}}]}`)
478
+ if err := AssertPortableComponentGraph(singleKey); err != nil {
479
+ t.Fatalf("unexpected error for single-key obj construction: %v", err)
480
+ }
481
+ collidingKey := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
482
+ {"name":"x","inputPorts":{},"body":[],"output":{"obj":{"add":1}}}]}`)
483
+ if err := AssertPortableComponentGraph(collidingKey); err != nil {
484
+ t.Fatalf("unexpected error for operator-colliding data key: %v", err)
485
+ }
486
+ // ただし obj の「値」は式として検査される(未知 operator は引き続き fail-closed)。
487
+ badValue := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
488
+ {"name":"x","inputPorts":{},"body":[],"output":{"obj":{"k":{"bogusOp":[1]}}}}]}`)
489
+ if err := AssertPortableComponentGraph(badValue); err == nil {
490
+ t.Fatal("expected error for unknown operator inside obj value")
491
+ }
492
+ }
493
+
494
+ func TestAssertPortableComponentGraphRejectsStaticProtoObjKey(t *testing.T) {
495
+ // evaluator は実行時に FORBIDDEN_KEY で拒否する(expression-ir.md §2.3/§8)。
496
+ // guard は静的にも拒否する(defense-in-depth — bc#24 audit fix)。
497
+ bad := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
498
+ {"name":"x","inputPorts":{},"body":[],"output":{"obj":{"__proto__":1}}}]}`)
499
+ err := AssertPortableComponentGraph(bad)
500
+ if err == nil {
501
+ t.Fatal("expected error for static __proto__ obj key")
502
+ }
503
+ if !bytes.Contains([]byte(err.Error()), []byte("__proto__")) {
504
+ t.Fatalf("error should name __proto__, got: %v", err)
505
+ }
506
+ badNested := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
507
+ {"name":"x","inputPorts":{},"body":[{"id":"a","component":"GetItem",
508
+ "ports":{"PK":{"obj":{"__proto__":{"ref":["x"]}}}}}],"output":null}]}`)
509
+ if err := AssertPortableComponentGraph(badNested); err == nil {
510
+ t.Fatal("expected error for nested static __proto__ obj key")
511
+ }
512
+ }
513
+
514
+ // ── behavior v2 (bc#22): handler ctx + guard vocabulary ──────────────────────
515
+ type ctxEchoHandler struct{}
516
+
517
+ func (ctxEchoHandler) Exec(component string, ports *Obj, bound Value) (ExecOutcome, bool) {
518
+ return ctxEchoHandler{}.ExecCtx("", component, ports, bound)
519
+ }
520
+
521
+ func (ctxEchoHandler) ExecCtx(nodeID, component string, _ *Obj, _ Value) (ExecOutcome, bool) {
522
+ out := NewObj()
523
+ out.Set("nodeId", nodeID)
524
+ out.Set("component", component)
525
+ return OkOutcome(out), true
526
+ }
527
+
528
+ func TestRunBehaviorHandlerCtxCarriesNodeIdentity(t *testing.T) {
529
+ ir := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
530
+ {"name":"x","inputPorts":{},"body":[{"id":"a","component":"GetItem","ports":{}}],"output":{"ref":["a"]}}]}`)
531
+ out, err := RunBehavior(ir, ctxEchoHandler{}, NewObj(), "")
532
+ if err != nil {
533
+ t.Fatalf("unexpected error: %v", err)
534
+ }
535
+ want := NewObj()
536
+ want.Set("nodeId", "a")
537
+ want.Set("component", "GetItem")
538
+ if !DeepEquals(out, want) {
539
+ t.Fatalf("got %s", EncodeValue(out))
540
+ }
541
+ }
542
+
543
+ func TestAssertPortableComponentGraphV2MapFields(t *testing.T) {
544
+ good := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
545
+ {"name":"x","inputPorts":{},"body":[{"id":"b","map":{
546
+ "over":{"ref":["xs"]},"as":"$t","component":"BatchGetItem",
547
+ "when":{"ne":[{"ref":["$t","role"]},"none"]},"into":"tag","batched":true,
548
+ "ports":{"PK":{"ref":["$t","id"]}},"portSchemas":{"PK":{"type":"string","required":true}}}}],"output":{"ref":["b"]}}]}`)
549
+ if err := AssertPortableComponentGraph(good); err != nil {
550
+ t.Fatalf("unexpected error for v2 map fields: %v", err)
551
+ }
552
+ badWhen := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
553
+ {"name":"x","inputPorts":{},"body":[{"id":"b","map":{
554
+ "over":{"ref":["xs"]},"as":"$t","component":"BatchGetItem",
555
+ "when":{"bogusOp":[1]},"ports":{}}}],"output":null}]}`)
556
+ if err := AssertPortableComponentGraph(badWhen); err == nil {
557
+ t.Fatal("expected error for unknown operator in when")
558
+ }
559
+ badInto := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
560
+ {"name":"x","inputPorts":{},"body":[{"id":"b","map":{
561
+ "over":{"ref":["xs"]},"as":"$t","component":"BatchGetItem",
562
+ "into":42,"ports":{}}}],"output":null}]}`)
563
+ if err := AssertPortableComponentGraph(badInto); err == nil {
564
+ t.Fatal("expected error for non-string into")
565
+ }
566
+ badBatched := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
567
+ {"name":"x","inputPorts":{},"body":[{"id":"b","map":{
568
+ "over":{"ref":["xs"]},"as":"$t","component":"BatchGetItem",
569
+ "batched":"yes","ports":{}}}],"output":null}]}`)
570
+ if err := AssertPortableComponentGraph(badBatched); err == nil {
571
+ t.Fatal("expected error for non-bool batched")
572
+ }
573
+ }
574
+
575
+ // #319: the conform {map:V} arm fails closed on an own "__proto__" key, as every object-building path does.
576
+ type protoLeafHandler struct{}
577
+
578
+ func (protoLeafHandler) Exec(component string, ports *Obj, bound Value) (ExecOutcome, bool) {
579
+ inner := NewObj()
580
+ inner.Set("doc1", "read")
581
+ evil := NewObj()
582
+ evil.Set("mallory", "admin")
583
+ out := NewObj()
584
+ out.Set("alice", inner)
585
+ out.Set("__proto__", evil)
586
+ return OkOutcome(out), true
587
+ }
588
+
589
+ func TestRunBehaviorMapOutTypeForbiddenKeyFailsClosed(t *testing.T) {
590
+ ir := parse(t, `{"irVersion":2,"exprVersion":2,"components":[
591
+ {"name":"c","body":[{"id":"g","component":"Get","ports":{},"outType":{"map":{"map":"string"}}}],
592
+ "output":{"ref":["g"]},"plan":{"groups":[[0]],"concurrency":1}}]}`)
593
+ _, err := RunBehavior(ir, protoLeafHandler{}, NewObj(), "")
594
+ ef, ok := err.(*ExprFailure)
595
+ if !ok || ef.Code != "FORBIDDEN_KEY" {
596
+ t.Fatalf("want ExprFailure FORBIDDEN_KEY, got %T %v", err, err)
597
+ }
598
+ }
599
+
600
+ // #318: a non-string dedupeKey's identity is the canonical identity (CanonicalJSON) in every runtime.
601
+ func TestFanoutDedupDropNonStringKeyUsesCanonicalIdentity(t *testing.T) {
602
+ keep := func(keys ...Value) ([]int64, error) {
603
+ rows := make([]Value, len(keys))
604
+ for i, k := range keys {
605
+ o := NewObj()
606
+ o.Set("id", k)
607
+ o.Set("i", int64(i))
608
+ rows[i] = o
609
+ }
610
+ out, err := fanoutDedupDrop(rows, "id", "dangling", nil)
611
+ if err != nil {
612
+ return nil, err
613
+ }
614
+ var idx []int64
615
+ for _, r := range out {
616
+ v, _ := r.(*Obj).Get("i")
617
+ idx = append(idx, v.(int64))
618
+ }
619
+ return idx, nil
620
+ }
621
+ obj := func(kv ...any) *Obj {
622
+ o := NewObj()
623
+ for i := 0; i < len(kv); i += 2 {
624
+ o.Set(kv[i].(string), kv[i+1])
625
+ }
626
+ return o
627
+ }
628
+ cases := []struct {
629
+ keys []Value
630
+ want []int64
631
+ }{
632
+ {[]Value{[]Value{"a b", "c"}, []Value{"a", "b c"}, []Value{"a b", "c"}}, []int64{0, 1}},
633
+ {[]Value{int64(1), float64(1), int64(1)}, []int64{0, 1}},
634
+ {[]Value{obj("a", int64(1), "b", int64(2)), obj("b", int64(2), "a", int64(1)), obj("a", int64(1), "b", int64(3))}, []int64{0, 2}},
635
+ }
636
+ for _, c := range cases {
637
+ got, err := keep(c.keys...)
638
+ if err != nil || len(got) != len(c.want) || got[0] != c.want[0] || got[1] != c.want[1] {
639
+ t.Fatalf("keys %s: got %v (err %v), want %v", EncodeValue(c.keys), got, err, c.want)
640
+ }
641
+ }
642
+ if _, err := keep(math.NaN(), math.Inf(1)); err == nil {
643
+ t.Fatal("a NaN/Inf dedupe key must fail closed")
644
+ }
645
+ }
646
+
647
+ // #322: only DECLARED input ports are bound.
648
+ type realHandler struct{}
649
+
650
+ func (realHandler) Exec(component string, ports *Obj, bound Value) (ExecOutcome, bool) {
651
+ return OkOutcome("real"), true
652
+ }
653
+
654
+ func TestRunBehaviorUndeclaredInputKeyIsNotBound(t *testing.T) {
655
+ doc := func(output string) JNode {
656
+ return parse(t, `{"irVersion":2,"exprVersion":2,"components":[
657
+ {"name":"c","inputPorts":{"id":{"type":"string","required":true}},
658
+ "body":[{"id":"n0","component":"Get","ports":{"PK":{"ref":["id"]}}}],
659
+ "output":`+output+`,"plan":{"groups":[[0]],"concurrency":1}}]}`)
660
+ }
661
+ in := func(k string) *Obj {
662
+ o := NewObj()
663
+ o.Set("id", "1")
664
+ o.Set(k, "injected")
665
+ return o
666
+ }
667
+ _, err := RunBehavior(doc(`{"ref":["extra"]}`), realHandler{}, in("extra"), "")
668
+ if ef, ok := err.(*ExprFailure); !ok || ef.Code != "UNKNOWN_BINDING" {
669
+ t.Fatalf("undeclared key must be unbound: got %T %v", err, err)
670
+ }
671
+ out, err := RunBehavior(doc(`{"ref":["n0"]}`), realHandler{}, in("n0"), "")
672
+ if err != nil || out != "real" {
673
+ t.Fatalf("an input key named like a node id must not shadow it: got %v (err %v)", out, err)
674
+ }
675
+ }