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>
| Changeset | 301164fbfb23ef17a335eb3f5b6df7bf8de86c35 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 2f2a7100aa12 |
| Children | |
| Pushlog | by timo via ssh |
modified Cargo.lock +0 −1
| @@ -651,7 +651,6 @@ | ||
| 651 | 651 | "jiff", |
| 652 | 652 | "pgrx", |
| 653 | 653 | "pgrx-tests", |
| 654 | - "serde_json", | |
| 655 | 654 | ] |
| 656 | 655 | |
| 657 | 656 | [[package]] |
modified DECISIONS.md +65 −1
| @@ -758,7 +758,7 @@ | ||
| 758 | 758 | |
| 759 | 759 | | Seam | feel-pg | feel-wasm | feel-py | **feel-lua** | |
| 760 | 760 | | --- | --- | --- | --- | --- | |
| 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) | | |
| 762 | 762 | | Regex dialect | `RustRegex` (RD-1) | `JsRegex` (ADR-16) | `PyRegex`/`re` (RD-4) | `RustRegex` (RD-7) | |
| 763 | 763 | | Temporal repr | ISO→native cast (RD-2) | JS `Date` / ISO (ADR-18) | `datetime`/`dateutil` (RD-5) | ISO-8601 string (RD-8) | |
| 764 | 764 | | Clock | transaction start | `Date.now()` | system (`jiff::now()`) | system (`jiff::now()`) | |
| @@ -1020,6 +1020,70 @@ | ||
| 1020 | 1020 | - **If flipped (drop the immutable subset):** delete `feel_eval_immutable` and the two |
| 1021 | 1021 | feel-core seams (`is_clock_free`, `forbidding_named_zones`/`vet_named_zone`); callers |
| 1022 | 1022 | 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. | |
| 1023 | 1087 | |
| 1024 | 1088 | ## Roadmap: deferred scope (recorded, not yet built) |
| 1025 | 1089 | |
modified README.md +6 −0
| @@ -194,6 +194,12 @@ | ||
| 194 | 194 | # ((feel_eval_immutable('applicant.age >= 18 and applicant.income > 50000', data))); |
| 195 | 195 | ``` |
| 196 | 196 | |
| 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 | + | |
| 197 | 203 | Note: the pgrx extension name is `feel_pg` (underscored) — see |
| 198 | 204 | `crates/feel-pg/feel_pg.control`. |
| 199 | 205 | |
modified crates/feel-pg/Cargo.toml +0 −1
| @@ -21,7 +21,6 @@ | ||
| 21 | 21 | |
| 22 | 22 | [dependencies] |
| 23 | 23 | pgrx = "=0.18.1" |
| 24 | -serde_json.workspace = true | |
| 25 | 24 | feel-core = { path = "../feel-core" } |
| 26 | 25 | # Used only to build the `EvalEnv` instant from the transaction start timestamp |
| 27 | 26 | # (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 @@ | ||
| 299 | 299 | // Input (approaches B and A): jsonb -> Context. |
| 300 | 300 | // --------------------------------------------------------------------------- |
| 301 | 301 | |
| 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. | |
| 309 | 308 | /// |
| 310 | 309 | /// Mirrors the old serde `context_from_json`: a jsonb object → context; a jsonb |
| 311 | 310 | /// `null` → empty context; any other shape → `Err`. |
| 312 | 311 | /// |
| 313 | 312 | /// # Safety |
| 314 | 313 | /// `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> { | |
| 317 | 316 | let container = ptr::addr_of_mut!((*jsonb).root); |
| 318 | 317 | if (*container).header & pg_sys::JB_FOBJECT == 0 { |
| 319 | 318 | // 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) { | |
| 321 | 320 | Value::Null => Ok(Context::new()), |
| 322 | 321 | _ => Err("expected a JSON object as the FEEL context".to_owned()), |
| 323 | 322 | }; |
| @@ -337,42 +336,41 @@ | ||
| 337 | 336 | let key = jbv_string(&v); |
| 338 | 337 | // WJB_VALUE (with skipNested, a nested container arrives as jbvBinary) |
| 339 | 338 | let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); |
| 340 | - let val = jbv_to_value(&v, lazy); | |
| 339 | + let val = jbv_to_value(&v); | |
| 341 | 340 | ctx.insert(key, val); |
| 342 | 341 | } |
| 343 | 342 | Ok(ctx) |
| 344 | 343 | } |
| 345 | 344 | |
| 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 { | |
| 350 | 348 | match jbv.type_ { |
| 351 | 349 | pg_sys::jbvType::jbvNull => Value::Null, |
| 352 | 350 | pg_sys::jbvType::jbvBool => Value::Boolean(jbv.val.boolean), |
| 353 | 351 | pg_sys::jbvType::jbvString => Value::String(jbv_string(jbv)), |
| 354 | 352 | pg_sys::jbvType::jbvNumeric => numeric_to_value(jbv.val.numeric), |
| 355 | 353 | 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 | + }))) | |
| 368 | 363 | } |
| 369 | 364 | _ => Value::Null, |
| 370 | 365 | } |
| 371 | 366 | } |
| 372 | 367 | |
| 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 { | |
| 376 | 374 | use pg_sys::JsonbIteratorToken::*; |
| 377 | 375 | let mut it = pg_sys::JsonbIteratorInit(container); |
| 378 | 376 | let mut v = pg_sys::JsonbValue::default(); |
| @@ -386,7 +384,7 @@ | ||
| 386 | 384 | } |
| 387 | 385 | let key = jbv_string(&v); |
| 388 | 386 | 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)); | |
| 390 | 388 | } |
| 391 | 389 | Value::Context(map) |
| 392 | 390 | } |
| @@ -394,7 +392,7 @@ | ||
| 394 | 392 | // A jsonb scalar is stored as a single-element raw-scalar array. |
| 395 | 393 | if v.val.array.rawScalar { |
| 396 | 394 | 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); | |
| 398 | 396 | let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); // WJB_END_ARRAY |
| 399 | 397 | scalar |
| 400 | 398 | } else { |
| @@ -404,7 +402,7 @@ | ||
| 404 | 402 | if tok == WJB_END_ARRAY { |
| 405 | 403 | break; |
| 406 | 404 | } |
| 407 | - items.push(jbv_to_value(&v, lazy)); | |
| 405 | + items.push(jbv_to_value(&v)); | |
| 408 | 406 | } |
| 409 | 407 | Value::List(items) |
| 410 | 408 | } |
| @@ -471,14 +469,14 @@ | ||
| 471 | 469 | Value::Null |
| 472 | 470 | } else { |
| 473 | 471 | // Shallow: a nested container stays a Foreign. |
| 474 | - jbv_to_value(&res, true) | |
| 472 | + jbv_to_value(&res) | |
| 475 | 473 | } |
| 476 | 474 | } |
| 477 | 475 | } |
| 478 | 476 | |
| 479 | 477 | fn force(&self) -> Value { |
| 480 | 478 | // 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) } | |
| 482 | 480 | } |
| 483 | 481 | |
| 484 | 482 | fn as_any(&self) -> &dyn Any { |
modified crates/feel-pg/src/lib.rs +47 −149
| @@ -15,7 +15,10 @@ | ||
| 15 | 15 | //! named time zones, leaving the result a pure function of `(expr, context)` (RD-10). |
| 16 | 16 | //! |
| 17 | 17 | //! 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. | |
| 19 | 22 | //! |
| 20 | 23 | //! Regex dialect: this wrapper keeps feel-core's default `RustRegex` provider, so |
| 21 | 24 | //! `matches`/`replace`/`split` use the Rust regex dialect (ADR-15/ADR-16). A |
| @@ -38,9 +41,9 @@ | ||
| 38 | 41 | //! across rows of a query and agree with PostgreSQL's own `now()`. |
| 39 | 42 | |
| 40 | 43 | 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}; | |
| 44 | 47 | |
| 45 | 48 | mod jsonb; |
| 46 | 49 | use jsonb::PgJsonb; |
| @@ -66,18 +69,19 @@ | ||
| 66 | 69 | /// transaction — exactly why PostgreSQL's own `transaction_timestamp()` is STABLE. |
| 67 | 70 | /// **PARALLEL SAFE**: evaluation has no global mutable state, I/O or randomness, |
| 68 | 71 | /// 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` | |
| 75 | 79 | /// args): a SQL `NULL` `expr` or `context` returns `NULL` unevaluated; the `context` |
| 76 | 80 | /// `DEFAULT '{}'` keeps `feel_eval('1 + 1')` working — only an *explicit* `NULL` |
| 77 | 81 | /// context short-circuits. It is *not* IMMUTABLE (`now()` varies across |
| 78 | 82 | /// transactions) — see [`feel_eval_immutable`] for the deterministic subset usable |
| 79 | 83 | /// in expression indexes (RD-10). |
| 80 | -#[pg_extern(stable, parallel_safe, cost = 500)] | |
| 84 | +#[pg_extern(stable, parallel_safe, cost = 100)] | |
| 81 | 85 | fn feel_eval( |
| 82 | 86 | expr: &str, |
| 83 | 87 | context: default!(PgJsonb, "'{}'::jsonb"), |
| @@ -90,7 +94,7 @@ | ||
| 90 | 94 | // `now()`/`today()` read the transaction start (ADR-18) — constant per query, |
| 91 | 95 | // matching PostgreSQL's own `now()`/`transaction_timestamp()`. |
| 92 | 96 | let env = EvalEnv::new(&RustRegex, transaction_start()); |
| 93 | - let ctx = build_context(&context, DEFAULT_LAZY_INPUT); | |
| 97 | + let ctx = build_context(&context); | |
| 94 | 98 | eval_to_jsonb(compiled, &ctx, strict, &env) |
| 95 | 99 | } |
| 96 | 100 | |
| @@ -144,14 +148,14 @@ | ||
| 144 | 148 | /// as immutable; their results are stable except across a libc/`regex` upgrade — |
| 145 | 149 | /// the same pragmatic stance PostgreSQL takes for its own such functions, after |
| 146 | 150 | /// 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`]. | |
| 148 | 152 | /// |
| 149 | 153 | /// ```sql |
| 150 | 154 | /// -- Index a FEEL predicate over a jsonb column: |
| 151 | 155 | /// CREATE INDEX ON applications |
| 152 | 156 | /// ((feel_eval_immutable('applicant.age >= 18 and applicant.income > 50000', data))); |
| 153 | 157 | /// ``` |
| 154 | -#[pg_extern(immutable, parallel_safe, cost = 500)] | |
| 158 | +#[pg_extern(immutable, parallel_safe, cost = 100)] | |
| 155 | 159 | fn feel_eval_immutable( |
| 156 | 160 | expr: &str, |
| 157 | 161 | context: default!(PgJsonb, "'{}'::jsonb"), |
| @@ -189,23 +193,19 @@ | ||
| 189 | 193 | // is a fixed sentinel — keeping this function free of any ambient read, as an |
| 190 | 194 | // IMMUTABLE function should be. Named zones are vetted away (RD-10). |
| 191 | 195 | 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); | |
| 193 | 197 | eval_to_jsonb(compiled, &ctx, strict, &env) |
| 194 | 198 | } |
| 195 | 199 | |
| 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 { | |
| 205 | 205 | // SAFETY: `context.0` is the live, detoasted argument jsonb, valid for the whole |
| 206 | 206 | // call; any lazy `Foreign` derived from it is confined to this call — the output |
| 207 | 207 | // 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) } | |
| 209 | 209 | .unwrap_or_else(|e| error!("invalid feel context: {e}")) |
| 210 | 210 | } |
| 211 | 211 | |
| @@ -222,67 +222,6 @@ | ||
| 222 | 222 | Ok(value) => PgJsonb(jsonb::value_to_jsonb(&value)), |
| 223 | 223 | Err(e) => error!("feel_eval failed: {e}"), |
| 224 | 224 | } |
| 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 | - ) | |
| 286 | 225 | } |
| 287 | 226 | |
| 288 | 227 | /// A fixed, arbitrary instant (the Unix epoch, UTC) for [`feel_eval_immutable`]'s |
| @@ -311,39 +250,6 @@ | ||
| 311 | 250 | .unwrap_or_else(|_| jiff::Zoned::now()) |
| 312 | 251 | } |
| 313 | 252 | |
| 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 | - | |
| 347 | 253 | #[cfg(any(test, feature = "pg_test"))] |
| 348 | 254 | #[pg_schema] |
| 349 | 255 | mod tests { |
| @@ -558,41 +464,33 @@ | ||
| 558 | 464 | } |
| 559 | 465 | |
| 560 | 466 | #[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>( | |
| 568 | 475 | 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) | |
| 574 | 477 | 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) | |
| 589 | 490 | "#, |
| 590 | 491 | ) |
| 591 | 492 | .expect("SPI query failed"); |
| 592 | - assert_eq!( | |
| 593 | - mismatches, None, | |
| 594 | - "input strategies disagree:\n{mismatches:?}" | |
| 595 | - ); | |
| 493 | + assert_eq!(all_match, Some(true)); | |
| 596 | 494 | } |
| 597 | 495 | |
| 598 | 496 | #[pg_test] |