Public repository: timo / feel

Reader

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

perf(pg)!: lazy binary jsonb the default; drop serde, eager, COST→100 (RD-11)

public

perf(pg)!: lazy binary jsonb the default; drop serde, eager, COST→100 (RD-11)

M4 benchmark (pg18, release, JIT+parallelism off, warm, N=1M) decides the input
strategy. Per-call cost over two workloads:

  decision expr, small nested ctx :  serde 3.6µs  eager 2.6µs  lazy 2.3µs
  selective deep path, ~30-key ctx:  serde 116µs  eager 120µs  lazy 7.9µs

Lazy (A+C) wins both — ~15x on selective access into a large context — and eager
never wins. So lazy is the default and the ONLY input path; eager (B) and the
three temporary feel_eval_bench_* variants are removed. Binary output alone took
full feel_eval from 13.5µs to 3.6µs; lazy binary input brings it to ~2.3µs, on par
with feel-wasm (~2.0µs).

- Simplify the jsonb walkers to lazy-only (drop the `lazy` parameter).
- Drop the serde_json dependency and the serde context_from_json/json_to_value /
  value_to_json helpers — feel-pg no longer round-trips jsonb through text.
- COST 500 -> 100 on both functions (~= PL/pgSQL's default; feel_eval is now
  roughly an ordinary function cost-wise). Update the COST rationale, module doc,
  and README perf note.
- Repurpose the strategy-agreement pg_test into a lazy-input correctness test
  (deep navigation + returning a sub-object, which forces a Foreign back to jsonb).
- DECISIONS.md: record RD-11 (binary jsonb boundary, lazy input, the longjmp-safety
  stance, the lazy lifetime invariant), note RD-10's revisit trigger fired, and
  flip the ADR-21 matrix row (feel-pg input is now lazy JsonbForeign).

All 28 feel-pg pg_tests pass on pg18; production feel_eval measures 2.30µs/call.

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

modified Cargo.lock +0 −1

@@ -651,7 +651,6 @@
651651
  "jiff",
652652
  "pgrx",
653653
  "pgrx-tests",
654
- "serde_json",
655654
 ]
656655
 
657656
 [[package]]

modified DECISIONS.md +65 −1

@@ -758,7 +758,7 @@
758758
 
759759
 | Seam | feel-pg | feel-wasm | feel-py | **feel-lua** |
760760
 | --- | --- | --- | --- | --- |
761
-| Input mapping | eager `jsonb` | lazy `JsForeign` | lazy `PyForeign` | lazy `LuaForeign` (RD-9) |
761
+| Input mapping | lazy `JsonbForeign` (RD-11) | lazy `JsForeign` | lazy `PyForeign` | lazy `LuaForeign` (RD-9) |
762762
 | Regex dialect | `RustRegex` (RD-1) | `JsRegex` (ADR-16) | `PyRegex`/`re` (RD-4) | `RustRegex` (RD-7) |
763763
 | Temporal repr | ISO→native cast (RD-2) | JS `Date` / ISO (ADR-18) | `datetime`/`dateutil` (RD-5) | ISO-8601 string (RD-8) |
764764
 | Clock | transaction start | `Date.now()` | system (`jiff::now()`) | system (`jiff::now()`) |
@@ -1020,6 +1020,70 @@
10201020
 - **If flipped (drop the immutable subset):** delete `feel_eval_immutable` and the two
10211021
   feel-core seams (`is_clock_free`, `forbidding_named_zones`/`vet_named_zone`); callers
10221022
   needing an index would precompute the value into a stored column via a trigger.
