Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

feat(core): track error provenance (error-null) with sticky three-valued logic

public

feat(core): track error provenance (error-null) with sticky three-valued logic

FEEL overloads `null` as both a legitimate absence and the result of a type/
domain error, so "errors should never pass silently" conflicts with ADR-9. Add
a distinct `Value::Error` ("error-null") that behaves identically to
`Value::Null` for every FEEL operation (equality, ordering, three-valued logic)
— the TCK stays bit-for-bit green — but carries provenance so the boundary can
surface it.

- Error sources of ADR-9 (non-numeric arithmetic, div-by-zero, non-finite,
  incomparable/typed-mismatch comparison, `not`/`if` of a wrong type, path on a
  non-context, non-iterable for/quantifier source) now yield Value::Error; the
  `null` literal, unbound vars and missing members stay Value::Null.
- AND/OR/quantifiers (Design 1, ADR-14): strong-Kleene truth value with sticky
  provenance — a dominating false/true wins (so `false and (1/0)` is false),
  and the unknown null is an error-null only if a contributing unknown operand
  was tainted. `if` keys on provenance: value-null condition -> else, error/
  wrong-type condition -> error-null (refines ADR-13).
- Boundary policy in the wrappers: lenient (default) collapses error-null to
  null; strict surfaces it. feel-pg `feel_eval(…, strict => true)` raises;
  feel-wasm adds `evaluate_strict`. Core never throws (ADR-1 intact).
- `Value::contains_error`/`into_lenient`; fixture test and lenient wrappers use
  the lenient view. New `error_provenance` unit test and pg strict/lenient tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changeset34d8df00d1effd8611592422741df2cd6e42bee2
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents7ca50f8bf17e
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/eval.rs +110 −49

@@ -33,15 +33,17 @@
3333
         Expr::Var(name) => Ok(ctx.get(name).cloned().unwrap_or(Value::Null)),
3434
         Expr::ContextLit(entries) => eval_context_lit(entries, ctx),
3535
         Expr::Path(target, name) => Ok(match eval(target, ctx)? {
36
-            // Path on a non-context (or a missing member) is null, per FEEL.
36
+            // A missing member is a value-null (like an unbound variable);
37
+            // a path on a non-context is a type error -> error-null.
3738
             Value::Context(map) => map.get(name).cloned().unwrap_or(Value::Null),
38
-            _ => Value::Null,
39
+            Value::Error => Value::Error,
40
+            _ => Value::Error,
3941
         }),
4042
 
4143
         // --- arithmetic ---
4244
         Expr::Neg(e) => Ok(match eval(e, ctx)? {
4345
             Value::Number(n) => Value::Number(-n),
44
-            _ => Value::Null,
46
+            _ => Value::Error, // negation of a non-number -> error-null
4547
         }),
4648
         Expr::Arith(op, l, r) => eval_arith(*op, eval(l, ctx)?, eval(r, ctx)?),
4749
 
@@ -64,17 +66,22 @@
6466
         Expr::Or(l, r) => Ok(or3(eval(l, ctx)?, eval(r, ctx)?)),
6567
         Expr::Not(e) => Ok(match eval(e, ctx)? {
6668
             Value::Boolean(b) => Value::Boolean(!b),
67
-            _ => Value::Null,
69
+            // `not` of a value-null is the Kleene "not unknown = unknown".
70
+            Value::Null => Value::Null,
71
+            _ => Value::Error, // not of a non-boolean (or error) -> error-null
6872
         }),
6973
 
7074
         // --- control flow ---
71
-        // `if` distinguishes a null condition (a legitimate FEEL value meaning
72
-        // "not true" -> else, per DMN-TCK 0032) from a wrong-TYPE condition (a
73
-        // genuine type error -> null, keeping it visible per ADR-9/ADR-13).
75
+        // `if` keys on the *provenance* of its condition (ADR-13/ADR-14):
76
+        //   true            -> then
77
+        //   false / value-null  -> else  (null is a value meaning "not true",
78
+        //                                  per DMN-TCK 0032)
79
+        //   error-null / wrong type -> error-null  (a type error escalates;
80
+        //                                  it does not silently take `else`)
7481
         Expr::If(c, t, e) => match eval(c, ctx)? {
7582
             Value::Boolean(true) => eval(t, ctx),
7683
             Value::Boolean(false) | Value::Null => eval(e, ctx),
77
-            _ => Ok(Value::Null), // non-boolean, non-null condition: type error
84
+            _ => Ok(Value::Error),
7885
         },
