Public repository: timo / feel

Reader

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

perf(pg): binary jsonb input — eager (B) and lazy (A) walks (RD-11)

public

perf(pg): binary jsonb input — eager (B) and lazy (A) walks (RD-11)

Replace the serde input boundary (jsonb_out + serde_json::from_str) with the
binary container API, in two flavours behind `context_from_jsonb(_, lazy)`:

- eager (B): walk the whole context jsonb into a concrete Context up front via
  JsonbIteratorInit/Next.
- lazy (A, ADR-21): materialise only the top-level members; a nested container
  becomes a Value::Foreign (JsonbForeign) whose get()/force() resolve through the
  jsonb C API (getKeyJsonValueFromContainer) only when the FEEL dot navigates in
  — the same seam feel-py/wasm/lua use. JsonbForeign holds a *mut JsonbContainer
  valid only for the call and never escapes eval_to_jsonb.

feel_eval / feel_eval_immutable take `context: PgJsonb` and build the Context via
the (provisional) DEFAULT_LAZY_INPUT path. The parse cache is factored into
`cached_compile`. Three temporary benchmark variants — feel_eval_bench_{serde,
eager,lazy} — differ only in the input decode so an in-SQL count() isolates the
boundary cost (M4); they are removed once the default is chosen.

Fix a use-after-free this surfaced: when the lazy path's output forces a Foreign
mid-stream, the forced sub-Value is a temporary dropped before the final
JsonbValueToJsonb, so value_to_jsonb now copies every emitted string/key into the
output arena (numerics are palloc'd, scalars inline) instead of borrowing — the
pointers handed to Postgres stay valid regardless of where the Value came from.

A new pg_test asserts serde == eager == lazy across scalar reads, deep path
navigation, list builtins, for-loops, returning a whole sub-object (exercising
the Foreign→jsonb forcing), and absent keys. All 28 feel-pg pg_tests pass on pg18.

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

modified crates/feel-pg/src/jsonb.rs +23 −15

@@ -150,9 +150,13 @@
150150
 /// * `Foreign` (only reachable via the lazy input path A) is **forced** recursively
151151
 ///   to jsonb — never nulled.
152152
 pub fn value_to_jsonb(value: &Value) -> *mut pg_sys::Jsonb {
153
-    // Owns ISO-8601 strings produced for temporals so their bytes stay alive until
154
-    // `JsonbValueToJsonb` copies them; growing the Vec never moves a String's heap
155
-    // buffer, so the pointers we hand to Postgres stay valid.
153
+    // Owns every string and object key we emit, so their bytes stay alive until
154
+    // `JsonbValueToJsonb` copies them at the end. This is load-bearing for the lazy
155
+    // input path (A): a `Foreign` forced mid-stream yields a *temporary* sub-`Value`
156
+    // that is dropped before the final encode, so we must copy out of it eagerly
157
+    // rather than point at it. (Growing the Vec never moves a `String`'s heap
158
+    // buffer, so the raw pointers we hand to Postgres stay valid; numerics are
159
+    // palloc'd, booleans/null are inline — all outlive the temporary too.)
156160
     let mut arena: Vec<String> = Vec::new();
157161
     unsafe { build_root(value, &mut arena) }
158162
 }
@@ -205,10 +209,8 @@
205209
         Value::Context(map) => {
206210
             pg_sys::pushJsonbValue(state, WJB_BEGIN_OBJECT, ptr::null_mut());
207211
             for (key, val) in map {
208
-                // The key bytes live in the borrowed `Value` tree (the map), which
209
-                // outlives this whole build, so we can point at them directly.
210212
                 let mut key_jbv = pg_sys::JsonbValue::default();
211
-                set_string(&mut key_jbv, key.as_bytes());
213
+                set_string(&mut key_jbv, arena, key);
212214
                 pg_sys::pushJsonbValue(state, WJB_KEY, &mut key_jbv);
213215
                 add_value(state, WJB_VALUE, val, arena);
214216
             }
@@ -236,17 +238,13 @@
236238
             jbv.val.boolean = *b;
237239
         }
238240
         Value::Number(n) => set_number(&mut jbv, *n),
239
-        Value::String(s) => set_string(&mut jbv, s.as_bytes()),
241
+        Value::String(s) => set_string(&mut jbv, arena, s),
240242
         Value::Date(_)
241243
         | Value::Time(_)
242244
         | Value::DateTime(_)
243245
         | Value::YearsMonthsDuration(_)
244246
         | Value::DaysTimeDuration(_) => match feel_core::temporal::to_iso(value) {
245
-            Some(iso) => {
246
-                arena.push(iso);
247
-                let bytes = arena.last().unwrap().as_bytes();
248
-                set_string(&mut jbv, bytes);
249
-            }
247
+            Some(iso) => set_string(&mut jbv, arena, &iso),
250248
             None => jbv.type_ = pg_sys::jbvType::jbvNull,
251249
         },
252250
         // Null / Error / Function (and, defensively, containers) -> jsonb null.
@@ -255,9 +253,13 @@
255253
     jbv
256254
 }
