Public repository: timo / feel

Reader

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

feat(feel-pg): scope-dependent name-run handling per row (ADR-47)

draft feat/special-char-names

feat(feel-pg): scope-dependent name-run handling per row (ADR-47)

The fn_extra parse cache is probe-free, so a special-character name run
(a-b, x.y) cached from one row could mis-read on another that binds the
joined name. Both SQL functions now guard per row via
feel_core::name_run_candidates (computed once per call site):

- feel_eval: no candidate bound in the row's jsonb -> the cached parse is
  already scope-correct (the fast path; plain path access pays only a
  few key lookups). A candidate bound -> re-parse against that row's
  keys, so a name reading and an arithmetic reading coexist across
  rows of the same query.
- feel_eval_immutable: a candidate bound -> loud ERROR (RD-10 style):
  an index expression must parse identically for every row, never
  silently flip its meaning. The guard fires only on the actual
  ambiguity, so ordinary path indexes are unaffected.

5 new pg tests (37 total), run via cargo pgrx test pg18.
Changeset5b344709d08e8c74f7becf9ef4fce5e0a49107b8
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents9ea85e0a23f4
Children
Pushlog
by timo via ssh

modified crates/feel-pg/src/lib.rs +150 −24

@@ -13,6 +13,10 @@
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).
1620
 //!
1721
 //! The JSON/jsonb boundary mapping lives here (not in `feel-core`), per the
1822
 //! project's boundary-mapping decision. It uses PostgreSQL's **binary** jsonb C
@@ -43,7 +47,10 @@
4347
 use pgrx::prelude::*;
4448
 use pgrx::{pg_func_extra, PgBox};
4549
 
46
-use feel_core::{compile, CompiledExpr, Context, EvalEnv, RustRegex};
50
+use feel_core::{
51
+    compile, compile_with_probe, name_run_candidates, CompiledExpr, Context, EvalEnv,
52
+    RustRegex, ScopeProbe,
53
+};
4754
 
4855
 mod jsonb;
4956
 use jsonb::PgJsonb;
@@ -63,6 +70,14 @@
6370
 /// context), keyed on the expression text. So when `expr` is a query constant —
6471
 /// the usual case, e.g. one decision over many rows — it is parsed once per query
6572
 /// and only re-parsed if the text actually changes. No global/session cache.
73
+///
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.
6681
 ///
6782
 /// Declared **STABLE** (not VOLATILE): the only non-argument input is the
6883
 /// transaction start timestamp behind `now()`/`today()`, constant within a
@@ -89,42 +104,74 @@
89104
     fcinfo: pg_sys::FunctionCallInfo,
90105
 ) -> PgJsonb {
91106
     // SAFETY: see [`cached_compile`] — the returned pointer is valid for the query.
92
-    let compiled = unsafe { &*cached_compile(expr, fcinfo) };
107
+    let parsed = unsafe { &*cached_compile(expr, fcinfo) };
108
+    let compiled = &parsed.compiled;
93109
 
94110
     // `now()`/`today()` read the transaction start (ADR-18) — constant per query,
95111
     // matching PostgreSQL's own `now()`/`transaction_timestamp()`.
96112
     let env = EvalEnv::new(&RustRegex, transaction_start());
97113
     let ctx = build_context(&context);
98
-    eval_to_jsonb(compiled, &ctx, strict, &env)
99
-}
100
-
101
-/// Parse `expr`, caching the [`CompiledExpr`] in the call site's `fn_extra` slot
102
-/// (allocated in `flinfo->fn_mcxt`, which lives for the whole query — never the
103
-/// per-row context), keyed on the text. A query constant is thus parsed once and
104
-/// reused across rows; the text only re-parses if it actually changes. Returns a
105
-/// pointer into that cache, valid for the rest of the query.
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.
106137
 ///
107138
 /// # Safety
108139
 /// `fcinfo` must be the genuine call info injected by the pgrx wrapper. The
109140
 /// returned pointer must not outlive the query (the `fn_mcxt`).
