Public repository: timo / feel

Reader

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

feat(feel-pg): adaptive per-row names, name_resolution argument (ADR-48)

draft feat/name-resolution-v2

feat(feel-pg): adaptive per-row names, name_resolution argument (ADR-48)

- `feel_eval`/`feel_eval_immutable` cache an adaptive `CompiledExpr`
  (keyed on text + level): no per-row candidate check or re-parse of their
  own; rows binding `a-b` get the name reading from the cached parse.
- `feel_eval_immutable` drops ADR-47's ERROR — the parse is a pure function
  of (expr, name_resolution, row), so the result still depends on the
  arguments alone.
- New `name_resolution` argument (`'symbols'` default, `'quoted'`), never
  a GUC; unknown spellings are an ERROR.
- Fix: selection on a lazy jsonb array now maps over its elements
  (`orders.x` over `[{"x":1},{"x":2}]` was null instead of `[1, 2]`).
- Tests: one call site over many rows (the old "per row" test used three
  call sites), immutable per row, nested hyphen members, backticks/levels.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Changeset826338f9286a483cbf97897a75195fc09762cd52
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents9e21c3bb6d58
Children
Pushlog
by timo via ssh

modified crates/feel-pg/src/jsonb.rs +22 −3

@@ -453,10 +453,29 @@
453453
 impl ForeignObject for JsonbForeign {
454454
     fn get(&self, key: &str) -> Value {
455455
         unsafe {
456
-            // Keyed access only makes sense for an object; an array member is an
457
-            // absent key (value-null), matching a missing context entry.
458456
             if (*self.container).header & pg_sys::JB_FOBJECT == 0 {
459
-                return Value::Null;
457
+                // Selection on a list maps over its elements (DMN §10.3.2.5):
458
+                // `[{x:1},{x:2}].x = [1, 2]` — the evaluator does this for an
459
+                // owned `Value::List`, but a lazy jsonb array arrives here as one
460
+                // `Foreign`. A non-object element yields a value-null in its
461
+                // slot, as for owned lists; a raw scalar has no members.
462
+                return match container_to_value(self.container) {
463
+                    Value::List(items) => Value::List(
464
+                        items
465
+                            .into_iter()
466
+                            .map(|it| match it {
467
+                                Value::Foreign(f) => match f.0.as_any().downcast_ref::<JsonbForeign>() {
468
+                                    Some(el) if (*el.container).header & pg_sys::JB_FOBJECT != 0 => {
469
+                                        el.get(key)
470
+                                    }
471
+                                    _ => Value::Null,
472
+                                },
473
+                                _ => Value::Null,
474
+                            })
475
+                            .collect(),
476
+                    ),
477
+                    _ => Value::Null,
478
+                };
460479
             }
461480
             let mut res = pg_sys::JsonbValue::default();
462481
             let found = pg_sys::getKeyJsonValueFromContainer(

modified crates/feel-pg/src/lib.rs +129 −112

@@ -13,10 +13,11 @@
1313
 //! (its `now()`/`today()` read the transaction clock); `feel_eval_immutable` is the
1414
 //! deterministic subset for expression indexes — it rejects `now()`/`today()` and
1515
 //! named time zones, leaving the result a pure function of `(expr, context)` (RD-10).
16
-//! Scope-dependent special-character names (`a-b`, §10.3.1.6, ADR-47) are handled
17
-//! per row: `feel_eval` re-parses against a row that binds one, `feel_eval_immutable`
18
-//! rejects such a row loudly (an index expression must parse identically for every
19
-//! row).
16
+//! Scope-dependent special-character names (`a-b`, `applicant.first-name`,
17
+//! §10.3.1.6) resolve per row against the row's jsonb (ADR-47/48): the cached
18
+//! [`CompiledExpr`] keeps one parse per distinct answer set, so neither function
19
+//! re-parses per row. A `name_resolution` argument selects the level (`'symbols'`,
20
+//! the default, or `'quoted'` — backticks only, no per-row name checks).
2021
 //!
2122
 //! The JSON/jsonb boundary mapping lives here (not in `feel-core`), per the
2223
 //! project's boundary-mapping decision. It uses PostgreSQL's **binary** jsonb C
@@ -47,10 +48,7 @@
4748
 use pgrx::prelude::*;
4849
 use pgrx::{pg_func_extra, PgBox};
4950
 
50
-use feel_core::{
51
-    compile, compile_with_probe, name_run_candidates, CompiledExpr, Context, EvalEnv,
52
-    RustRegex, ScopeProbe,
53
-};
51
+use feel_core::{compile_with, CompiledExpr, Context, EvalEnv, NameResolution, ParseOptions, RustRegex};
5452
 
5553
 mod jsonb;
5654
 use jsonb::PgJsonb;
@@ -71,13 +69,13 @@
7169
 /// the usual case, e.g. one decision over many rows — it is parsed once per query
7270
 /// and only re-parsed if the text actually changes. No global/session cache.
7371
 ///
74
-/// The cached parse is **probe-free** (ADR-47): special-character name runs
75
-/// (`a-b`, `x.y`) are guarded per row via [`feel_core::name_run_candidates`] —
76
-/// when a row binds none of them, the cached parse is already scope-correct
77
-/// (the fast path; plain `applicant.age` path access pays only a few key
78
-/// lookups); when a row *does* bind one, that row's expression is re-parsed
79
-/// against its keys (§10.3.1.6), so a name and an arithmetic reading can coexist
80
-/// across rows of the same query.
72
+/// The cached [`CompiledExpr`] is **scope-adaptive** (ADR-48): special-character
73
+/// runs (`a-b`, `x.y`, `applicant.first-name`) are checked against each row —
74
+/// one key lookup per candidate — and the row gets the parse for its scope, from
75
+/// a small per-call-site cache of parses keyed by those answers. A name and an
76
+/// arithmetic reading thus coexist across rows of one query at no per-row parse
77
+/// cost. `name_resolution => 'quoted'` (backticks only, Camunda semantics) skips
78
+/// the checks altogether; `'symbols'` is the default.
8179
 ///
8280
 /// Declared **STABLE** (not VOLATILE): the only non-argument input is the
8381
 /// transaction start timestamp behind `now()`/`today()`, constant within a
@@ -101,77 +99,60 @@
10199
     expr: &str,
102100
     context: default!(PgJsonb, "'{}'::jsonb"),
103101
     strict: default!(bool, "false"),
102
+    name_resolution: default!(&str, "'symbols'"),
104103
     fcinfo: pg_sys::FunctionCallInfo,
105104
 ) -> PgJsonb {
105
+    let names = name_level(name_resolution, "feel_eval");
106106
     // SAFETY: see [`cached_compile`] — the returned pointer is valid for the query.
107
-    let parsed = unsafe { &*cached_compile(expr, fcinfo) };
108
-    let compiled = &parsed.compiled;
107
+    let compiled = unsafe { &*cached_compile(expr, names, fcinfo) };
109108
 
110109
     // `now()`/`today()` read the transaction start (ADR-18) — constant per query,
111110
     // matching PostgreSQL's own `now()`/`transaction_timestamp()`.
112111
     let env = EvalEnv::new(&RustRegex, transaction_start());
113112
     let ctx = build_context(&context);
114
-    // ADR-47: a special-character name run is resolved against the row's scope.
115
-    // No candidate bound -> the cached probe-free parse is already correct (the
116
-    // overwhelming case); otherwise re-parse against this row's keys — µs-cheap,
117
-    // and only rows that actually bind such a name pay it.
118
-    let row_scoped = if parsed.candidates.iter().any(|c| ctx.contains(c)) {
119
-        Some(compile_with_probe(expr, &ctx).unwrap_or_else(|e| error!("feel_eval failed: {e}")))
120
-    } else {
121
-        None
122
-    };
123
-    eval_to_jsonb(
124
-        row_scoped.as_ref().unwrap_or(compiled),
125
-        &ctx,
126
-        strict,
127
-        &env,
128
-    )
129
-}
130
-
131
-/// Parse `expr` probe-free, caching it plus its [`feel_core::name_run_candidates`]
132
-/// in the call site's `fn_extra` slot (allocated in `flinfo->fn_mcxt`, which lives
133
-/// for the whole query — never the per-row context), keyed on the text. A query
134
-/// constant is thus parsed once and reused across rows; the text only re-parses
135
-/// if it actually changes. Returns a pointer into that cache, valid for the rest
136
-/// of the query.
113
+    eval_to_jsonb(compiled, &ctx, strict, &env)
114
+}
115
+
116
+/// The `name_resolution` argument as a level; an unknown spelling is an ERROR.
117
+fn name_level(arg: &str, func: &str) -> NameResolution {
118
+    NameResolution::from_name(arg).unwrap_or_else(|| {
119
+        error!("{func}: unknown name_resolution '{arg}' (expected 'symbols' or 'quoted')")
120
+    })
121
+}
122
+
123
+/// Parse `expr` at `names`, caching the [`CompiledExpr`] in the call site's
124
+/// `fn_extra` slot (allocated in `flinfo->fn_mcxt`, which lives for the whole
125
+/// query — never the per-row context), keyed on the text and the level. A query
126
+/// constant is thus parsed once and reused across rows; the compiled expression
127
+/// itself caches its few scope-specific parses (ADR-48). Returns a pointer into
128
+/// that cache, valid for the rest of the query.
137129
 ///
138130
 /// # Safety
139131
 /// `fcinfo` must be the genuine call info injected by the pgrx wrapper. The
140132
 /// returned pointer must not outlive the query (the `fn_mcxt`).
141133
 unsafe fn cached_compile(
142134
     expr: &str,
135
+    names: NameResolution,
143136
     fcinfo: pg_sys::FunctionCallInfo,
144
-) -> *const CachedParse {
137
+) -> *const CompiledExpr {
145138
     // `pg_func_extra` allocates the cache in `fn_mcxt` and registers a drop
146139
     // callback, so the owned `CompiledExpr` is freed on context teardown.
147
-    let mut cache: PgBox<Option<(String, CachedParse)>> = pg_func_extra(fcinfo, || None);
140
+    let mut cache: PgBox<Option<(String, NameResolution, CompiledExpr)>> =
141
+        pg_func_extra(fcinfo, || None);
148142
     let stale = match &*cache {
149
-        Some((cached, _)) => cached != expr,
143
+        Some((cached, level, _)) => cached != expr || *level != names,
150144
         None => true,
151145
     };
152146
     if stale {
153
-        match compile(expr) {
154
-            Ok(compiled) => {
155
-                let parsed = CachedParse {
156
-                    compiled,
157
-                    candidates: name_run_candidates(expr),
158
-                };
159
-                *cache = Some((expr.to_owned(), parsed));
160
-            }
147
+        match compile_with(expr, &ParseOptions::names(names)) {
148
+            Ok(compiled) => *cache = Some((expr.to_owned(), names, compiled)),
161149
             Err(e) => error!("feel_eval failed: {e}"),
162150
         }
163151
     }
164152
     match &*cache {
165
-        Some((_, parsed)) => parsed as *const CachedParse,
153
+        Some((_, _, compiled)) => compiled as *const CompiledExpr,
166154
         None => unreachable!("cache populated above"),
167155
     }
168
-}
169
-
170
-/// The per-call-site cached parse: the probe-free [`CompiledExpr`] plus the
171
-/// special-character name candidates guarding it (ADR-47).
172
-struct CachedParse {
173
-    compiled: CompiledExpr,
174
-    candidates: Vec<String>,
175156
 }
176157
 
177158
 /// Evaluate a FEEL expression as an **IMMUTABLE**, deterministic function — the
@@ -190,14 +171,14 @@
190171
 ///   `strict => true`): their UTC offset is read from the IANA tzdb, which can
191172
 ///   change. Fixed offsets (`+02:00`) and `Z` are tzdb-independent and fully
192173
 ///   supported — all an index needs.
193
-/// - A special-character name run (`a-b`, `x.y`) that the row's context
194
-///   **resolves as a name** is rejected with an ERROR (ADR-47): the §10.3.1.6
195
-///   parse depends on the scope, so such a row would silently flip the indexed
196
-///   meaning between rows (name here, arithmetic there). The guard fires only
197
-///   on the *actual* ambiguity — a row that binds none of the expression's
198
-///   [`feel_core::name_run_candidates`] (the ordinary case, e.g. plain path
199
-///   access) evaluates from the cached parse. Use explicit parentheses
200
-///   (`(a)-(b)`) to force the operator reading, or [`feel_eval`].
174
+///
175
+/// Special-character names resolve per row exactly as in [`feel_eval`] (ADR-48):
176
+/// a row binding `a-b` indexes the name, a row binding only `a` and `b` the
177
+/// difference — as §10.3.1.6 demands for each row. That is still IMMUTABLE: the
178
+/// parse is a pure function of the expression, the `name_resolution` argument and
179
+/// the row, so the result depends on the arguments alone. (Never a GUC: a session
180
+/// setting would break that.) `name_resolution => 'quoted'` gives one parse for
181
+/// every row.
201182
 ///
202183
 /// Math/regex builtins (`exp`/`log`/`sqrt`, `matches`/`replace`/`split`) are taken
203184
 /// as immutable; their results are stable except across a libc/`regex` upgrade —
@@ -215,29 +196,29 @@
215196
     expr: &str,
216197
     context: default!(PgJsonb, "'{}'::jsonb"),
217198
     strict: default!(bool, "false"),
199
+    name_resolution: default!(&str, "'symbols'"),
218200
     fcinfo: pg_sys::FunctionCallInfo,
219201
 ) -> PgJsonb {
202
+    let names = name_level(name_resolution, "feel_eval_immutable");
220203
     // Same per-call-site parse cache as `feel_eval`, plus the cached clock-free
221
-    // verdict so the static check is paid once per query, never per row. The
222
-    // name-run candidates ride along for the per-row guard below.
223
-    let mut cache: PgBox<Option<(String, CompiledExpr, bool, Vec<String>)>> =
204
+    // verdict so the static check is paid once per query, never per row.
205
+    let mut cache: PgBox<Option<(String, NameResolution, CompiledExpr, bool)>> =
224206
         unsafe { pg_func_extra(fcinfo, || None) };
225207
     let stale = match &*cache {
226
-        Some((cached, _, _, _)) => cached != expr,
208
+        Some((cached, level, _, _)) => cached != expr || *level != names,
227209
         None => true,
228210
     };
229211
     if stale {
230
-        match compile(expr) {
212
+        match compile_with(expr, &ParseOptions::names(names)) {
231213
             Ok(compiled) => {
232214
                 let clock_free = compiled.is_clock_free();
233
-                let candidates = name_run_candidates(expr);
234
-                *cache = Some((expr.to_owned(), compiled, clock_free, candidates));
215
+                *cache = Some((expr.to_owned(), names, compiled, clock_free));
235216
             }
236217
             Err(e) => error!("feel_eval_immutable failed: {e}"),
237218
         }
238219
     }
239
-    let (compiled, clock_free, candidates) = match &*cache {
240
-        Some((_, compiled, clock_free, candidates)) => (compiled, *clock_free, candidates),
220
+    let (compiled, clock_free) = match &*cache {
221
+        Some((_, _, compiled, clock_free)) => (compiled, *clock_free),
241222
         None => unreachable!("cache populated above"),
242223
     };
243224
     if !clock_free {
@@ -251,17 +232,6 @@
251232
     // IMMUTABLE function should be. Named zones are vetted away (RD-10).
252233
     let env = EvalEnv::new(&RustRegex, fixed_instant()).forbidding_named_zones();
253234
     let ctx = build_context(&context);
254
-    // ADR-47: an index expression must parse identically for every row. A context
255
-    // that resolves one of the expression's name-run candidates would flip the
256
-    // parse per row (name vs arithmetic) — reject loudly (RD-10 style) instead of
257
-    // silently indexing different meanings.
258
-    if candidates.iter().any(|c| ctx.contains(c)) {
259
-        error!(
260
-            "feel_eval_immutable: context resolves a special-character name run in the \
261
-             expression, so its parse is scope-dependent (10.3.1.6) and cannot be \
262
-             IMMUTABLE; write explicit parentheses (e.g. (a)-(b)) or use feel_eval"
263
-        );
264
-    }
265235
     eval_to_jsonb(compiled, &ctx, strict, &env)
266236
 }
267237
 
@@ -700,40 +670,87 @@
700670
     }
701671
 
702672
     #[pg_test]
703
-    fn special_char_name_parse_is_per_row_not_cached_across_rows() {
704
-        // The SAME expression text in ONE query must read as a NAME on rows that
705
-        // bind `a-b` and as subtraction on rows that do not — the candidate check
706
-        // (name_run_candidates) routes ambiguous rows through a fresh probe parse.
707
-        let matched = Spi::get_one::<bool>(
708
-            r#"SELECT feel_eval('a-b', jsonb_build_object('a-b', 5)) = '5'::jsonb
709
-                  AND feel_eval('a-b', jsonb_build_object('a', 7, 'b', 3)) = '4'::jsonb
710
-                  AND feel_eval('a-b', jsonb_build_object('a-b', 5)) = '5'::jsonb"#,
711
-        )
712
-        .expect("SPI query failed");
713
-        assert_eq!(matched, Some(true));
714
-    }
715
-
716
-    #[pg_test]
717
-    fn immutable_uses_cached_parse_for_plain_path_access() {
718
-        // `x.y` HAS a name-run pattern (candidate `x.y`) but the row binds no
719
-        // such key: the cached probe-free parse (path access) is used. The guard
720
-        // fires only on the actual ambiguity, so ordinary path indexes — the
721
-        // core RD-10 use case — are unaffected.
722
-        let matched = Spi::get_one::<bool>(
673
+    fn special_char_name_parse_follows_each_row_at_one_call_site() {
674
+        // ONE call site (one fn_extra cache) over several rows: rows binding
675
+        // `a-b` read the NAME, rows binding only `a`/`b` the difference — the
676
+        // adaptive CompiledExpr picks the parse per row (ADR-48).
677
+        let matched = Spi::get_one::<bool>(
678
+            r#"SELECT bool_and(feel_eval('a-b', c) = e)
679
+                 FROM (VALUES ('{"a-b": 5}'::jsonb, '5'::jsonb),
680
+                              ('{"a": 7, "b": 3}', '4'),
681
+                              ('{"a-b": 5, "a": 7, "b": 3}', '5'),
682
+                              ('{"a": 9, "b": 1}', '8')) t(c, e)"#,
683
+        )
684
+        .expect("SPI query failed");
685
+        assert_eq!(matched, Some(true));
686
+    }
687
+
688
+    #[pg_test]
689
+    fn immutable_resolves_per_row_too() {
690
+        // ADR-48 drops ADR-47's ERROR: the parse is a pure function of
691
+        // (expr, name_resolution, row), so per-row names are still IMMUTABLE.
692
+        let matched = Spi::get_one::<bool>(
693
+            r#"SELECT bool_and(feel_eval_immutable('a-b', c) = e)
694
+                 FROM (VALUES ('{"a-b": 5}'::jsonb, '5'::jsonb),
695
+                              ('{"a": 7, "b": 3}', '4')) t(c, e)"#,
696
+        )
697
+        .expect("SPI query failed");
698
+        assert_eq!(matched, Some(true));
699
+        let path = Spi::get_one::<bool>(
723700
             r#"SELECT feel_eval_immutable('x.y', '{"x": {"y": 42}}'::jsonb) = '42'::jsonb"#,
724701
         )
725702
         .expect("SPI query failed");
703
+        assert_eq!(path, Some(true));
704
+    }
705
+
706
+    #[pg_test]
707
+    fn nested_jsonb_member_with_hyphen() {
708
+        // The path-member probe navigates the lazy jsonb (ADR-48).
709
+        let matched = Spi::get_one::<bool>(
710
+            r#"SELECT feel_eval('applicant.first-name',
711
+                                '{"applicant": {"first-name": "Ada"}}'::jsonb) = '"Ada"'::jsonb
712
+                  AND feel_eval('orders.unit-price',
713
+                                '{"orders": [{"unit-price": 2}, {"unit-price": 3}]}'::jsonb)
714
+                      = '[2, 3]'::jsonb"#,
715
+        )
716
+        .expect("SPI query failed");
717
+        assert_eq!(matched, Some(true));
718
+    }
719
+
720
+    #[pg_test]
721
+    fn path_selection_maps_over_a_jsonb_array() {
722
+        // §10.3.2.5: selection on a list of contexts maps over it. A lazy jsonb
723
+        // array used to answer every key with null.
724
+        let matched = Spi::get_one::<bool>(
725
+            r#"SELECT feel_eval('orders.x', '{"orders": [{"x": 1}, {"x": 2}, 3]}'::jsonb)
726
+                      = '[1, 2, null]'::jsonb
727
+                  AND feel_eval('o.items.x', '{"o": {"items": [{"x": 1}]}}'::jsonb)
728
+                      = '[1]'::jsonb"#,
729
+        )
730
+        .expect("SPI query failed");
731
+        assert_eq!(matched, Some(true));
732
+    }
733
+
734
+    #[pg_test]
735
+    fn backticks_and_quoted_level() {
736
+        // Backticks at every level; `'quoted'` never resolves unquoted runs.
737
+        let matched = Spi::get_one::<bool>(
738
+            r#"SELECT feel_eval('`Profit and loss`', '{"Profit and loss": 1}'::jsonb) = '1'::jsonb
739
+                  AND feel_eval('a-b', '{"a-b": 5, "a": 7, "b": 3}'::jsonb,
740
+                                name_resolution => 'quoted') = '4'::jsonb
741
+                  AND feel_eval('`a-b`', '{"a-b": 5}'::jsonb,
742
+                                name_resolution => 'quoted') = '5'::jsonb"#,
743
+        )
744
+        .expect("SPI query failed");
726745
         assert_eq!(matched, Some(true));
727746
     }
728747
 
729748
     #[pg_test(
730
-        error = "feel_eval_immutable: context resolves a special-character name run in the expression, so its parse is scope-dependent (10.3.1.6) and cannot be IMMUTABLE; write explicit parentheses (e.g. (a)-(b)) or use feel_eval"
749
+        error = "feel_eval: unknown name_resolution 'full' (expected 'symbols' or 'quoted')"
731750
     )]
732
-    fn immutable_rejects_row_resolved_name_run() {
733
-        // A row that resolves `a-b` as a name would flip the indexed meaning
734
-        // between rows — a loud ERROR, never a silent flip (RD-10 style).
751
+    fn unknown_name_resolution_is_an_error() {
735752
         let _ = Spi::get_one::<bool>(
736
-            r#"SELECT feel_eval_immutable('a-b', '{"a-b": 5}'::jsonb) IS NOT NULL"#,
753
+            r#"SELECT feel_eval('1', '{}'::jsonb, name_resolution => 'full') IS NOT NULL"#,
737754
         );
738755
     }
739756
 }