7986
         Expr::For { var, source, body } => eval_for(var, source, body, ctx),
8087
         Expr::Quantified {
@@ -111,7 +118,7 @@
111118
 fn eval_arith(op: ArithOp, lhs: Value, rhs: Value) -> EvalResult {
112119
     let (a, b) = match (as_number(&lhs), as_number(&rhs)) {
113120
         (Some(a), Some(b)) => (a, b),
114
-        _ => return Ok(Value::Null), // non-numeric operand -> null
121
+        _ => return Ok(Value::Error), // non-numeric operand -> error-null
115122
     };
116123
     let out = match op {
117124
         ArithOp::Add => a + b,
@@ -119,18 +126,18 @@
119126
         ArithOp::Mul => a * b,
120127
         ArithOp::Div => {
121128
             if b == 0.0 {
122
-                return Ok(Value::Null); // division by zero -> null
129
+                return Ok(Value::Error); // division by zero -> error-null
123130
             }
124131
             a / b
125132
         }
126133
         ArithOp::Pow => a.powf(b),
127134
     };
128
-    // Non-finite results (overflow / NaN, e.g. (-8) ** 0.5) collapse to null;
135
+    // Non-finite results (overflow / NaN, e.g. (-8) ** 0.5) are a domain error;
129136
     // this also keeps every Number JSON-representable at the wrappers.
130137
     Ok(if out.is_finite() {
131138
         Value::Number(out)
132139
     } else {
133
-        Value::Null
140
+        Value::Error
134141
     })
135142
 }
136143
 
@@ -140,24 +147,27 @@
140147
 
141148
 fn eval_compare(op: CmpOp, a: &Value, b: &Value) -> Value {
142149
     match op {
143
-        CmpOp::Eq => from_opt_bool(feel_equal(a, b)),
144
-        CmpOp::Ne => from_opt_bool(feel_equal(a, b).map(|eq| !eq)),
145
-        CmpOp::Lt => order_to_bool(feel_order(a, b), |o| o == Ordering::Less),
146
-        CmpOp::Le => order_to_bool(feel_order(a, b), |o| o != Ordering::Greater),
147
-        CmpOp::Gt => order_to_bool(feel_order(a, b), |o| o == Ordering::Greater),
148
-        CmpOp::Ge => order_to_bool(feel_order(a, b), |o| o != Ordering::Less),
150
+        // Equality is defined for null (null = null -> true), so it does not
151
+        // propagate null; only a type mismatch (`None`) is an error.
152
+        CmpOp::Eq => eq_result(feel_equal(a, b)),
153
+        CmpOp::Ne => eq_result(feel_equal(a, b).map(|eq| !eq)),
154
+        CmpOp::Lt => order_compare(a, b, |o| o == Ordering::Less),
155
+        CmpOp::Le => order_compare(a, b, |o| o != Ordering::Greater),
156
+        CmpOp::Gt => order_compare(a, b, |o| o == Ordering::Greater),
157
+        CmpOp::Ge => order_compare(a, b, |o| o != Ordering::Less),
149158
     }
150159
 }
151160
 
152161
 /// FEEL equality, three-valued:
153
-///   * both null            -> Some(true)
154
-///   * exactly one null     -> Some(false)
162
+///   * both null-ish        -> Some(true)   (error-null equals value-null)
163
+///   * exactly one null-ish -> Some(false)
155164
 ///   * same type            -> Some(value comparison) (lists compared elementwise)
156
-///   * different non-null   -> None  (-> null)
165
+///   * different non-null   -> None  (-> error-null at the call site)
157166
 fn feel_equal(a: &Value, b: &Value) -> Option<bool> {
167
+    use Value::{Error, Null};
158168
     match (a, b) {
159
-        (Value::Null, Value::Null) => Some(true),
160
-        (Value::Null, _) | (_, Value::Null) => Some(false),
169
+        (Null | Error, Null | Error) => Some(true),
170
+        (Null | Error, _) | (_, Null | Error) => Some(false),
161171
         (Value::Number(x), Value::Number(y)) => Some(x == y),
162172
         (Value::Boolean(x), Value::Boolean(y)) => Some(x == y),
163173
         (Value::String(x), Value::String(y)) => Some(x == y),
@@ -198,8 +208,9 @@
198208
     }
199209
 }
200210
 
201
-/// FEEL ordering. Only numbers and strings are ordered; anything else (null,
202
-/// boolean, list, or a type mismatch) yields `None` (-> null).
211
+/// FEEL ordering of two comparable, non-null values. Only numbers and strings
212
+/// are ordered; any other pairing is a type mismatch (`None`). Null/error
213
+/// operands are handled by [`order_compare`] before this is reached.
203214
 fn feel_order(a: &Value, b: &Value) -> Option<Ordering> {
204215
     match (a, b) {
205216
         (Value::Number(x), Value::Number(y)) => x.partial_cmp(y),
@@ -208,17 +219,30 @@
208219
     }
209220
 }
210221
 
211
-fn from_opt_bool(b: Option<bool>) -> Value {
222
+/// Map an equality outcome to a value. `None` (different non-null types) is a
223
+/// type mismatch -> error-null.
224
+fn eq_result(b: Option<bool>) -> Value {
212225
     match b {
213226
         Some(b) => Value::Boolean(b),
214
-        None => Value::Null,
215
-    }
216
-}
217
-
218
-fn order_to_bool(ord: Option<Ordering>, pred: impl Fn(Ordering) -> bool) -> Value {
219
-    match ord {
227
+        None => Value::Error,
228
+    }
229
+}
230
+
231
+/// Ordering comparison (`< <= > >=`) with provenance:
232
+///   * an error operand -> error-null (propagated);
233
+///   * a value-null operand -> value-null (the order is unknown, like Kleene);
234
+///   * two comparable values -> the boolean;
235
+///   * incomparable non-null types -> error-null (type mismatch).
236
+fn order_compare(a: &Value, b: &Value, pred: impl Fn(Ordering) -> bool) -> Value {
237
+    if is_error(a) || is_error(b) {
238
+        return Value::Error;
239
+    }
240
+    if matches!(a, Value::Null) || matches!(b, Value::Null) {
241
+        return Value::Null;
242
+    }
243
+    match feel_order(a, b) {
220244
         Some(o) => Value::Boolean(pred(o)),
221
-        None => Value::Null,
245
+        None => Value::Error, // incomparable non-null types
222246
     }
223247
 }
224248
 
@@ -247,25 +271,34 @@
247271
 // Kleene logic
248272
 // --------------------------------------------------------------------------- //
249273
 
250
-/// `and`: false if either operand is `false`, true if both are `true`, else null.
274
+// Strong Kleene with sticky error provenance (Design 1, ADR-14): the truth
275
+// value is exactly strong three-valued logic — a dominating `false` (and) or
276
+// `true` (or) wins regardless of the other operand — so the TCK stays green.
277
+// Provenance only matters when the result is the "unknown" null: then it is an
278
+// error-null iff a contributing operand was tainted. A value-null operand is
279
+// untainted (it is a legitimate unknown); a wrong-typed or error operand taints.
280
+
281
+/// `and`: false if either operand is `false`, true if both are `true`, else
282
+/// null (error-null iff an unknown operand was tainted).
251283
 fn and3(a: Value, b: Value) -> Value {
252284
     if is_false(&a) || is_false(&b) {
253285
         Value::Boolean(false)
254286
     } else if is_true(&a) && is_true(&b) {
255287
         Value::Boolean(true)
256288
     } else {
257
-        Value::Null
258
-    }
259
-}
260
-
261
-/// `or`: true if either operand is `true`, false if both are `false`, else null.
289
+        nullish(taints(&a) || taints(&b))
290
+    }
291
+}
292
+
293
+/// `or`: true if either operand is `true`, false if both are `false`, else
294
+/// null (error-null iff an unknown operand was tainted).
262295
 fn or3(a: Value, b: Value) -> Value {
263296
     if is_true(&a) || is_true(&b) {
264297
         Value::Boolean(true)
265298
     } else if is_false(&a) && is_false(&b) {
266299
         Value::Boolean(false)
267300
     } else {
268
-        Value::Null
301
+        nullish(taints(&a) || taints(&b))
269302
     }
270303
 }