110
-unsafe fn cached_compile(expr: &str, fcinfo: pg_sys::FunctionCallInfo) -> *const CompiledExpr {
141
+unsafe fn cached_compile(
142
+    expr: &str,
143
+    fcinfo: pg_sys::FunctionCallInfo,
144
+) -> *const CachedParse {
111145
     // `pg_func_extra` allocates the cache in `fn_mcxt` and registers a drop
112146
     // callback, so the owned `CompiledExpr` is freed on context teardown.
113
-    let mut cache: PgBox<Option<(String, CompiledExpr)>> = pg_func_extra(fcinfo, || None);
147
+    let mut cache: PgBox<Option<(String, CachedParse)>> = pg_func_extra(fcinfo, || None);
114148
     let stale = match &*cache {
115149
         Some((cached, _)) => cached != expr,
116150
         None => true,
117151
     };
118152
     if stale {
119153
         match compile(expr) {
120
-            Ok(compiled) => *cache = Some((expr.to_owned(), compiled)),
154
+            Ok(compiled) => {
155
+                let parsed = CachedParse {
156
+                    compiled,
157
+                    candidates: name_run_candidates(expr),
158
+                };
159
+                *cache = Some((expr.to_owned(), parsed));
160
+            }
121161
             Err(e) => error!("feel_eval failed: {e}"),
122162
         }
123163
     }
124164
     match &*cache {
125
-        Some((_, compiled)) => compiled as *const CompiledExpr,
165
+        Some((_, parsed)) => parsed as *const CachedParse,
126166
         None => unreachable!("cache populated above"),
127167
     }
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>,
128175
 }
129176
 
130177
 /// Evaluate a FEEL expression as an **IMMUTABLE**, deterministic function — the
@@ -143,6 +190,14 @@
143190
 ///   `strict => true`): their UTC offset is read from the IANA tzdb, which can
144191
 ///   change. Fixed offsets (`+02:00`) and `Z` are tzdb-independent and fully
145192
 ///   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`].
146201
 ///
147202
 /// Math/regex builtins (`exp`/`log`/`sqrt`, `matches`/`replace`/`split`) are taken
148203
 /// as immutable; their results are stable except across a libc/`regex` upgrade —
@@ -163,24 +218,26 @@
163218
     fcinfo: pg_sys::FunctionCallInfo,
164219
 ) -> PgJsonb {
165220
     // Same per-call-site parse cache as `feel_eval`, plus the cached clock-free
166
-    // verdict so the static check is paid once per query, never per row.
167
-    let mut cache: PgBox<Option<(String, CompiledExpr, bool)>> =
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>)>> =
168224
         unsafe { pg_func_extra(fcinfo, || None) };
169225
     let stale = match &*cache {
170
-        Some((cached, _, _)) => cached != expr,
226
+        Some((cached, _, _, _)) => cached != expr,
171227
         None => true,
172228
     };
173229
     if stale {
174230
         match compile(expr) {
175231
             Ok(compiled) => {
176232
                 let clock_free = compiled.is_clock_free();
177
-                *cache = Some((expr.to_owned(), compiled, clock_free));
233
+                let candidates = name_run_candidates(expr);
234
+                *cache = Some((expr.to_owned(), compiled, clock_free, candidates));
178235
             }
179236
             Err(e) => error!("feel_eval_immutable failed: {e}"),
180237
         }
181238
     }
182
-    let (compiled, clock_free) = match &*cache {
183
-        Some((_, compiled, clock_free)) => (compiled, *clock_free),
239
+    let (compiled, clock_free, candidates) = match &*cache {
240
+        Some((_, compiled, clock_free, candidates)) => (compiled, *clock_free, candidates),
184241
         None => unreachable!("cache populated above"),
185242
     };
186243
     if !clock_free {
@@ -194,6 +251,17 @@
194251
     // IMMUTABLE function should be. Named zones are vetted away (RD-10).
195252
     let env = EvalEnv::new(&RustRegex, fixed_instant()).forbidding_named_zones();
196253
     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
+    }
197265
     eval_to_jsonb(compiled, &ctx, strict, &env)
198266
 }
199267
 
@@ -605,10 +673,68 @@
605673
     fn descendant_descends_into_nested_jsonb() {
606674
         let matched = Spi::get_one::<bool>(
607675
             r#"SELECT feel_eval('o ... name', '{"o": {"customer": {"name": "Ada"}}}'::jsonb)
608
-                       = '["Ada"]'::jsonb"#,
609
-        )
610
-        .expect("SPI query failed");
611
-        assert_eq!(matched, Some(true));
676
+                        = '["Ada"]'::jsonb"#,
677
+        )
678
+        .expect("SPI query failed");
679
+        assert_eq!(matched, Some(true));
680
+    }
681
+
682
+    // Special-character names (§10.3.1.6, ADR-47): the row's jsonb keys are the
683
+    // scope. `a-b` resolves to the KEY when bound, to subtraction otherwise; the
684
+    // fn_extra parse cache must not leak one reading into the other row.
685
+    #[pg_test]
686
+    fn special_char_name_resolves_from_jsonb_key() {
687
+        let matched = Spi::get_one::<bool>(
688
+            r#"SELECT feel_eval('a-b', '{"a-b": 5}'::jsonb) = '5'::jsonb"#,
689
+        )
690
+        .expect("SPI query failed");
691
+        assert_eq!(matched, Some(true));
692
+    }
693
+
694
+    #[pg_test]
695
+    fn special_char_name_unbound_is_subtraction() {
696
+        let matched =
697
+            Spi::get_one::<bool>(r#"SELECT feel_eval('a-b', '{"a": 7, "b": 3}'::jsonb) = '4'::jsonb"#)
698
+                .expect("SPI query failed");
699
+        assert_eq!(matched, Some(true));
700
+    }
701
+
702
+    #[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>(
723
+            r#"SELECT feel_eval_immutable('x.y', '{"x": {"y": 42}}'::jsonb) = '42'::jsonb"#,
724
+        )
725
+        .expect("SPI query failed");
726
+        assert_eq!(matched, Some(true));
727
+    }
728
+
729
+    #[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"
731
+    )]
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).
735
+        let _ = Spi::get_one::<bool>(
736
+            r#"SELECT feel_eval_immutable('a-b', '{"a-b": 5}'::jsonb) IS NOT NULL"#,
737
+        );
612738
     }
613739
 }
614740