257255
 
258
-/// Point a `jbvString` at `bytes` (not null-terminated — jsonb strings are
259
-/// length-counted). `bytes` must outlive the eventual `JsonbValueToJsonb`.
260
-unsafe fn set_string(jbv: &mut pg_sys::JsonbValue, bytes: &[u8]) {
256
+/// Make `jbv` a `jbvString` over a copy of `s` owned by `arena`, so its bytes
257
+/// outlive the eventual `JsonbValueToJsonb` even when `s` itself is borrowed from a
258
+/// temporary (a forced `Foreign`). jsonb strings are length-counted, not
259
+/// null-terminated.
260
+unsafe fn set_string(jbv: &mut pg_sys::JsonbValue, arena: &mut Vec<String>, s: &str) {
261
+    arena.push(s.to_owned());
262
+    let bytes = arena.last().unwrap().as_bytes();
261263
     jbv.type_ = pg_sys::jbvType::jbvString;
262264
     jbv.val.string.len = bytes.len() as c_int;
263265
     jbv.val.string.val = bytes.as_ptr() as *mut c_char;
@@ -353,6 +355,12 @@
353355
         pg_sys::jbvType::jbvBinary => {
354356
             let container = jbv.val.binary.data;
355357
             if lazy {
358
+                // `JsonbForeign` is intentionally `!Send`/`!Sync` (it holds a raw
359
+                // container pointer valid only for this call), which is exactly
360
+                // ADR-21's model: a `Value` carrying a `Foreign` is `!Send`. The
361
+                // `Arc` is mandated by feel-core's `Foreign(Arc<dyn ForeignObject>)`
362
+                // and never crosses threads (evaluation is single-threaded per call).
363
+                #[allow(clippy::arc_with_non_send_sync)]
356364
                 Value::Foreign(Foreign(Arc::new(JsonbForeign { container })))
357365
             } else {
358366
                 container_to_value(container, false)

modified crates/feel-pg/src/lib.rs +155 −22

@@ -80,15 +80,33 @@
8080
 #[pg_extern(stable, parallel_safe, cost = 500)]
8181
 fn feel_eval(
8282
     expr: &str,
83
-    context: default!(JsonB, "'{}'::jsonb"),
83
+    context: default!(PgJsonb, "'{}'::jsonb"),
8484
     strict: default!(bool, "false"),
8585
     fcinfo: pg_sys::FunctionCallInfo,
8686
 ) -> PgJsonb {
87
-    // SAFETY: `fcinfo` is the genuine call info injected by the pgrx wrapper;
87
+    // SAFETY: see [`cached_compile`] — the returned pointer is valid for the query.
88
+    let compiled = unsafe { &*cached_compile(expr, fcinfo) };
89
+
90
+    // `now()`/`today()` read the transaction start (ADR-18) — constant per query,
91
+    // matching PostgreSQL's own `now()`/`transaction_timestamp()`.
92
+    let env = EvalEnv::new(&RustRegex, transaction_start());
93
+    let ctx = build_context(&context, DEFAULT_LAZY_INPUT);
94
+    eval_to_jsonb(compiled, &ctx, strict, &env)
95
+}
96
+
97
+/// Parse `expr`, caching the [`CompiledExpr`] in the call site's `fn_extra` slot
98
+/// (allocated in `flinfo->fn_mcxt`, which lives for the whole query — never the
99
+/// per-row context), keyed on the text. A query constant is thus parsed once and
100
+/// reused across rows; the text only re-parses if it actually changes. Returns a
101
+/// pointer into that cache, valid for the rest of the query.
102
+///
103
+/// # Safety
104
+/// `fcinfo` must be the genuine call info injected by the pgrx wrapper. The
105
+/// returned pointer must not outlive the query (the `fn_mcxt`).
106
+unsafe fn cached_compile(expr: &str, fcinfo: pg_sys::FunctionCallInfo) -> *const CompiledExpr {
88107
     // `pg_func_extra` allocates the cache in `fn_mcxt` and registers a drop
89108
     // callback, so the owned `CompiledExpr` is freed on context teardown.
90
-    let mut cache: PgBox<Option<(String, CompiledExpr)>> =
91
-        unsafe { pg_func_extra(fcinfo, || None) };
109
+    let mut cache: PgBox<Option<(String, CompiledExpr)>> = pg_func_extra(fcinfo, || None);
92110
     let stale = match &*cache {
93111
         Some((cached, _)) => cached != expr,
94112
         None => true,
@@ -99,15 +117,10 @@
99117
             Err(e) => error!("feel_eval failed: {e}"),
100118
         }
101119
     }
102
-    let compiled = match &*cache {
103
-        Some((_, compiled)) => compiled,
120
+    match &*cache {
121
+        Some((_, compiled)) => compiled as *const CompiledExpr,
104122
         None => unreachable!("cache populated above"),
105
-    };
106
-
107
-    // `now()`/`today()` read the transaction start (ADR-18) — constant per query,
108
-    // matching PostgreSQL's own `now()`/`transaction_timestamp()`.
109
-    let env = EvalEnv::new(&RustRegex, transaction_start());
110
-    eval_to_jsonb(compiled, &context, strict, &env)
123
+    }
111124
 }
112125
 
113126
 /// Evaluate a FEEL expression as an **IMMUTABLE**, deterministic function — the
@@ -141,7 +154,7 @@
141154
 #[pg_extern(immutable, parallel_safe, cost = 500)]
142155
 fn feel_eval_immutable(
143156
     expr: &str,
144
-    context: default!(JsonB, "'{}'::jsonb"),
157
+    context: default!(PgJsonb, "'{}'::jsonb"),
145158
     strict: default!(bool, "false"),
146159
     fcinfo: pg_sys::FunctionCallInfo,
147160
 ) -> PgJsonb {
@@ -176,22 +189,100 @@
176189
     // is a fixed sentinel — keeping this function free of any ambient read, as an
177190
     // IMMUTABLE function should be. Named zones are vetted away (RD-10).
178191
     let env = EvalEnv::new(&RustRegex, fixed_instant()).forbidding_named_zones();
179
-    eval_to_jsonb(compiled, &context, strict, &env)
192
+    let ctx = build_context(&context, DEFAULT_LAZY_INPUT);
193
+    eval_to_jsonb(compiled, &ctx, strict, &env)
194
+}
195
+
196
+/// Provisional default for the context input strategy, pending the M4 benchmark
197
+/// (RD-11): `true` selects the lazy [`jsonb::context_from_jsonb`] walk (approach A,
198
+/// ADR-21) — nested context navigated on demand; `false` walks it eagerly
199
+/// (approach B). The benchmark functions below force each path explicitly.
200
+const DEFAULT_LAZY_INPUT: bool = true;
201
+
202
+/// Build the evaluation [`Context`] from the binary jsonb argument, lazily (ADR-21)
203
+/// or eagerly (RD-11).
204
+fn build_context(context: &PgJsonb, lazy: bool) -> Context {
205
+    // SAFETY: `context.0` is the live, detoasted argument jsonb, valid for the whole
206
+    // call; any lazy `Foreign` derived from it is confined to this call — the output
207
+    // path forces it to owned jsonb, so it never escapes.
208
+    unsafe { jsonb::context_from_jsonb(context.0, lazy) }
209
+        .unwrap_or_else(|e| error!("invalid feel context: {e}"))
180210
 }
181211
 
182212
 /// The eval-and-map-to-jsonb tail shared by [`feel_eval`] and
183
-/// [`feel_eval_immutable`]: build the [`Context`] from the jsonb argument, run the
184
-/// compiled expression under `env`, and apply the strict/lenient boundary (ADR-14).
185
-/// The volatility difference lives entirely in the `env` the caller supplies.
186
-fn eval_to_jsonb(compiled: &CompiledExpr, context: &JsonB, strict: bool, env: &EvalEnv) -> PgJsonb {
187
-    let ctx = context_from_json(&context.0).unwrap_or_else(|e| error!("invalid feel context: {e}"));
188
-    match compiled.evaluate_with_env(&ctx, env) {
213
+/// [`feel_eval_immutable`]: run the compiled expression against the prebuilt
214
+/// [`Context`] under `env`, and apply the strict/lenient boundary (ADR-14), then
215
+/// build the result jsonb directly (approach C). The volatility difference lives
216
+/// entirely in the `env`, and the input strategy in how `ctx` was built.
217
+fn eval_to_jsonb(compiled: &CompiledExpr, ctx: &Context, strict: bool, env: &EvalEnv) -> PgJsonb {
218
+    match compiled.evaluate_with_env(ctx, env) {
189219
         Ok(value) if strict && value.contains_error() => {
190220
             error!("feel_eval: result is null from a type or domain error (strict mode)")
191221
         }
192222
         Ok(value) => PgJsonb(jsonb::value_to_jsonb(&value)),
193223
         Err(e) => error!("feel_eval failed: {e}"),
194224
     }
225
+}
226
+
227
+// ---------------------------------------------------------------------------
228
+// Benchmark-only variants (RD-11). Temporary: removed once M4 picks the input
229
+// default. Evaluation is identical; they differ ONLY in how the context jsonb is
230
+// decoded, so an in-SQL `count()` over `generate_series` isolates the input
231
+// boundary cost. All three use the binary output path (approach C).
232
+// ---------------------------------------------------------------------------
233
+
234
+/// Serde-input baseline (binary output): the pre-RD-11 input boundary
235
+/// (`jsonb_out` + `serde_json::from_str`), for comparison against the binary walks.
236
+#[pg_extern(stable, parallel_safe, cost = 500)]
237
+fn feel_eval_bench_serde(
238
+    expr: &str,
239
+    context: default!(JsonB, "'{}'::jsonb"),
240
+    fcinfo: pg_sys::FunctionCallInfo,
241
+) -> PgJsonb {
242
+    let compiled = unsafe { &*cached_compile(expr, fcinfo) };
243
+    let ctx = context_from_json(&context.0).unwrap_or_else(|e| error!("invalid feel context: {e}"));
244
+    eval_to_jsonb(
245
+        compiled,
246
+        &ctx,
247
+        false,
248
+        &EvalEnv::new(&RustRegex, transaction_start()),
249
+    )
250
+}
251
+
252
+/// Eager binary input (approach B): the whole context jsonb is walked into a
253
+/// concrete [`Context`] up front.
254
+#[pg_extern(stable, parallel_safe, cost = 500)]
255
+fn feel_eval_bench_eager(
256
+    expr: &str,
257
+    context: default!(PgJsonb, "'{}'::jsonb"),
258
+    fcinfo: pg_sys::FunctionCallInfo,
259
+) -> PgJsonb {
260
+    let compiled = unsafe { &*cached_compile(expr, fcinfo) };
261
+    let ctx = build_context(&context, false);
262
+    eval_to_jsonb(
263
+        compiled,
264
+        &ctx,
265
+        false,
266
+        &EvalEnv::new(&RustRegex, transaction_start()),
267
+    )
268
+}
269
+
270
+/// Lazy binary input (approach A, ADR-21): only the top-level members are
271
+/// materialised; nested containers resolve through the FEEL dot on demand.
272
+#[pg_extern(stable, parallel_safe, cost = 500)]
273
+fn feel_eval_bench_lazy(
274
+    expr: &str,
275
+    context: default!(PgJsonb, "'{}'::jsonb"),
276
+    fcinfo: pg_sys::FunctionCallInfo,
277
+) -> PgJsonb {
278
+    let compiled = unsafe { &*cached_compile(expr, fcinfo) };
279
+    let ctx = build_context(&context, true);
280
+    eval_to_jsonb(
281
+        compiled,
282
+        &ctx,
283
+        false,
284
+        &EvalEnv::new(&RustRegex, transaction_start()),
285
+    )
195286
 }
196287
 
197288
 /// A fixed, arbitrary instant (the Unix epoch, UTC) for [`feel_eval_immutable`]'s
@@ -412,13 +503,17 @@
412503
         assert_eq!(matched, Some(true));
413504
     }
414505
 
415
-    #[pg_test(error = "feel_eval_immutable: expression calls now()/today(), which are not IMMUTABLE; use feel_eval instead")]
506
+    #[pg_test(
507
+        error = "feel_eval_immutable: expression calls now()/today(), which are not IMMUTABLE; use feel_eval instead"
508
+    )]
416509
     fn immutable_rejects_now() {
417510
         // now() can never be IMMUTABLE -> hard ERROR (not a silent null).
418511
         let _ = Spi::get_one::<bool>("SELECT feel_eval_immutable('now()') IS NOT NULL");
419512
     }
420513
 
421
-    #[pg_test(error = "feel_eval_immutable: expression calls now()/today(), which are not IMMUTABLE; use feel_eval instead")]
514
+    #[pg_test(
515
+        error = "feel_eval_immutable: expression calls now()/today(), which are not IMMUTABLE; use feel_eval instead"
516
+    )]
422517
     fn immutable_rejects_today() {
423518
         let _ = Spi::get_one::<bool>("SELECT feel_eval_immutable('today() = today()') IS NOT NULL");
424519
     }