1023
+- **Update (2026-06-17):** the "optimising the jsonb boundary away" revisit trigger
1024
+  fired the same day — see **RD-11**. The pgrx `JsonB` text round-trip is gone, the
1025
+  per-call cost dropped from ~13.5 µs to ~2.3 µs, and `COST` was re-tuned 500 → 100 on
1026
+  both functions.
1027
+
1028
+### RD-11: feel-pg binary jsonb boundary — direct C API, lazy input (no serde)
1029
+
1030
+- **Weighed:** RD-10 measured `feel_eval` at ~13.5 µs/call and pinned the cost on the
1031
+  pgrx `JsonB` boundary, which round-trips jsonb↔text↔`serde_json` **twice** per call
1032
+  (`jsonb_out` + `serde_json::from_str` in; `serde_json::to_string` + `jsonb_in` out) —
1033
+  not FEEL evaluation (a native-binary jsonb PL/pgSQL UDF is ~1.2 µs) and not jsonb
1034
+  access. PostgreSQL exposes its **binary** jsonb container API
1035
+  (`pushJsonbValue`/`JsonbValueToJsonb` to build; `JsonbIterator*` /
1036
+  `getKeyJsonValueFromContainer` to read), all `#[pg_guard] extern "C-unwind"`-wrapped
1037
+  in pgrx. Three independent levers: **C** (binary *output*), **B** (eager binary
1038
+  *input*), **A** (lazy binary input via a `JsonbForeign` behind feel-core's
1039
+  `ForeignObject` seam, ADR-21 — the same lazy boundary feel-py/wasm/lua use). Gate:
1040
+  only proceed past C if it reliably reproduces the serde output across arrays/complex
1041
+  shapes.
1042
+- **Decision (2026-06-17, implemented):** all three built; **C is the gate and passed**
1043
+  (a pg_test asserts binary output `=` expected jsonb across deep/mixed nesting, empty
1044
+  containers, the 2⁵³ integer/float boundary, unicode, every temporal type, and
1045
+  null/error). A benchmark (pg18, release, JIT + parallelism off, warm, N = 1M; baseline
1046
+  ~0.2 µs/row subtracted) decided the input strategy over two workloads:
1047
+  - decision expr `if person.age >= 18 then "adult" else "minor"`, small nested ctx:
1048
+    serde-in + binary-out **3.6 µs**, eager **2.6 µs**, lazy **2.3 µs**.
1049
+  - selective deep path `k17.sub.value` over a ~30-key nested ctx: serde **116 µs**,
1050
+    eager **120 µs**, lazy **7.9 µs**.
1051
+  **Lazy (A+C) wins both** — marginally on the small case, **~15×** on selective access
1052
+  into a large context (it walks only the navigated path) — and eager never wins (it
1053
+  materialises the whole context, even trailing serde on the big one). So **lazy is the
1054
+  default and the only input path**; eager (B) is not offered. Binary output alone took
1055
+  full `feel_eval` from 13.5 → 3.6 µs; lazy binary input brings it to ~2.3 µs, on par
1056
+  with feel-wasm (~2.0 µs). The `serde_json` dependency is dropped from feel-pg. `COST`
1057
+  re-tuned 500 → **100** (≈ PL/pgSQL's default; feel_eval is now roughly an ordinary
1058
+  function cost-wise).
1059
+  - **Boundary newtype:** `PgJsonb(*mut pg_sys::Jsonb)` replaces pgrx `JsonB` as the arg
1060
+    and return type; its `FromDatum` only detoasts (no `jsonb_out`), `IntoDatum` is
1061
+    `JsonbPGetDatum`, and the `ArgAbi`/`BoxRet`/`SqlTranslatable` impls mirror pgrx's own
1062
+    `JsonB` so it drops straight into `#[pg_extern]` as a SQL `jsonb`.
1063
+  - **Safety — the "no ereport/longjmp through Rust frames" cost — is moderate and
1064
+    bounded.** Every jsonb C function is `#[pg_guard] extern "C-unwind"`, so a Postgres
1065
+    `ereport`/`longjmp` (e.g. a jsonb size-limit error from `JsonbValueToJsonb`) is
1066
+    caught at the FFI boundary and re-raised as a Rust panic that unwinds *normally*
1067
+    (destructors run, no stack corruption), surfacing as the original PG ERROR. No manual
1068
+    `PgTryBuilder` is needed for stack safety; a genuine encode error is left to
1069
+    propagate as a real ERROR rather than masked as null. The read path does not
1070
+    `ereport` for valid in-memory jsonb; `AnyNumeric` guards its own f64↔numeric
1071
+    conversions. One nuance the lazy *output* surfaced and fixed: a `Foreign` forced
1072
+    mid-encode yields a temporary sub-`Value` dropped before the final
1073
+    `JsonbValueToJsonb`, so `value_to_jsonb` copies every emitted string/key into an
1074
+    output arena (numerics are palloc'd, scalars inline) rather than borrowing.
1075
+  - **Lazy lifetime invariant:** a `JsonbForeign` holds a `*mut JsonbContainer` valid
1076
+    only for the call — created from the live argument, used during `evaluate_with_env`,
1077
+    forced to owned jsonb on output, dropped before return; it never escapes
1078
+    `eval_to_jsonb`. A `Value` carrying one is `!Send` (ADR-21), fine for the
1079
+    single-threaded per-call evaluation.
1080
+- **Revisit trigger:** a workload that consistently consumes the *entire* context (where
1081
+  eager's single walk could beat lazy's per-key `Foreign` allocations) — reintroduce
1082
+  eager (B) as an opt-in then; evidence that `COST 100` mis-orders plans; or a pgrx
1083
+  change to how the jsonb FFI is guarded.
1084
+- **If flipped (back to serde):** restore the pgrx `JsonB` arg/return type and the
1085
+  serde `context_from_json`/`value_to_json` helpers, re-add the `serde_json` dependency,
1086
+  and bump `COST` back toward 500.
10231087
 
10241088
 ## Roadmap: deferred scope (recorded, not yet built)
10251089
 

modified README.md +6 −0

@@ -194,6 +194,12 @@
194194
 #     ((feel_eval_immutable('applicant.age >= 18 and applicant.income > 50000', data)));
195195
 ```
196196
 
197
+The jsonb boundary uses PostgreSQL's binary jsonb C API directly (no `serde_json`)
198
+and reads the context lazily — nested objects are navigated on demand (ADR-21), so
199
+reading one deep path out of a large context is cheap. A parse-cached `feel_eval` of
200
+a low-to-medium expression runs ~2.3 µs/call on pg18, on par with the WASM build
201
+(`COST 100`; RD-11).
202
+
197203
 Note: the pgrx extension name is `feel_pg` (underscored) — see
198204
 `crates/feel-pg/feel_pg.control`.
199205
 

modified crates/feel-pg/Cargo.toml +0 −1

@@ -21,7 +21,6 @@
2121
 
2222
 [dependencies]
2323
 pgrx = "=0.18.1"
24
-serde_json.workspace = true
2524
 feel-core = { path = "../feel-core" }
2625
 # Used only to build the `EvalEnv` instant from the transaction start timestamp
2726
 # (ADR-18); the temporal value logic — and the IANA tzdb bundle (via feel-core's

modified crates/feel-pg/src/jsonb.rs +33 −35

@@ -299,25 +299,24 @@
299299
 // Input (approaches B and A): jsonb -> Context.
300300
 // ---------------------------------------------------------------------------
301301
 
302
-/// Build a [`Context`] from the context jsonb argument.
303
-///
304
-/// The top level is always materialised into the `Context` (the evaluator looks up
305
-/// variables there). With `lazy = false` (approach **B**) the whole graph is walked
306
-/// eagerly into concrete `Value`s; with `lazy = true` (approach **A**, ADR-21) only
307
-/// the top-level members are materialised and each nested container becomes a
308
-/// [`Value::Foreign`] resolved on demand.
302
+/// Build a [`Context`] from the context jsonb argument, **lazily** (approach A,
303
+/// ADR-21 — the M4 benchmark's winner, RD-11): the top-level members are
304
+/// materialised into the `Context` (where the evaluator looks up variables), but a
305
+/// nested container becomes a [`Value::Foreign`] resolved only when the FEEL dot
306
+/// navigates into it. A context whose deep structure is never touched is never
307
+/// walked — the per-call win grows with context size and path selectivity.
309308
 ///
310309
 /// Mirrors the old serde `context_from_json`: a jsonb object → context; a jsonb
311310
 /// `null` → empty context; any other shape → `Err`.
312311
 ///
313312
 /// # Safety
314313
 /// `jsonb` must be a valid, fully detoasted `Jsonb` pointer that outlives the
315
-/// returned `Context` (and, for `lazy`, every `Foreign` derived from it).
316
-pub unsafe fn context_from_jsonb(jsonb: *mut pg_sys::Jsonb, lazy: bool) -> Result<Context, String> {
314
+/// returned `Context` and every `Foreign` derived from it (see the module note).
315
+pub unsafe fn context_from_jsonb(jsonb: *mut pg_sys::Jsonb) -> Result<Context, String> {
317316
     let container = ptr::addr_of_mut!((*jsonb).root);
318317
     if (*container).header & pg_sys::JB_FOBJECT == 0 {
319318
         // Not an object: accept only a JSON null (-> empty context), like serde.
320
-        return match container_to_value(container, false) {
319
+        return match container_to_value(container) {
321320
             Value::Null => Ok(Context::new()),
322321
             _ => Err("expected a JSON object as the FEEL context".to_owned()),
323322
         };
@@ -337,42 +336,41 @@
337336
         let key = jbv_string(&v);
338337
         // WJB_VALUE (with skipNested, a nested container arrives as jbvBinary)
339338
         let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true);
340
-        let val = jbv_to_value(&v, lazy);
339
+        let val = jbv_to_value(&v);
341340
         ctx.insert(key, val);
342341
     }
343342
     Ok(ctx)
344343
 }
345344
 
346
-/// Convert one `JsonbValue` to a `feel-core` [`Value`]. With `lazy`, a nested
347
-/// container (`jbvBinary`) becomes a [`Value::Foreign`]; otherwise it is walked
348
-/// eagerly.
349
-unsafe fn jbv_to_value(jbv: &pg_sys::JsonbValue, lazy: bool) -> Value {
345
+/// Convert one `JsonbValue` to a *shallow* `feel-core` [`Value`]: scalars eagerly, a
346
+/// nested container (`jbvBinary`) to a lazy [`Value::Foreign`] ([`JsonbForeign`]).
347
+unsafe fn jbv_to_value(jbv: &pg_sys::JsonbValue) -> Value {
350348
     match jbv.type_ {
351349
         pg_sys::jbvType::jbvNull => Value::Null,
352350
         pg_sys::jbvType::jbvBool => Value::Boolean(jbv.val.boolean),
353351
         pg_sys::jbvType::jbvString => Value::String(jbv_string(jbv)),
354352
         pg_sys::jbvType::jbvNumeric => numeric_to_value(jbv.val.numeric),
355353
         pg_sys::jbvType::jbvBinary => {
356
-            let container = jbv.val.binary.data;
357
-            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)]
364
-                Value::Foreign(Foreign(Arc::new(JsonbForeign { container })))
365
-            } else {
366
-                container_to_value(container, false)
367
-            }
354
+            // `JsonbForeign` is intentionally `!Send`/`!Sync` (it holds a raw
355
+            // container pointer valid only for this call), which is exactly ADR-21's
356
+            // model: a `Value` carrying a `Foreign` is `!Send`. The `Arc` is mandated
357
+            // by feel-core's `Foreign(Arc<dyn ForeignObject>)` and never crosses
358
+            // threads (evaluation is single-threaded per call).
359
+            #[allow(clippy::arc_with_non_send_sync)]
360
+            Value::Foreign(Foreign(Arc::new(JsonbForeign {
361
+                container: jbv.val.binary.data,
362
+            })))
368363
         }
369364
         _ => Value::Null,
370365
     }
371366
 }
372367
 
373
-/// Walk a jsonb container one… or, when `!lazy`, all the way down, into a `Value`.
374
-/// An object → `Context`, an array → `List`, a raw-scalar pseudo-array → its scalar.
375
-unsafe fn container_to_value(container: *mut pg_sys::JsonbContainer, lazy: bool) -> Value {
368
+/// Walk a jsonb container **one level** into a `Value` (an object → `Context`, an
369
+/// array → `List`, a raw-scalar pseudo-array → its scalar). Members are shallow
370
+/// (nested containers stay lazy [`Value::Foreign`]s via [`jbv_to_value`]), so this
371
+/// is both the top-level force of a [`JsonbForeign`] and the incremental step that
372
+/// keeps laziness going.
373
+unsafe fn container_to_value(container: *mut pg_sys::JsonbContainer) -> Value {
376374
     use pg_sys::JsonbIteratorToken::*;
377375
     let mut it = pg_sys::JsonbIteratorInit(container);
378376
     let mut v = pg_sys::JsonbValue::default();
@@ -386,7 +384,7 @@
386384
                 }
387385
                 let key = jbv_string(&v);
388386
                 let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true);
389
-                map.insert(key, jbv_to_value(&v, lazy));
387
+                map.insert(key, jbv_to_value(&v));
390388
             }
391389
             Value::Context(map)
392390
         }
@@ -394,7 +392,7 @@
394392
             // A jsonb scalar is stored as a single-element raw-scalar array.
395393
             if v.val.array.rawScalar {
396394
                 let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); // WJB_ELEM
397
-                let scalar = jbv_to_value(&v, lazy);
395
+                let scalar = jbv_to_value(&v);
398396
                 let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); // WJB_END_ARRAY
399397
                 scalar
400398
             } else {
@@ -404,7 +402,7 @@
404402
                     if tok == WJB_END_ARRAY {
405403
                         break;
406404
                     }
407
-                    items.push(jbv_to_value(&v, lazy));
405
+                    items.push(jbv_to_value(&v));
408406
                 }
409407
                 Value::List(items)
410408
             }
@@ -471,14 +469,14 @@
471469
                 Value::Null
472470
             } else {
473471
                 // Shallow: a nested container stays a Foreign.
474
-                jbv_to_value(&res, true)
472
+                jbv_to_value(&res)
475473
             }
476474
         }
477475
     }
478476
 
479477
     fn force(&self) -> Value {
480478
         // One level: members are shallow, so nested containers stay lazy.
481
-        unsafe { container_to_value(self.container, true) }
479
+        unsafe { container_to_value(self.container) }
482480
     }
483481
 
484482
     fn as_any(&self) -> &dyn Any {

modified crates/feel-pg/src/lib.rs +47 −149

@@ -15,7 +15,10 @@
1515
 //! named time zones, leaving the result a pure function of `(expr, context)` (RD-10).
1616
 //!
1717
 //! The JSON/jsonb boundary mapping lives here (not in `feel-core`), per the
18
-//! project's boundary-mapping decision.
18
+//! project's boundary-mapping decision. It uses PostgreSQL's **binary** jsonb C
19
+//! API directly — no `serde_json` round-trip — and reads the context **lazily**
20
+//! (nested objects navigated on demand, ADR-21); see the [`jsonb`] module and
21
+//! RD-11.
1922
 //!
2023
 //! Regex dialect: this wrapper keeps feel-core's default `RustRegex` provider, so
2124
 //! `matches`/`replace`/`split` use the Rust regex dialect (ADR-15/ADR-16). A
@@ -38,9 +41,9 @@
3841
 //! across rows of a query and agree with PostgreSQL's own `now()`.
3942
 
4043
 use pgrx::prelude::*;
41
-use pgrx::{pg_func_extra, JsonB, PgBox};
42
-
43
-use feel_core::{compile, CompiledExpr, Context, EvalEnv, RustRegex, Value};
44
+use pgrx::{pg_func_extra, PgBox};
45
+
46
+use feel_core::{compile, CompiledExpr, Context, EvalEnv, RustRegex};
4447
 
4548
 mod jsonb;
4649
 use jsonb::PgJsonb;
@@ -66,18 +69,19 @@
6669
 /// transaction — exactly why PostgreSQL's own `transaction_timestamp()` is STABLE.
6770
 /// **PARALLEL SAFE**: evaluation has no global mutable state, I/O or randomness,
6871
 /// and a parallel worker is a separate process with its own `fn_extra` cache.
69
-/// `COST 500`: a parse-cached eval of a low-to-medium expression measures
70
-/// ~13.5 µs/call on pg18 — ≈ 560× a baseline `procost`-1 C call (one
71
-/// `cpu_operator_cost` ≈ 24 ns here), rounded down (conservative). Most of that is
72
-/// the pgrx `JsonB` boundary (jsonb↔text↔`serde_json`, twice per call), not FEEL
73
-/// evaluation — so the planner keeps feel_eval out of hot loops and orders cheaper
74
-/// quals ahead of it (RD-10). The function is STRICT (pgrx default for non-`Option`
72
+/// `COST 100`: a parse-cached eval of a low-to-medium expression over a small
73
+/// context measures ~2.3 µs/call on pg18 — ≈ 95× a baseline `procost`-1 C call (one
74
+/// `cpu_operator_cost` ≈ 24 ns here), rounded to PostgreSQL's own PL/pgSQL default
75
+/// of 100, which feel_eval is now roughly on par with (RD-11). The earlier `COST
76
+/// 500` reflected the pgrx `JsonB` text↔`serde_json` boundary (~13.5 µs); the binary
77
+/// jsonb boundary (RD-11) removed that, so the planner can now schedule feel_eval
78
+/// more like an ordinary function. The function is STRICT (pgrx default for non-`Option`
7579
 /// args): a SQL `NULL` `expr` or `context` returns `NULL` unevaluated; the `context`
7680
 /// `DEFAULT '{}'` keeps `feel_eval('1 + 1')` working — only an *explicit* `NULL`
7781
 /// context short-circuits. It is *not* IMMUTABLE (`now()` varies across
7882
 /// transactions) — see [`feel_eval_immutable`] for the deterministic subset usable
7983
 /// in expression indexes (RD-10).
80
-#[pg_extern(stable, parallel_safe, cost = 500)]
84
+#[pg_extern(stable, parallel_safe, cost = 100)]
8185
 fn feel_eval(
8286
     expr: &str,
8387
     context: default!(PgJsonb, "'{}'::jsonb"),
@@ -90,7 +94,7 @@
9094
     // `now()`/`today()` read the transaction start (ADR-18) — constant per query,
9195
     // matching PostgreSQL's own `now()`/`transaction_timestamp()`.
9296
     let env = EvalEnv::new(&RustRegex, transaction_start());
93
-    let ctx = build_context(&context, DEFAULT_LAZY_INPUT);
97
+    let ctx = build_context(&context);
9498
     eval_to_jsonb(compiled, &ctx, strict, &env)
9599
 }
96100
 
@@ -144,14 +148,14 @@
144148
 /// as immutable; their results are stable except across a libc/`regex` upgrade —
145149
 /// the same pragmatic stance PostgreSQL takes for its own such functions, after
146150
 /// which an index may need a one-off `REINDEX` (RD-10). `PARALLEL SAFE` and
147
-/// `COST 500` for the same reasons as [`feel_eval`].
151
+/// `COST 100` for the same reasons as [`feel_eval`].
148152
 ///
149153
 /// ```sql
150154
 /// -- Index a FEEL predicate over a jsonb column:
151155
 /// CREATE INDEX ON applications
152156
 ///   ((feel_eval_immutable('applicant.age >= 18 and applicant.income > 50000', data)));
153157
 /// ```
154
-#[pg_extern(immutable, parallel_safe, cost = 500)]
158
+#[pg_extern(immutable, parallel_safe, cost = 100)]
155159
 fn feel_eval_immutable(
156160
     expr: &str,
157161
     context: default!(PgJsonb, "'{}'::jsonb"),
@@ -189,23 +193,19 @@
189193
     // is a fixed sentinel — keeping this function free of any ambient read, as an
190194
     // IMMUTABLE function should be. Named zones are vetted away (RD-10).
191195
     let env = EvalEnv::new(&RustRegex, fixed_instant()).forbidding_named_zones();
192
-    let ctx = build_context(&context, DEFAULT_LAZY_INPUT);
196
+    let ctx = build_context(&context);
193197
     eval_to_jsonb(compiled, &ctx, strict, &env)
194198
 }
195199
 
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 {
200
+/// Build the evaluation [`Context`] from the binary jsonb argument, lazily (approach
201
+/// A, ADR-21) — the M4 benchmark's clear winner over the eager and serde walks
202
+/// (RD-11): a nested context is navigated on demand, so an expression that reads one
203
+/// deep path out of a large context pays almost nothing.
204
+fn build_context(context: &PgJsonb) -> Context {
205205
     // SAFETY: `context.0` is the live, detoasted argument jsonb, valid for the whole
206206
     // call; any lazy `Foreign` derived from it is confined to this call — the output
207207
     // path forces it to owned jsonb, so it never escapes.
208
-    unsafe { jsonb::context_from_jsonb(context.0, lazy) }
208
+    unsafe { jsonb::context_from_jsonb(context.0) }
209209
         .unwrap_or_else(|e| error!("invalid feel context: {e}"))
210210
 }
211211
 
@@ -222,67 +222,6 @@
222222
         Ok(value) => PgJsonb(jsonb::value_to_jsonb(&value)),
223223
         Err(e) => error!("feel_eval failed: {e}"),
224224
     }
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
-    )
286225
 }
