| @@ -80,15 +80,33 @@ |
| 80 | 80 | #[pg_extern(stable, parallel_safe, cost = 500)] |
| 81 | 81 | fn feel_eval( |
| 82 | 82 | expr: &str, |
| 83 | | - context: default!(JsonB, "'{}'::jsonb"), |
| 83 | + context: default!(PgJsonb, "'{}'::jsonb"), |
| 84 | 84 | strict: default!(bool, "false"), |
| 85 | 85 | fcinfo: pg_sys::FunctionCallInfo, |
| 86 | 86 | ) -> 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 { |
| 88 | 107 | // `pg_func_extra` allocates the cache in `fn_mcxt` and registers a drop |
| 89 | 108 | // 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); |
| 92 | 110 | let stale = match &*cache { |
| 93 | 111 | Some((cached, _)) => cached != expr, |
| 94 | 112 | None => true, |
| @@ -99,15 +117,10 @@ |
| 99 | 117 | Err(e) => error!("feel_eval failed: {e}"), |
| 100 | 118 | } |
| 101 | 119 | } |
| 102 | | - let compiled = match &*cache { |
| 103 | | - Some((_, compiled)) => compiled, |
| 120 | + match &*cache { |
| 121 | + Some((_, compiled)) => compiled as *const CompiledExpr, |
| 104 | 122 | 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 | + } |
| 111 | 124 | } |
| 112 | 125 | |
| 113 | 126 | /// Evaluate a FEEL expression as an **IMMUTABLE**, deterministic function — the |
| @@ -141,7 +154,7 @@ |
| 141 | 154 | #[pg_extern(immutable, parallel_safe, cost = 500)] |
| 142 | 155 | fn feel_eval_immutable( |
| 143 | 156 | expr: &str, |
| 144 | | - context: default!(JsonB, "'{}'::jsonb"), |
| 157 | + context: default!(PgJsonb, "'{}'::jsonb"), |
| 145 | 158 | strict: default!(bool, "false"), |
| 146 | 159 | fcinfo: pg_sys::FunctionCallInfo, |
| 147 | 160 | ) -> PgJsonb { |
| @@ -176,22 +189,100 @@ |
| 176 | 189 | // is a fixed sentinel — keeping this function free of any ambient read, as an |
| 177 | 190 | // IMMUTABLE function should be. Named zones are vetted away (RD-10). |
| 178 | 191 | 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}")) |
| 180 | 210 | } |
| 181 | 211 | |
| 182 | 212 | /// 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) { |
| 189 | 219 | Ok(value) if strict && value.contains_error() => { |
| 190 | 220 | error!("feel_eval: result is null from a type or domain error (strict mode)") |
| 191 | 221 | } |
| 192 | 222 | Ok(value) => PgJsonb(jsonb::value_to_jsonb(&value)), |
| 193 | 223 | Err(e) => error!("feel_eval failed: {e}"), |
| 194 | 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 | + ) |
| 195 | 286 | } |
| 196 | 287 | |
| 197 | 288 | /// A fixed, arbitrary instant (the Unix epoch, UTC) for [`feel_eval_immutable`]'s |
| @@ -412,13 +503,17 @@ |
| 412 | 503 | assert_eq!(matched, Some(true)); |
| 413 | 504 | } |
| 414 | 505 | |
| 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 | + )] |
| 416 | 509 | fn immutable_rejects_now() { |
| 417 | 510 | // now() can never be IMMUTABLE -> hard ERROR (not a silent null). |
| 418 | 511 | let _ = Spi::get_one::<bool>("SELECT feel_eval_immutable('now()') IS NOT NULL"); |
| 419 | 512 | } |
| 420 | 513 | |
| 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 | + )] |
| 422 | 517 | fn immutable_rejects_today() { |
| 423 | 518 | let _ = Spi::get_one::<bool>("SELECT feel_eval_immutable('today() = today()') IS NOT NULL"); |
| 424 | 519 | } |
| @@ -460,6 +555,44 @@ |
| 460 | 555 | CREATE INDEX ON feel_idx_ok ((feel_eval_immutable('applicant.age >= 18', data)));", |
| 461 | 556 | ) |
| 462 | 557 | .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 | + ); |
| 463 | 596 | } |
| 464 | 597 | |
| 465 | 598 | #[pg_test] |