@@ -460,6 +555,44 @@
460555
              CREATE INDEX ON feel_idx_ok ((feel_eval_immutable('applicant.age >= 18', data)));",
461556
         )
462557
         .expect("an expression index over feel_eval_immutable should be allowed");
558
+    }
559
+
560
+    #[pg_test]
561
+    fn input_paths_agree_serde_eager_lazy() {
562
+        // M2/M3: the eager (B) and lazy (A) binary input walks must agree with the
563
+        // serde walk (and each other) on every context shape — scalar reads, deep
564
+        // path navigation, 1-based list indexing, list-of-objects, list builtins,
565
+        // and returning a whole sub-object (which exercises the output path forcing
566
+        // a lazy `Foreign` back to jsonb). `feel_eval` itself uses the lazy default.
567
+        let mismatches = Spi::get_one::<String>(
568
+            r#"
569
+            SELECT string_agg(
570
+                     format('%s : serde=%s eager=%s lazy=%s', expr,
571
+                            feel_eval_bench_serde(expr, ctx),
572
+                            feel_eval_bench_eager(expr, ctx),
573
+                            feel_eval_bench_lazy(expr, ctx)), E'\n')
574
+            FROM (VALUES
575
+                ('a + 1',            '{"a": 41}'::jsonb),
576
+                ('p.address.city',   '{"p": {"address": {"city": "Berlin"}}}'::jsonb),
577
+                ('sum(xs)',          '{"xs": [1, 2, 3, 4]}'::jsonb),
578
+                ('count(p.tags)',    '{"p": {"tags": ["x", "y", "z"]}}'::jsonb),
579
+                ('for x in xs return x * 2', '{"xs": [10, 20, 30]}'::jsonb),
580
+                ('p',                '{"p": {"a": 1, "b": [2, {"c": 3}], "d": null}}'::jsonb),
581
+                ('p.tags',           '{"p": {"tags": ["x", "y"]}}'::jsonb),
582
+                ('missing.key',      '{"present": 1}'::jsonb),
583
+                ('flag and 1 < 2',   '{"flag": true}'::jsonb)
584
+            ) AS t(expr, ctx)
585
+            WHERE NOT (
586
+                    feel_eval_bench_serde(expr, ctx) = feel_eval_bench_eager(expr, ctx)
587
+                AND feel_eval_bench_eager(expr, ctx) = feel_eval_bench_lazy(expr, ctx)
588
+                AND feel_eval(expr, ctx)             = feel_eval_bench_lazy(expr, ctx))
589
+            "#,
590
+        )
591
+        .expect("SPI query failed");
592
+        assert_eq!(
593
+            mismatches, None,
594
+            "input strategies disagree:\n{mismatches:?}"
595
+        );
463596
     }
464597
 
465598
     #[pg_test]