287226
 
288227
 /// A fixed, arbitrary instant (the Unix epoch, UTC) for [`feel_eval_immutable`]'s
@@ -311,39 +250,6 @@
311250
         .unwrap_or_else(|_| jiff::Zoned::now())
312251
 }
313252
 
314
-/// Build a [`Context`] from a JSON object, mapping each member value with
315
-/// [`json_to_value`].
316
-fn context_from_json(json: &serde_json::Value) -> Result<Context, String> {
317
-    let mut ctx = Context::new();
318
-    match json {
319
-        serde_json::Value::Object(map) => {
320
-            for (key, val) in map {
321
-                ctx.insert(key.clone(), json_to_value(val));
322
-            }
323
-            Ok(ctx)
324
-        }
325
-        serde_json::Value::Null => Ok(ctx),
326
-        other => Err(format!("expected a JSON object, got {other}")),
327
-    }
328
-}
329
-
330
-/// Map a JSON value to a `feel-core` [`Value`]. Numbers, booleans, strings,
331
-/// arrays (-> list), objects (-> context) and null are supported.
332
-fn json_to_value(json: &serde_json::Value) -> Value {
333
-    match json {
334
-        serde_json::Value::Number(num) => num.as_f64().map(Value::Number).unwrap_or(Value::Null),
335
-        serde_json::Value::Bool(b) => Value::Boolean(*b),
336
-        serde_json::Value::String(s) => Value::String(s.clone()),
337
-        serde_json::Value::Array(arr) => Value::List(arr.iter().map(json_to_value).collect()),
338
-        serde_json::Value::Object(map) => Value::Context(
339
-            map.iter()
340
-                .map(|(k, v)| (k.clone(), json_to_value(v)))
341
-                .collect(),
342
-        ),
343
-        serde_json::Value::Null => Value::Null,
344
-    }
345
-}
346
-
347253
 #[cfg(any(test, feature = "pg_test"))]
