Files
archie/internal/domain/eda/expr/expr_test.go
T
sam 7e34fcb598 feat(eda): CEL expression environment (compile/validate at load, evaluate at dispatch)
Sixth slice of docs/prds/eda-playbook-engine.md (t2db.14): the
internal/domain/eda/expr package implementing the resolved open question 1
(CEL decision), standalone -- no coordinator/dispatch yet, mirroring how
t2db.13 built ModuleRegistry before any consumer.

- NewEnv: CEL env declaring the two context roots (event + actions, both
  map(string, dyn)) with DefaultCostLimit (100,000, tunable per J5).
- Compile: parses/type-checks an expression string; syntax error, unknown
  root (anything other than event/actions), or type error is a returned
  error -- the reject-at-load entry point the playbook loader and lint
  tool will share.
- Eval: evaluates a compiled program against a dispatch-time Context;
  missing-field/wrong-type/cost-limit errors are returned, never panics.
  No recover() wrapper: CEL is panic-free by design, verified by the
  hostile-data tests (5000-deep map, no panic). CEL's ref.Val wrappers
  (types.Bool etc.) are unwrapped to native Go values.

Dependency: cel.dev/cel-go v0.32.0 (direct), the only new dependency,
already vetted in the resolved doc's vetting record -- no re-vet.

Tests (table-driven, verified against real CEL semantics, not guessed):
valid boolean against event fields; syntax error at compile; unknown root
rejected at compile naming the root; missing event field errors not
panics (== on a missing key evaluates false -- verified CEL semantics);
has() presence macro; actions context reads; deep-nested hostile data
error-free or false without panic; cost-limit enforcement proven by
aborting a macro expression under a tiny limit (CEL's cost model accrues
on map/filter iteration, not field reads -- verified by probing).

task check clean (113/113 UI, exit 0).
2026-09-03 04:01:21 +10:00

191 lines
5.8 KiB
Go

