feat(feel-pg): scope-dependent name-run handling per row (ADR-47)
draft feat/special-char-names
feat(feel-pg): scope-dependent name-run handling per row (ADR-47) The fn_extra parse cache is probe-free, so a special-character name run (a-b, x.y) cached from one row could mis-read on another that binds the joined name. Both SQL functions now guard per row via feel_core::name_run_candidates (computed once per call site): - feel_eval: no candidate bound in the row's jsonb -> the cached parse is already scope-correct (the fast path; plain path access pays only a few key lookups). A candidate bound -> re-parse against that row's keys, so a name reading and an arithmetic reading coexist across rows of the same query. - feel_eval_immutable: a candidate bound -> loud ERROR (RD-10 style): an index expression must parse identically for every row, never silently flip its meaning. The guard fires only on the actual ambiguity, so ordinary path indexes are unaffected. 5 new pg tests (37 total), run via cargo pgrx test pg18.
| Changeset | 5b344709d08e8c74f7becf9ef4fce5e0a49107b8 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 9ea85e0a23f4 |
| Children | |
| Pushlog | by timo via ssh |
modified crates/feel-pg/src/lib.rs +150 −24
| @@ -13,6 +13,10 @@ | ||
| 13 | 13 | //! (its `now()`/`today()` read the transaction clock); `feel_eval_immutable` is the |
| 14 | 14 | //! deterministic subset for expression indexes — it rejects `now()`/`today()` and |
| 15 | 15 | //! named time zones, leaving the result a pure function of `(expr, context)` (RD-10). |
| 16 | +//! Scope-dependent special-character names (`a-b`, §10.3.1.6, ADR-47) are handled | |
| 17 | +//! per row: `feel_eval` re-parses against a row that binds one, `feel_eval_immutable` | |
| 18 | +//! rejects such a row loudly (an index expression must parse identically for every | |
| 19 | +//! row). | |
| 16 | 20 | //! |
| 17 | 21 | //! The JSON/jsonb boundary mapping lives here (not in `feel-core`), per the |
| 18 | 22 | //! project's boundary-mapping decision. It uses PostgreSQL's **binary** jsonb C |
| @@ -43,7 +47,10 @@ | ||
| 43 | 47 | use pgrx::prelude::*; |
| 44 | 48 | use pgrx::{pg_func_extra, PgBox}; |
| 45 | 49 | |
| 46 | -use feel_core::{compile, CompiledExpr, Context, EvalEnv, RustRegex}; | |
| 50 | +use feel_core::{ | |
| 51 | + compile, compile_with_probe, name_run_candidates, CompiledExpr, Context, EvalEnv, | |
| 52 | + RustRegex, ScopeProbe, | |
| 53 | +}; | |
| 47 | 54 | |
| 48 | 55 | mod jsonb; |
| 49 | 56 | use jsonb::PgJsonb; |
| @@ -63,6 +70,14 @@ | ||
| 63 | 70 | /// context), keyed on the expression text. So when `expr` is a query constant — |
| 64 | 71 | /// the usual case, e.g. one decision over many rows — it is parsed once per query |
| 65 | 72 | /// and only re-parsed if the text actually changes. No global/session cache. |
| 73 | +/// | |
| 74 | +/// The cached parse is **probe-free** (ADR-47): special-character name runs | |
| 75 | +/// (`a-b`, `x.y`) are guarded per row via [`feel_core::name_run_candidates`] — | |
| 76 | +/// when a row binds none of them, the cached parse is already scope-correct | |
| 77 | +/// (the fast path; plain `applicant.age` path access pays only a few key | |
| 78 | +/// lookups); when a row *does* bind one, that row's expression is re-parsed | |
| 79 | +/// against its keys (§10.3.1.6), so a name and an arithmetic reading can coexist | |
| 80 | +/// across rows of the same query. | |
| 66 | 81 | /// |
| 67 | 82 | /// Declared **STABLE** (not VOLATILE): the only non-argument input is the |
| 68 | 83 | /// transaction start timestamp behind `now()`/`today()`, constant within a |
| @@ -89,42 +104,74 @@ | ||
| 89 | 104 | fcinfo: pg_sys::FunctionCallInfo, |
| 90 | 105 | ) -> PgJsonb { |
| 91 | 106 | // SAFETY: see [`cached_compile`] — the returned pointer is valid for the query. |
| 92 | - let compiled = unsafe { &*cached_compile(expr, fcinfo) }; | |
| 107 | + let parsed = unsafe { &*cached_compile(expr, fcinfo) }; | |
| 108 | + let compiled = &parsed.compiled; | |
| 93 | 109 | |
| 94 | 110 | // `now()`/`today()` read the transaction start (ADR-18) — constant per query, |
| 95 | 111 | // matching PostgreSQL's own `now()`/`transaction_timestamp()`. |
| 96 | 112 | let env = EvalEnv::new(&RustRegex, transaction_start()); |
| 97 | 113 | let ctx = build_context(&context); |
| 98 | - eval_to_jsonb(compiled, &ctx, strict, &env) | |
| 99 | -} | |
| 100 | - | |
| 101 | -/// Parse `expr`, caching the [`CompiledExpr`] in the call site's `fn_extra` slot | |
| 102 | -/// (allocated in `flinfo->fn_mcxt`, which lives for the whole query — never the | |
| 103 | -/// per-row context), keyed on the text. A query constant is thus parsed once and | |
| 104 | -/// reused across rows; the text only re-parses if it actually changes. Returns a | |
| 105 | -/// pointer into that cache, valid for the rest of the query. | |
| 114 | + // ADR-47: a special-character name run is resolved against the row's scope. | |
| 115 | + // No candidate bound -> the cached probe-free parse is already correct (the | |
| 116 | + // overwhelming case); otherwise re-parse against this row's keys — µs-cheap, | |
| 117 | + // and only rows that actually bind such a name pay it. | |
| 118 | + let row_scoped = if parsed.candidates.iter().any(|c| ctx.contains(c)) { | |
| 119 | + Some(compile_with_probe(expr, &ctx).unwrap_or_else(|e| error!("feel_eval failed: {e}"))) | |
| 120 | + } else { | |
| 121 | + None | |
| 122 | + }; | |
| 123 | + eval_to_jsonb( | |
| 124 | + row_scoped.as_ref().unwrap_or(compiled), | |
| 125 | + &ctx, | |
| 126 | + strict, | |
| 127 | + &env, | |
| 128 | + ) | |
| 129 | +} | |
| 130 | + | |
| 131 | +/// Parse `expr` probe-free, caching it plus its [`feel_core::name_run_candidates`] | |
| 132 | +/// in the call site's `fn_extra` slot (allocated in `flinfo->fn_mcxt`, which lives | |
| 133 | +/// for the whole query — never the per-row context), keyed on the text. A query | |
| 134 | +/// constant is thus parsed once and reused across rows; the text only re-parses | |
| 135 | +/// if it actually changes. Returns a pointer into that cache, valid for the rest | |
| 136 | +/// of the query. | |
| 106 | 137 | /// |
| 107 | 138 | /// # Safety |
| 108 | 139 | /// `fcinfo` must be the genuine call info injected by the pgrx wrapper. The |
| 109 | 140 | /// returned pointer must not outlive the query (the `fn_mcxt`). |
| 110 | -unsafe fn cached_compile(expr: &str, fcinfo: pg_sys::FunctionCallInfo) -> *const CompiledExpr { | |
| 141 | +unsafe fn cached_compile( | |
| 142 | + expr: &str, | |
| 143 | + fcinfo: pg_sys::FunctionCallInfo, | |
| 144 | +) -> *const CachedParse { | |
| 111 | 145 | // `pg_func_extra` allocates the cache in `fn_mcxt` and registers a drop |
| 112 | 146 | // callback, so the owned `CompiledExpr` is freed on context teardown. |
| 113 | - let mut cache: PgBox<Option<(String, CompiledExpr)>> = pg_func_extra(fcinfo, || None); | |
| 147 | + let mut cache: PgBox<Option<(String, CachedParse)>> = pg_func_extra(fcinfo, || None); | |
| 114 | 148 | let stale = match &*cache { |
| 115 | 149 | Some((cached, _)) => cached != expr, |
| 116 | 150 | None => true, |
| 117 | 151 | }; |
| 118 | 152 | if stale { |
| 119 | 153 | match compile(expr) { |
| 120 | - Ok(compiled) => *cache = Some((expr.to_owned(), compiled)), | |
| 154 | + Ok(compiled) => { | |
| 155 | + let parsed = CachedParse { | |
| 156 | + compiled, | |
| 157 | + candidates: name_run_candidates(expr), | |
| 158 | + }; | |
| 159 | + *cache = Some((expr.to_owned(), parsed)); | |
| 160 | + } | |
| 121 | 161 | Err(e) => error!("feel_eval failed: {e}"), |
| 122 | 162 | } |
| 123 | 163 | } |
| 124 | 164 | match &*cache { |
| 125 | - Some((_, compiled)) => compiled as *const CompiledExpr, | |
| 165 | + Some((_, parsed)) => parsed as *const CachedParse, | |
| 126 | 166 | None => unreachable!("cache populated above"), |
| 127 | 167 | } |
| 168 | +} | |
| 169 | + | |
| 170 | +/// The per-call-site cached parse: the probe-free [`CompiledExpr`] plus the | |
| 171 | +/// special-character name candidates guarding it (ADR-47). | |
| 172 | +struct CachedParse { | |
| 173 | + compiled: CompiledExpr, | |
| 174 | + candidates: Vec<String>, | |
| 128 | 175 | } |
| 129 | 176 | |
| 130 | 177 | /// Evaluate a FEEL expression as an **IMMUTABLE**, deterministic function — the |
| @@ -143,6 +190,14 @@ | ||
| 143 | 190 | /// `strict => true`): their UTC offset is read from the IANA tzdb, which can |
| 144 | 191 | /// change. Fixed offsets (`+02:00`) and `Z` are tzdb-independent and fully |
| 145 | 192 | /// supported — all an index needs. |
| 193 | +/// - A special-character name run (`a-b`, `x.y`) that the row's context | |
| 194 | +/// **resolves as a name** is rejected with an ERROR (ADR-47): the §10.3.1.6 | |
| 195 | +/// parse depends on the scope, so such a row would silently flip the indexed | |
| 196 | +/// meaning between rows (name here, arithmetic there). The guard fires only | |
| 197 | +/// on the *actual* ambiguity — a row that binds none of the expression's | |
| 198 | +/// [`feel_core::name_run_candidates`] (the ordinary case, e.g. plain path | |
| 199 | +/// access) evaluates from the cached parse. Use explicit parentheses | |
| 200 | +/// (`(a)-(b)`) to force the operator reading, or [`feel_eval`]. | |
| 146 | 201 | /// |
| 147 | 202 | /// Math/regex builtins (`exp`/`log`/`sqrt`, `matches`/`replace`/`split`) are taken |
| 148 | 203 | /// as immutable; their results are stable except across a libc/`regex` upgrade — |
| @@ -163,24 +218,26 @@ | ||
| 163 | 218 | fcinfo: pg_sys::FunctionCallInfo, |
| 164 | 219 | ) -> PgJsonb { |
| 165 | 220 | // Same per-call-site parse cache as `feel_eval`, plus the cached clock-free |
| 166 | - // verdict so the static check is paid once per query, never per row. | |
| 167 | - let mut cache: PgBox<Option<(String, CompiledExpr, bool)>> = | |
| 221 | + // verdict so the static check is paid once per query, never per row. The | |
| 222 | + // name-run candidates ride along for the per-row guard below. | |
| 223 | + let mut cache: PgBox<Option<(String, CompiledExpr, bool, Vec<String>)>> = | |
| 168 | 224 | unsafe { pg_func_extra(fcinfo, || None) }; |
| 169 | 225 | let stale = match &*cache { |
| 170 | - Some((cached, _, _)) => cached != expr, | |
| 226 | + Some((cached, _, _, _)) => cached != expr, | |
| 171 | 227 | None => true, |
| 172 | 228 | }; |
| 173 | 229 | if stale { |
| 174 | 230 | match compile(expr) { |
| 175 | 231 | Ok(compiled) => { |
| 176 | 232 | let clock_free = compiled.is_clock_free(); |
| 177 | - *cache = Some((expr.to_owned(), compiled, clock_free)); | |
| 233 | + let candidates = name_run_candidates(expr); | |
| 234 | + *cache = Some((expr.to_owned(), compiled, clock_free, candidates)); | |
| 178 | 235 | } |
| 179 | 236 | Err(e) => error!("feel_eval_immutable failed: {e}"), |
| 180 | 237 | } |
| 181 | 238 | } |
| 182 | - let (compiled, clock_free) = match &*cache { | |
| 183 | - Some((_, compiled, clock_free)) => (compiled, *clock_free), | |
| 239 | + let (compiled, clock_free, candidates) = match &*cache { | |
| 240 | + Some((_, compiled, clock_free, candidates)) => (compiled, *clock_free, candidates), | |
| 184 | 241 | None => unreachable!("cache populated above"), |
| 185 | 242 | }; |
| 186 | 243 | if !clock_free { |
| @@ -194,6 +251,17 @@ | ||
| 194 | 251 | // IMMUTABLE function should be. Named zones are vetted away (RD-10). |
| 195 | 252 | let env = EvalEnv::new(&RustRegex, fixed_instant()).forbidding_named_zones(); |
| 196 | 253 | let ctx = build_context(&context); |
| 254 | + // ADR-47: an index expression must parse identically for every row. A context | |
| 255 | + // that resolves one of the expression's name-run candidates would flip the | |
| 256 | + // parse per row (name vs arithmetic) — reject loudly (RD-10 style) instead of | |
| 257 | + // silently indexing different meanings. | |
| 258 | + if candidates.iter().any(|c| ctx.contains(c)) { | |
| 259 | + error!( | |
| 260 | + "feel_eval_immutable: context resolves a special-character name run in the \ | |
| 261 | + expression, so its parse is scope-dependent (10.3.1.6) and cannot be \ | |
| 262 | + IMMUTABLE; write explicit parentheses (e.g. (a)-(b)) or use feel_eval" | |
| 263 | + ); | |
| 264 | + } | |
| 197 | 265 | eval_to_jsonb(compiled, &ctx, strict, &env) |
| 198 | 266 | } |
| 199 | 267 | |
| @@ -605,10 +673,68 @@ | ||
| 605 | 673 | fn descendant_descends_into_nested_jsonb() { |
| 606 | 674 | let matched = Spi::get_one::<bool>( |
| 607 | 675 | r#"SELECT feel_eval('o ... name', '{"o": {"customer": {"name": "Ada"}}}'::jsonb) |
| 608 | - = '["Ada"]'::jsonb"#, | |
| 609 | - ) | |
| 610 | - .expect("SPI query failed"); | |
| 611 | - assert_eq!(matched, Some(true)); | |
| 676 | + = '["Ada"]'::jsonb"#, | |
| 677 | + ) | |
| 678 | + .expect("SPI query failed"); | |
| 679 | + assert_eq!(matched, Some(true)); | |
| 680 | + } | |
| 681 | + | |
| 682 | + // Special-character names (§10.3.1.6, ADR-47): the row's jsonb keys are the | |
| 683 | + // scope. `a-b` resolves to the KEY when bound, to subtraction otherwise; the | |
| 684 | + // fn_extra parse cache must not leak one reading into the other row. | |
| 685 | + #[pg_test] | |
| 686 | + fn special_char_name_resolves_from_jsonb_key() { | |
| 687 | + let matched = Spi::get_one::<bool>( | |
| 688 | + r#"SELECT feel_eval('a-b', '{"a-b": 5}'::jsonb) = '5'::jsonb"#, | |
| 689 | + ) | |
| 690 | + .expect("SPI query failed"); | |
| 691 | + assert_eq!(matched, Some(true)); | |
| 692 | + } | |
| 693 | + | |
| 694 | + #[pg_test] | |
| 695 | + fn special_char_name_unbound_is_subtraction() { | |
| 696 | + let matched = | |
| 697 | + Spi::get_one::<bool>(r#"SELECT feel_eval('a-b', '{"a": 7, "b": 3}'::jsonb) = '4'::jsonb"#) | |
| 698 | + .expect("SPI query failed"); | |
| 699 | + assert_eq!(matched, Some(true)); | |
| 700 | + } | |
| 701 | + | |
| 702 | + #[pg_test] | |
| 703 | + fn special_char_name_parse_is_per_row_not_cached_across_rows() { | |
| 704 | + // The SAME expression text in ONE query must read as a NAME on rows that | |
| 705 | + // bind `a-b` and as subtraction on rows that do not — the candidate check | |
| 706 | + // (name_run_candidates) routes ambiguous rows through a fresh probe parse. | |
| 707 | + let matched = Spi::get_one::<bool>( | |
| 708 | + r#"SELECT feel_eval('a-b', jsonb_build_object('a-b', 5)) = '5'::jsonb | |
| 709 | + AND feel_eval('a-b', jsonb_build_object('a', 7, 'b', 3)) = '4'::jsonb | |
| 710 | + AND feel_eval('a-b', jsonb_build_object('a-b', 5)) = '5'::jsonb"#, | |
| 711 | + ) | |
| 712 | + .expect("SPI query failed"); | |
| 713 | + assert_eq!(matched, Some(true)); | |
| 714 | + } | |
| 715 | + | |
| 716 | + #[pg_test] | |
| 717 | + fn immutable_uses_cached_parse_for_plain_path_access() { | |
| 718 | + // `x.y` HAS a name-run pattern (candidate `x.y`) but the row binds no | |
| 719 | + // such key: the cached probe-free parse (path access) is used. The guard | |
| 720 | + // fires only on the actual ambiguity, so ordinary path indexes — the | |
| 721 | + // core RD-10 use case — are unaffected. | |
| 722 | + let matched = Spi::get_one::<bool>( | |
| 723 | + r#"SELECT feel_eval_immutable('x.y', '{"x": {"y": 42}}'::jsonb) = '42'::jsonb"#, | |
| 724 | + ) | |
| 725 | + .expect("SPI query failed"); | |
| 726 | + assert_eq!(matched, Some(true)); | |
| 727 | + } | |
| 728 | + | |
| 729 | + #[pg_test( | |
| 730 | + error = "feel_eval_immutable: context resolves a special-character name run in the expression, so its parse is scope-dependent (10.3.1.6) and cannot be IMMUTABLE; write explicit parentheses (e.g. (a)-(b)) or use feel_eval" | |
| 731 | + )] | |
| 732 | + fn immutable_rejects_row_resolved_name_run() { | |
| 733 | + // A row that resolves `a-b` as a name would flip the indexed meaning | |
| 734 | + // between rows — a loud ERROR, never a silent flip (RD-10 style). | |
| 735 | + let _ = Spi::get_one::<bool>( | |
| 736 | + r#"SELECT feel_eval_immutable('a-b', '{"a-b": 5}'::jsonb) IS NOT NULL"#, | |
| 737 | + ); | |
| 612 | 738 | } |
| 613 | 739 | } |
| 614 | 740 | |