348254
 #[pg_schema]
349255
 mod tests {
@@ -558,41 +464,33 @@
558464
     }
559465
 
560466
     #[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>(
467
+    fn lazy_binary_input_reads_every_shape() {
468
+        // The lazy binary input walk (approach A, ADR-21 — RD-11's chosen default)
469
+        // must read every context shape correctly: scalar reads, deep path
470
+        // navigation through nested objects, list builtins over a context list,
471
+        // for-loops, absent keys (-> null), and — crucially — returning a whole
472
+        // sub-object or sub-list, which exercises the output path forcing a lazy
473
+        // `Foreign` recursively back to jsonb.
474
+        let all_match = Spi::get_one::<bool>(
568475
             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')
476
+            SELECT bool_and(feel_eval(expr, ctx) IS NOT DISTINCT FROM expected)
574477
             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))
478
+                ('a + 1',            '{"a": 41}'::jsonb,                              '42'::jsonb),
479
+                ('p.address.city',   '{"p": {"address": {"city": "Berlin"}}}'::jsonb, '"Berlin"'::jsonb),
480
+                ('sum(xs)',          '{"xs": [1, 2, 3, 4]}'::jsonb,                   '10'::jsonb),
481
+                ('count(p.tags)',    '{"p": {"tags": ["x", "y", "z"]}}'::jsonb,       '3'::jsonb),
482
+                ('for x in xs return x * 2', '{"xs": [10, 20, 30]}'::jsonb,           '[20, 40, 60]'::jsonb),
483
+                -- return a whole nested sub-object: forces the lazy Foreign back out
484
+                ('p',  '{"p": {"a": 1, "b": [2, {"c": 3}], "d": null}}'::jsonb,
485
+                       '{"a": 1, "b": [2, {"c": 3}], "d": null}'::jsonb),
486
+                ('p.tags',           '{"p": {"tags": ["x", "y"]}}'::jsonb,            '["x", "y"]'::jsonb),
487
+                ('missing.key',      '{"present": 1}'::jsonb,                         'null'::jsonb),
488
+                ('flag and 1 < 2',   '{"flag": true}'::jsonb,                         'true'::jsonb)
489
+            ) AS t(expr, ctx, expected)
589490
             "#,
590491
         )
591492
         .expect("SPI query failed");
592
-        assert_eq!(
593
-            mismatches, None,
594
-            "input strategies disagree:\n{mismatches:?}"
595
-        );
493
+        assert_eq!(all_match, Some(true));
596494
     }
597495
 
598496
     #[pg_test]