271304
 
@@ -275,6 +308,27 @@
275308
 
276309
 fn is_false(v: &Value) -> bool {
277310
     matches!(v, Value::Boolean(false))
311
+}
312
+
313
+fn is_error(v: &Value) -> bool {
314
+    matches!(v, Value::Error)
315
+}
316
+
317
+/// An "unknown" operand taints the result with an error iff it is an error-null
318
+/// or a wrong-typed value (a non-boolean, non-(value-null) value is a type error
319
+/// as a logic operand). A plain value-null is a legitimate unknown -> untainted.
320
+fn taints(v: &Value) -> bool {
321
+    !matches!(v, Value::Boolean(_) | Value::Null)
322
+}
323
+
324
+/// The "unknown" result of a three-valued operation: error-null if tainted,
325
+/// else value-null.
326
+fn nullish(tainted: bool) -> Value {
327
+    if tainted {
328
+        Value::Error
329
+    } else {
330
+        Value::Null
331
+    }
278332
 }
279333
 
280334
 // --------------------------------------------------------------------------- //
@@ -321,7 +375,7 @@
321375
 
322376
 fn eval_for(var: &str, source: &IterSource, body: &Expr, ctx: &Context) -> EvalResult {
323377
     let Some(items) = iter_values(source, ctx)? else {
324
-        return Ok(Value::Null);
378
+        return Ok(Value::Error); // non-iterable source: type error
325379
     };
326380
     let mut out = Vec::with_capacity(items.len());
327381
     for item in items {
@@ -338,19 +392,26 @@
338392
     ctx: &Context,
339393
 ) -> EvalResult {
340394
     let Some(items) = iter_values(source, ctx)? else {
341
-        return Ok(Value::Null);
342
-    };
343
-    let mut any_null = false;
395
+        return Ok(Value::Error); // non-iterable source: type error
396
+    };
397
+    // A quantifier is a folded and/or, so it carries the same sticky-provenance
398
+    // rule (Design 1): a dominating result short-circuits; otherwise the unknown
399
+    // result is an error-null iff a non-boolean predicate result tainted it.
400
+    let mut saw_unknown = false;
401
+    let mut tainted = false;
344402
     for item in items {
345403
         match eval(predicate, &ctx.with(var, item))? {
346404
             Value::Boolean(true) if kind == Quantifier::Some => return Ok(Value::Boolean(true)),
347405
             Value::Boolean(false) if kind == Quantifier::Every => return Ok(Value::Boolean(false)),
348406
             Value::Boolean(_) => {}
349
-            _ => any_null = true, // non-boolean / null predicate result
350
-        }
351
-    }
352
-    Ok(if any_null {
353
-        Value::Null
407
+            other => {
408
+                saw_unknown = true;
409
+                tainted |= taints(&other);
410
+            }
411
+        }
412
+    }
413
+    Ok(if saw_unknown {
414
+        nullish(tainted)
354415
     } else {
355416
         match kind {
356417
             Quantifier::Some => Value::Boolean(false),

modified crates/feel-core/src/lib.rs +43 −2

@@ -78,9 +78,14 @@
7878
 mod tests {
7979
     use super::*;
8080
 
81
-    /// Evaluate against an empty context, panicking on error.
81
+    /// Evaluate against an empty context, panicking on error, and collapse error
82
+    /// provenance — this is the lenient/observable view, so these tests assert
83
+    /// plain FEEL value semantics where an error-null and a value-null coincide.
84
+    /// (See `error_provenance` for the raw, provenance-aware assertions.)
8285
     fn ev(src: &str) -> Value {
83
-        evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
86
+        evaluate(src, &Context::empty())
87
+            .unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
88
+            .into_lenient()
8489
     }
8590
 
8691
     fn num(n: f64) -> Value {
@@ -213,6 +218,42 @@
213218
     }
214219
 
215220
     #[test]
221
+    fn error_provenance() {
222
+        // Raw view: do NOT collapse error provenance (unlike `ev`).
223
+        let raw = |src: &str| {
224
+            evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
225
+        };
226
+
227
+        // Type / domain errors produce an error-null...
228
+        assert_eq!(raw("1 + true"), Value::Error);
229
+        assert_eq!(raw("1 / 0"), Value::Error);
230
+        assert_eq!(raw("-true"), Value::Error);
231
+        assert_eq!(raw("1 < true"), Value::Error); // incomparable types
232
+        assert_eq!(raw(r#"100 = "100""#), Value::Error); // type mismatch in `=`
233
+        assert_eq!(raw("if 5 then 1 else 2"), Value::Error); // wrong-type condition
234
+        assert_eq!(raw("5 .a"), Value::Error); // path on a non-context
235
+        assert_eq!(raw("not(0)"), Value::Error); // `not` of a non-boolean
236
+
237
+        // ...while a genuine value-null stays a value-null.
238
+        assert_eq!(raw("null"), Value::Null);
239
+        assert_eq!(raw("missing"), Value::Null); // unbound variable
240
+        assert_eq!(raw("1 < null"), Value::Null); // value-null operand: unknown
241
+        assert_eq!(raw("if null then 1 else 2"), num(2.0)); // value-null -> else
242
+        assert_eq!(raw("not(null)"), Value::Null); // not unknown = unknown
243
+        assert_eq!(raw("true and null"), Value::Null); // value-null: untainted
244
+
245
+        // error-null and value-null behave identically under FEEL equality.
246
+        assert_eq!(raw("null = (1 + true)"), b(true));
247
+
248
+        // Design 1: a dominator swallows the error (truth value wins, TCK-safe)...
249
+        assert_eq!(raw("false and (1 + true)"), b(false));
250
+        assert_eq!(raw("true or (1 + true)"), b(true));
251
+        // ...but provenance is sticky where the result is the unknown null.
252
+        assert_eq!(raw("true and (1 + true)"), Value::Error);
253
+        assert_eq!(raw("false or (1 + true)"), Value::Error);
254
+    }
255
+
256
+    #[test]
216257
     fn for_loops() {
217258
         assert_eq!(
218259
             ev("for i in [1,2,3] return i + 1"),

modified crates/feel-core/src/value.rs +39 −0

@@ -18,5 +18,44 @@
1818
     /// A FEEL context (map of name -> value). Backed by a `BTreeMap` so equality
1919
     /// is key/value structural and JSON output is key-ordered (deterministic).
2020
     Context(BTreeMap<String, Value>),
21
+    /// A "value null": a legitimate absence — the `null` literal, an unbound
22
+    /// variable, a missing context member, or an input null.
2123
     Null,
24
+    /// An "error null": a null that arose from a *type or domain error* (e.g.
25
+    /// arithmetic on non-numbers, division by zero, comparing incomparable
26
+    /// types). It behaves exactly like [`Value::Null`] for every FEEL operation
27
+    /// (equality, ordering, three-valued logic) — see DECISIONS.md ADR-14 — but
28
+    /// carries provenance so a strict boundary can surface it instead of letting
29
+    /// the error pass silently. The wrappers collapse it to JSON `null` by
30
+    /// default (lenient) or raise on it (strict).
31
+    Error,
2232
 }
33
+
34
+impl Value {
35
+    /// True if this value is, or transitively contains, an [`Value::Error`].
36
+    /// Used by the strict boundary policy in the wrappers.
37
+    pub fn contains_error(&self) -> bool {
38
+        match self {
39
+            Value::Error => true,
40
+            Value::List(items) => items.iter().any(Value::contains_error),
41
+            Value::Context(map) => map.values().any(Value::contains_error),
42
+            _ => false,
43
+        }
44
+    }
45
+
46
+    /// Collapse every [`Value::Error`] (including nested ones) to [`Value::Null`].
47
+    /// This is the lenient boundary policy: error provenance is dropped and the
48
+    /// result is the plain, spec-shaped value.
49
+    pub fn into_lenient(self) -> Value {
50
+        match self {
51
+            Value::Error => Value::Null,
52
+            Value::List(items) => {
53
+                Value::List(items.into_iter().map(Value::into_lenient).collect())
54
+            }
55
+            Value::Context(map) => {
56
+                Value::Context(map.into_iter().map(|(k, v)| (k, v.into_lenient())).collect())
57
+            }
58
+            other => other,
59
+        }
60
+    }
61
+}

modified crates/feel-core/tests/fixtures_test.rs +4 −1

@@ -59,8 +59,11 @@
5959
     let comparison = case["comparison"].as_str().unwrap_or("exact");
6060
 
6161
     let ctx = context_from_case(case, id);
62
+    // Collapse error provenance: TCK expectations are spec-shaped (a type error
63
+    // is just `null`), so we compare against the lenient view (ADR-14).
6264
     let got = evaluate(expr, &ctx)
63
-        .unwrap_or_else(|e| panic!("[{id}] evaluating `{expr}` failed: {e}"));
65
+        .unwrap_or_else(|e| panic!("[{id}] evaluating `{expr}` failed: {e}"))
66
+        .into_lenient();
6467
 
6568
     match comparison {
6669
         "exact" => {

modified crates/feel-pg/src/lib.rs +39 −3

@@ -18,12 +18,23 @@
1818
 
1919
 /// Evaluate a FEEL expression and return the result as jsonb.
2020
 ///
21
-/// Raises a Postgres ERROR if the expression cannot be parsed or evaluated.
21
+/// Raises a Postgres ERROR if the expression cannot be parsed. By default the
22
+/// boundary is *lenient*: a null arising from a type/domain error is returned as
23
+/// jsonb `null`. Pass `strict => true` to instead raise an ERROR when the result
24
+/// is, or contains, such an error-null, so the error does not pass silently
25
+/// (ADR-14).
2226
 #[pg_extern]
23
-fn feel_eval(expr: &str, context: default!(JsonB, "'{}'::jsonb")) -> JsonB {
27
+fn feel_eval(
28
+    expr: &str,
29
+    context: default!(JsonB, "'{}'::jsonb"),
30
+    strict: default!(bool, "false"),
31
+) -> JsonB {
2432
     let ctx = context_from_json(&context.0)
2533
         .unwrap_or_else(|e| error!("invalid feel context: {e}"));
2634
     match evaluate(expr, &ctx) {
35
+        Ok(value) if strict && value.contains_error() => {
36
+            error!("feel_eval: result is null from a type or domain error (strict mode)")
37
+        }
2738
         Ok(value) => JsonB(value_to_json(&value)),
2839
         Err(e) => error!("feel_eval failed: {e}"),
2940
     }
@@ -42,7 +53,9 @@
4253
         Value::Context(map) => serde_json::Value::Object(
4354
             map.iter().map(|(k, v)| (k.clone(), value_to_json(v))).collect(),
4455
         ),
45
-        Value::Null => serde_json::Value::Null,
56
+        // Lenient: an error-null serialises like a plain null. Strict callers
57
+        // check `Value::contains_error` before reaching here.
58
+        Value::Null | Value::Error => serde_json::Value::Null,
4659
     }
4760
 }
4861
 
@@ -132,6 +145,29 @@
132145
     }
133146
 
134147
     #[pg_test]
148
+    fn type_error_is_lenient_null_by_default() {
149
+        // A type error -> jsonb null (lenient boundary).
150
+        let matched = Spi::get_one::<bool>("SELECT feel_eval('1 + true') = 'null'::jsonb")
151
+            .expect("SPI query failed");
152
+        assert_eq!(matched, Some(true));
153
+    }
154
+
155
+    #[pg_test(error = "feel_eval: result is null from a type or domain error (strict mode)")]
156
+    fn strict_mode_raises_on_error_null() {
157
+        // strict => true escalates the error-null to an ERROR (this query raises).
158
+        let _ = Spi::get_one::<bool>("SELECT feel_eval('1 + true', '{}'::jsonb, true) IS NOT NULL");
159
+    }
160
+
161
+    #[pg_test]
162
+    fn strict_mode_passes_plain_null() {
163
+        // A genuine value-null is fine even in strict mode.
164
+        let matched =
165
+            Spi::get_one::<bool>("SELECT feel_eval('null', '{}'::jsonb, true) = 'null'::jsonb")
166
+                .expect("SPI query failed");
167
+        assert_eq!(matched, Some(true));
168
+    }
169
+
170
+    #[pg_test]
135171
     fn path_access_reads_nested_context() {
136172
         // A nested jsonb object is bound as a FEEL context; `p.age` reads it.
137173
         let matched = Spi::get_one::<bool>(

modified crates/feel-wasm/smoke.mjs +18 −1

@@ -14,7 +14,7 @@
1414
 //   {a: 1, b: a + 1} => {"a":1,"b":2}
1515
 //   person.age (ctx {"person":{"age":42}}) => 42
1616
 
17
-import { evaluate } from "./pkg/feel_wasm.js";
17
+import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js";
1818
 
1919
 // [expression, context-json, expected-json]. These mirror the feel-core and
2020
 // feel-pg tests, demonstrating "same core, same result" across all three
@@ -39,5 +39,22 @@
3939
     ok = false;
4040
   }
4141
 }
42
+
43
+// Boundary policy (ADR-14): a type error is a lenient `null`, but `evaluate_strict`
44
+// surfaces it as an {"error": ...} object instead of letting it pass silently.
45
+const strictCases = [
46
+  ["1 + true", "{}", "null", true], // lenient: null; strict: error
47
+  ["null", "{}", "null", false], // a genuine value-null is fine even in strict
48
+];
49
+for (const [expr, ctx, expectedLenient, expectStrictError] of strictCases) {
50
+  const lenient = evaluate(expr, ctx);
51
+  const strict = evaluate_strict(expr, ctx);
52
+  console.log(`${expr} => lenient ${lenient} | strict ${strict}`);
53
+  const strictIsError = strict.includes('"error"');
54
+  if (lenient !== expectedLenient || strictIsError !== expectStrictError) {
55
+    console.error(`FAIL: ${expr} lenient/strict mismatch`);
56
+    ok = false;
57
+  }
58
+}
4259
 if (!ok) process.exit(1);
4360
 console.error("smoke test passed");

modified crates/feel-wasm/src/lib.rs +26 −7

@@ -7,25 +7,42 @@
77
 use feel_core::{evaluate as core_evaluate, Context, Value};
88
 use wasm_bindgen::prelude::*;
99
 
10
-/// Evaluate a FEEL expression.
10
+/// Evaluate a FEEL expression (lenient boundary policy).
1111
 ///
1212
 /// `context_json` is a JSON object string (e.g. `"{}"`). The result is returned
1313
 /// as a JSON string. On error, a JSON object `{"error": "..."}` is returned so
1414
 /// the JS side never has to deal with thrown exceptions for plain eval errors.
15
+/// A null arising from a type/domain error is emitted as plain JSON `null` (the
16
+/// spec-shaped result); see `evaluate_strict` to surface such errors instead.
1517
 #[wasm_bindgen]
1618
 pub fn evaluate(expr: &str, context_json: &str) -> String {
17
-    match eval_to_json(expr, context_json) {
18
-        Ok(json) => json,
19
+    match eval_value(expr, context_json) {
20
+        Ok(value) => value_to_json(&value).to_string(),
1921
         Err(message) => serde_json::json!({ "error": message }).to_string(),
2022
     }
2123
 }
2224
 
23
-fn eval_to_json(expr: &str, context_json: &str) -> Result<String, String> {
25
+/// Evaluate a FEEL expression (strict boundary policy): if the result is, or
26
+/// contains, a null that arose from a type/domain error, return
27
+/// `{"error": "..."}` instead of letting the error pass silently as `null`
28
+/// (ADR-14). A plain (value) null is still returned as `null`.
29
+#[wasm_bindgen]
30
+pub fn evaluate_strict(expr: &str, context_json: &str) -> String {
31
+    match eval_value(expr, context_json) {
32
+        Ok(value) if value.contains_error() => serde_json::json!({
33
+            "error": "evaluation produced a null from a type or domain error"
34
+        })
35
+        .to_string(),
36
+        Ok(value) => value_to_json(&value).to_string(),
37
+        Err(message) => serde_json::json!({ "error": message }).to_string(),
38
+    }
39
+}
40
+
41
+fn eval_value(expr: &str, context_json: &str) -> Result<Value, String> {
2442
     let parsed: serde_json::Value =
2543
         serde_json::from_str(context_json).map_err(|e| format!("invalid context JSON: {e}"))?;
2644
     let ctx = context_from_json(&parsed)?;
27
-    let value = core_evaluate(expr, &ctx).map_err(|e| e.to_string())?;
28
-    Ok(value_to_json(&value).to_string())
45
+    core_evaluate(expr, &ctx).map_err(|e| e.to_string())
2946
 }
3047
 
3148
 /// Map a `feel-core` [`Value`] to a JSON value for the string boundary.
@@ -41,7 +58,9 @@
4158
         Value::Context(map) => serde_json::Value::Object(
4259
             map.iter().map(|(k, v)| (k.clone(), value_to_json(v))).collect(),
4360
         ),
44
-        Value::Null => serde_json::Value::Null,
61
+        // Lenient: an error-null serialises like a plain null. Strict callers
62
+        // check `Value::contains_error` before reaching here.
63
+        Value::Null | Value::Error => serde_json::Value::Null,
4564
     }
4665
 }
4766