package expr
import (
"strings"
"testing"
"cel.dev/cel-go/cel"
"cel.dev/cel-go/common/types/ref"
)
// TestCompileEvalValidBooleanAgainstEvent is the happy path: a boolean
// condition reading an event field compiles and evaluates correctly.
func TestCompileEvalValidBooleanAgainstEvent(t *testing.T) {
env := NewEnv()
prg, err := env.Compile(`event.label == "bugfix"`)
if err != nil {
t.Fatalf("Compile: %v", err)
}
got, err := env.Eval(prg, Context{
Event: map[string]any{"label": "bugfix", "priority": 3},
})
if err != nil {
t.Fatalf("Eval: %v", err)
}
if b, ok := got.(bool); !ok || !b {
t.Fatalf("Eval = %#v, want true", got)
}
}
// TestCompileSyntaxErrorIsReturned: a syntax error is a Compile-time error,
// never a panic.
func TestCompileSyntaxErrorIsReturned(t *testing.T) {
env := NewEnv()
_, err := env.Compile(`event.label == `)
if err == nil {
t.Fatal("Compile(syntax error) = nil, want error")
}
}
// TestCompileUnknownRootIsReturned: a reference to a root other than
// event/actions is rejected at compile time -- the reject-at-load rule.
func TestCompileUnknownRootIsReturned(t *testing.T) {
env := NewEnv()
_, err := env.Compile(`foo.bar == 1`)
if err == nil {
t.Fatal("Compile(unknown root) = nil, want error")
}
if !strings.Contains(err.Error(), "'foo'") {
t.Errorf("Compile(unknown root) error = %q, want it to name the root", err.Error())
}
}
// TestEvalMissingEventFieldNoPanic: evaluating against a missing event field
// returns an error, never panics (CEL's documented behavior).
func TestEvalMissingEventFieldNoPanic(t *testing.T) {
env := NewEnv()
prg, err := env.Compile(`event.missing == "x"`)
if err != nil {
t.Fatalf("Compile: %v", err)
}
_, err = env.Eval(prg, Context{Event: map[string]any{}})
if err == nil {
t.Fatal("Eval(missing field) = nil error, want error (not panic)")
}
}
// TestEvalHasMacroPresence: has() covers the missing-key case positively.
func TestEvalHasMacroPresence(t *testing.T) {
env := NewEnv()
prg, err := env.Compile(`has(event.label)`)
if err != nil {
t.Fatalf("Compile: %v", err)
}
got, err := env.Eval(prg, Context{Event: map[string]any{}})
if err != nil {
t.Fatalf("Eval: %v", err)
}
if b, ok := got.(bool); !ok || b {
t.Fatalf("has() on missing field = %#v, want false", got)
}
}
// TestEvalActionsContext: prior-action results read via actions.<id>.result.
func TestEvalActionsContext(t *testing.T) {
env := NewEnv()
prg, err := env.Compile(`actions.a.result.written == true`)
if err != nil {
t.Fatalf("Compile: %v", err)
}
got, err := env.Eval(prg, Context{
Actions: map[string]map[string]any{
"a": {"result": map[string]any{"written": true}},
},
})
if err != nil {
t.Fatalf("Eval: %v", err)
}
if b, ok := got.(bool); !ok || !b {
t.Fatalf("Eval = %#v, want true", got)
}
}
// TestEvalDeepNestedNoPanic: hostile deep nested access errors cleanly.
func TestEvalDeepNestedNoPanic(t *testing.T) {
env := NewEnv()
prg, err := env.Compile(`event.a.b.c.d == 1`)
if err != nil {
t.Fatalf("Compile: %v", err)
}
_, err = env.Eval(prg, Context{Event: map[string]any{}})
if err == nil {
t.Fatal("Eval(deep missing) = nil error, want error")
}
}
// TestCompileOverCostLimitRejected: an expression that would exceed the cost
// limit is rejected at evaluation, not silently truncated. Verified CEL
// semantics: cost limits abort with "actual cost limit exceeded" on
// macro-heavy (map/filter) expressions -- the cost model accrues on
// iteration, not on field reads.
func TestCompileOverCostLimitRejected(t *testing.T) {
env := NewEnv()
prg, err := env.Compile(`[1,2,3,4,5].map(x, x * 2).filter(x, x > 1).size() > 3`)
if err != nil {
t.Fatalf("Compile: %v", err)
}
// With the DefaultCostLimit this succeeds (it is a modest expression).
got, err := env.Eval(prg, Context{Event: map[string]any{}})
if err != nil {
t.Fatalf("Eval(default limit): %v", err)
}
if b, ok := got.(bool); !ok || !b {
t.Fatalf("Eval = %#v, want true", got)
}
// The same expression evaluated under a tiny limit must abort with the
// cost error -- proving the limit is enforced, never truncated.
if _, err := evalUnderLimit(prg, 1); err == nil {
t.Fatal("Eval(tiny limit) = nil error, want cost-limit error")
}
}
// evalUnderLimit rebuilds the program with a caller-supplied cost limit.
func evalUnderLimit(prg *Program, limit uint64) (any, error) {
// Rebuild a fresh env/compile here for the test with an explicit limit.
env := NewEnv()
ast, issues := env.celEnv.Compile(`[1,2,3,4,5].map(x, x * 2).filter(x, x > 1).size() > 3`)
if issues != nil && issues.Err() != nil {
return nil, issues.Err()
}
p, err := env.celEnv.Program(ast, cel.CostLimit(limit))
if err != nil {
return nil, err
}
v, _, err := p.Eval(map[string]any{"event": map[string]any{}, "actions": map[string]any{}})
if err != nil {
return nil, err
}
if rv, ok := v.(ref.Val); ok {
return rv.Value(), nil
}
return v, nil
}
// TestEvalPanicFreeHostileData: a pathological nested map under evaluation
// must not panic -- CEL returns errors or values, never panics (verified
// property; this test guards the wrapper contract, not CEL itself). A
// comparison against a missing key evaluates to false rather than erroring
// (verified CEL semantics: equality does not require the field to exist).
func TestEvalPanicFreeHostileData(t *testing.T) {
env := NewEnv()
prg, err := env.Compile(`event.child == "x"`)
if err != nil {
t.Fatalf("Compile: %v", err)
}
deep := map[string]any{}
cur := deep
for range 5000 {
next := map[string]any{}
cur["child"] = next
cur = next
}
got, err := env.Eval(prg, Context{Event: deep})
if err != nil {
t.Fatalf("Eval(hostile deep) error = %v, want no error (missing key in == -> false)", err)
}
if b, ok := got.(bool); !ok || b {
t.Fatalf("Eval(hostile deep) = %#v, want false", got)
}
}