Public repository: timo / feel

Reader

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

feat(pg): STABLE feel_eval and a new IMMUTABLE feel_eval_immutable (RD-10)

public

feat(pg): STABLE feel_eval and a new IMMUTABLE feel_eval_immutable (RD-10)

Declare the existing feel_eval STABLE, PARALLEL SAFE, COST 100 (it was the pgrx
default VOLATILE / PARALLEL UNSAFE): its only non-argument input is the
transaction-start clock behind now()/today() — constant within a transaction,
exactly like PostgreSQL's own transaction_timestamp() — and evaluation has no
global state, I/O or randomness. COST 100 matches PostgreSQL's default for a
non-trivial function, so the planner orders cheaper quals ahead of it.

Add feel_eval_immutable, the deterministic subset usable in expression indexes,
generated columns and constant folding. It is IMMUTABLE PARALLEL SAFE COST 100
and enforces determinism with the two feel-core seams:
- rejects now()/today() up front via CompiledExpr::is_clock_free() (cached in
  fn_extra alongside the parse, so the check is per-query, never per-row);
- evaluates under EvalEnv::forbidding_named_zones(), so a named IANA zone becomes
  null (or an ERROR under strict => true) while fixed offsets / Z pass through.
  The instant is a fixed sentinel, never the clock.

The shared eval-to-jsonb tail is factored out; the volatility difference lives
entirely in the EvalEnv each entry point builds.

pg_tests cover both directions of the index proof: an expression index over
feel_eval_immutable is accepted, while STABLE feel_eval is refused ("must be
marked IMMUTABLE") — plus clock rejection, offset/Z support, and the named-zone
null/strict paths. cargo pgrx test pg18: 24 passed.

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

modified crates/feel-pg/src/lib.rs +191 −5

@@ -1,10 +1,18 @@
11
 //! PostgreSQL wrapper for `feel-core`, built with pgrx.
22
 //!
3
-//! Exposes a single SQL function:
3
+//! Exposes two SQL functions:
44
 //!
55
 //! ```sql
6
-//! feel_eval(expr text, context jsonb DEFAULT '{}'::jsonb) RETURNS jsonb
6
+//! feel_eval(expr text, context jsonb DEFAULT '{}', strict bool DEFAULT false)
7
+//!   RETURNS jsonb                                       -- STABLE PARALLEL SAFE
8
+//! feel_eval_immutable(expr text, context jsonb DEFAULT '{}', strict bool DEFAULT false)
9
+//!   RETURNS jsonb                                       -- IMMUTABLE PARALLEL SAFE
710
 //! ```
11
+//!
12
+//! Both evaluate a FEEL expression against a jsonb context. `feel_eval` is STABLE
13
+//! (its `now()`/`today()` read the transaction clock); `feel_eval_immutable` is the
14
+//! deterministic subset for expression indexes — it rejects `now()`/`today()` and
15
+//! named time zones, leaving the result a pure function of `(expr, context)` (RD-10).
816
 //!
917
 //! The JSON/jsonb boundary mapping lives here (not in `feel-core`), per the
1018
 //! project's boundary-mapping decision.
@@ -49,7 +57,19 @@
4957
 /// context), keyed on the expression text. So when `expr` is a query constant —
5058
 /// the usual case, e.g. one decision over many rows — it is parsed once per query
5159
 /// and only re-parsed if the text actually changes. No global/session cache.
52
-#[pg_extern]
60
+///
61
+/// Declared **STABLE** (not VOLATILE): the only non-argument input is the
62
+/// transaction start timestamp behind `now()`/`today()`, constant within a
63
+/// transaction — exactly why PostgreSQL's own `transaction_timestamp()` is STABLE.
64
+/// **PARALLEL SAFE**: evaluation has no global mutable state, I/O or randomness,
65
+/// and a parallel worker is a separate process with its own `fn_extra` cache.
66
+/// `COST 100` matches PostgreSQL's default for a non-trivial (procedural-language)
67
+/// function and is far above the C-function default of 1: a parse-cached eval of a
68
+/// low-to-medium FEEL expression (jsonb→context, a tree-walk, jsonb out) sits in
69
+/// that ballpark, so the planner orders cheaper quals ahead of it. It is *not*
70
+/// IMMUTABLE (`now()` varies across transactions) — see [`feel_eval_immutable`]
71
+/// for the deterministic subset usable in expression indexes (RD-10).
72
+#[pg_extern(stable, parallel_safe, cost = 100)]
5373
 fn feel_eval(
5474
     expr: &str,
5575
     context: default!(JsonB, "'{}'::jsonb"),
@@ -76,17 +96,105 @@
7696
         None => unreachable!("cache populated above"),
7797
     };
7898
 
79
-    let ctx = context_from_json(&context.0).unwrap_or_else(|e| error!("invalid feel context: {e}"));
8099
     // `now()`/`today()` read the transaction start (ADR-18) — constant per query,
81100
     // matching PostgreSQL's own `now()`/`transaction_timestamp()`.
82101
     let env = EvalEnv::new(&RustRegex, transaction_start());
83
-    match compiled.evaluate_with_env(&ctx, &env) {
102
+    eval_to_jsonb(compiled, &context, strict, &env)
103
+}
104
+
105
+/// Evaluate a FEEL expression as an **IMMUTABLE**, deterministic function — the
106
+/// subset safe in expression indexes, generated columns, and constant folding
107
+/// (RD-10).
108
+///
109
+/// Same arguments and jsonb boundary as [`feel_eval`], with two restrictions that
110
+/// make the result depend only on `(expr, context)` and never on time or the
111
+/// (updatable) IANA tzdb:
112
+///
113
+/// - `now()`/`today()` are **rejected** with an ERROR: they vary across
114
+///   transactions, so can never be IMMUTABLE — use [`feel_eval`] for those. The
115
+///   check is static ([`CompiledExpr::is_clock_free`]) and cached per call site,
116
+///   so it costs nothing per row.
117
+/// - *Named* time zones (`@Europe/Berlin`) become null (or ERROR under
118
+///   `strict => true`): their UTC offset is read from the IANA tzdb, which can
119
+///   change. Fixed offsets (`+02:00`) and `Z` are tzdb-independent and fully
120
+///   supported — all an index needs.
121
+///
122
+/// Math/regex builtins (`exp`/`log`/`sqrt`, `matches`/`replace`/`split`) are taken
123
+/// as immutable; their results are stable except across a libc/`regex` upgrade —
124
+/// the same pragmatic stance PostgreSQL takes for its own such functions, after
125
+/// which an index may need a one-off `REINDEX` (RD-10). `PARALLEL SAFE` and
126
+/// `COST 100` for the same reasons as [`feel_eval`].
127
+///
128
+/// ```sql
129
+/// -- Index a FEEL predicate over a jsonb column:
130
+/// CREATE INDEX ON applications
131
+///   ((feel_eval_immutable('applicant.age >= 18 and applicant.income > 50000', data)));
132
+/// ```
133
+#[pg_extern(immutable, parallel_safe, cost = 100)]
134
+fn feel_eval_immutable(
135
+    expr: &str,
136
+    context: default!(JsonB, "'{}'::jsonb"),
137
+    strict: default!(bool, "false"),
138
+    fcinfo: pg_sys::FunctionCallInfo,
139
+) -> JsonB {
140
+    // Same per-call-site parse cache as `feel_eval`, plus the cached clock-free
141
+    // verdict so the static check is paid once per query, never per row.
142
+    let mut cache: PgBox<Option<(String, CompiledExpr, bool)>> =
143
+        unsafe { pg_func_extra(fcinfo, || None) };
144
+    let stale = match &*cache {
145
+        Some((cached, _, _)) => cached != expr,
146
+        None => true,
147
+    };
148
+    if stale {
149
+        match compile(expr) {
150
+            Ok(compiled) => {
151
+                let clock_free = compiled.is_clock_free();
152
+                *cache = Some((expr.to_owned(), compiled, clock_free));
153
+            }
154
+            Err(e) => error!("feel_eval_immutable failed: {e}"),
155
+        }
156
+    }
157
+    let (compiled, clock_free) = match &*cache {
158
+        Some((_, compiled, clock_free)) => (compiled, *clock_free),
159
+        None => unreachable!("cache populated above"),
160
+    };
161
+    if !clock_free {
162
+        error!(
163
+            "feel_eval_immutable: expression calls now()/today(), which are not \
164
+             IMMUTABLE; use feel_eval instead"
165
+        );
166
+    }
167
+    // The clock is never read (now()/today() are rejected above), so the instant
168
+    // is a fixed sentinel — keeping this function free of any ambient read, as an
169
+    // IMMUTABLE function should be. Named zones are vetted away (RD-10).
170
+    let env = EvalEnv::new(&RustRegex, fixed_instant()).forbidding_named_zones();
171
+    eval_to_jsonb(compiled, &context, strict, &env)
172
+}
173
+
174
+/// The eval-and-map-to-jsonb tail shared by [`feel_eval`] and
175
+/// [`feel_eval_immutable`]: build the [`Context`] from the jsonb argument, run the
176
+/// compiled expression under `env`, and apply the strict/lenient boundary (ADR-14).
177
+/// The volatility difference lives entirely in the `env` the caller supplies.
178
+fn eval_to_jsonb(compiled: &CompiledExpr, context: &JsonB, strict: bool, env: &EvalEnv) -> JsonB {
179
+    let ctx = context_from_json(&context.0).unwrap_or_else(|e| error!("invalid feel context: {e}"));
180
+    match compiled.evaluate_with_env(&ctx, env) {
84181
         Ok(value) if strict && value.contains_error() => {
85182
             error!("feel_eval: result is null from a type or domain error (strict mode)")
86183
         }
87184
         Ok(value) => JsonB(value_to_json(&value)),
88185
         Err(e) => error!("feel_eval failed: {e}"),
89186
     }
187
+}
188
+
189
+/// A fixed, arbitrary instant (the Unix epoch, UTC) for [`feel_eval_immutable`]'s
190
+/// `EvalEnv`. `now()`/`today()` are rejected before evaluation there, so it is
191
+/// never read; using a constant — not the transaction clock — keeps the function
192
+/// free of any ambient read.
193
+fn fixed_instant() -> jiff::Zoned {
194
+    let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC);
195
+    jiff::Timestamp::from_microsecond(0)
196
+        .map(|ts| ts.to_zoned(utc))
197
+        .unwrap_or_else(|_| jiff::Zoned::now())
90198
 }
91199
 
92200
 /// The current transaction's start time as a `jiff::Zoned` (UTC), for `now()`/
@@ -325,6 +433,84 @@
325433
         .expect("SPI query failed");
326434
         assert_eq!(matched, Some(true));
327435
     }
436
+
437
+    #[pg_test]
438
+    fn immutable_evaluates_like_feel_eval() {
439
+        let matched = Spi::get_one::<bool>("SELECT feel_eval_immutable('1 + 1') = '2'::jsonb")
440
+            .expect("SPI query failed");
441
+        assert_eq!(matched, Some(true));
442
+    }
443
+
444
+    #[pg_test]
445
+    fn immutable_parses_once_over_many_rows() {
446
+        // The fn_extra cache (parse + clock-free verdict) is reused per row.
447
+        let matched = Spi::get_one::<bool>(
448
+            r#"SELECT bool_and(feel_eval_immutable('a + 1', jsonb_build_object('a', g)) = to_jsonb(g + 1))
449
+               FROM generate_series(1, 100) AS g"#,
450
+        )
451
+        .expect("SPI query failed");
452
+        assert_eq!(matched, Some(true));
453
+    }
454
+
455
+    #[pg_test(error = "feel_eval_immutable: expression calls now()/today(), which are not IMMUTABLE; use feel_eval instead")]
456
+    fn immutable_rejects_now() {
457
+        // now() can never be IMMUTABLE -> hard ERROR (not a silent null).
458
+        let _ = Spi::get_one::<bool>("SELECT feel_eval_immutable('now()') IS NOT NULL");
459
+    }
460
+
461
+    #[pg_test(error = "feel_eval_immutable: expression calls now()/today(), which are not IMMUTABLE; use feel_eval instead")]
462
+    fn immutable_rejects_today() {
463
+        let _ = Spi::get_one::<bool>("SELECT feel_eval_immutable('today() = today()') IS NOT NULL");
464
+    }
465
+
466
+    #[pg_test]
467
+    fn immutable_allows_offset_zones() {
468
+        // Fixed offsets and Z are tzdb-independent -> fully supported.
469
+        let matched = Spi::get_one::<bool>(
470
+            r#"SELECT feel_eval_immutable('time("12:00:00+02:00")') = '"12:00:00+02:00"'::jsonb"#,
471
+        )
472
+        .expect("SPI query failed");
473
+        assert_eq!(matched, Some(true));
474
+    }
475
+
476
+    #[pg_test]
477
+    fn immutable_named_zone_is_null_by_default() {
478
+        // A named zone (tzdb-dependent) is vetted to jsonb null at the lenient boundary.
479
+        let matched = Spi::get_one::<bool>(
480
+            r#"SELECT feel_eval_immutable('time("12:00:00@Europe/Berlin")') = 'null'::jsonb"#,
481
+        )
482
+        .expect("SPI query failed");
483
+        assert_eq!(matched, Some(true));
484
+    }
485
+
486
+    #[pg_test(error = "feel_eval: result is null from a type or domain error (strict mode)")]
487
+    fn immutable_named_zone_raises_in_strict_mode() {
488
+        // strict => true escalates the vetted named-zone error-null to an ERROR.
489
+        let _ = Spi::get_one::<bool>(
490
+            r#"SELECT feel_eval_immutable('time("12:00:00@Europe/Berlin")', '{}', true) IS NOT NULL"#,
491
+        );
492
+    }
493
+
494
+    #[pg_test]
495
+    fn immutable_is_usable_in_an_expression_index() {
496
+        // The payoff: PostgreSQL only accepts IMMUTABLE functions in an index
497
+        // expression, so this DDL succeeding *is* the proof of the marker.
498
+        Spi::run(
499
+            "CREATE TEMP TABLE feel_idx_ok (data jsonb);
500
+             CREATE INDEX ON feel_idx_ok ((feel_eval_immutable('applicant.age >= 18', data)));",
501
+        )
502
+        .expect("an expression index over feel_eval_immutable should be allowed");
503
+    }
504
+
505
+    #[pg_test(error = "functions in index expression must be marked IMMUTABLE")]
506
+    fn stable_feel_eval_is_rejected_in_an_index() {
507
+        // The flip side: feel_eval is STABLE, so PostgreSQL refuses it in an index.
508
+        Spi::run(
509
+            "CREATE TEMP TABLE feel_idx_bad (data jsonb);
510
+             CREATE INDEX ON feel_idx_bad ((feel_eval('applicant.age >= 18', data)));",
511
+        )
512
+        .expect("DDL should raise before this unwrap");
513
+    }
328514
 }
329515
 
330516
 /// Required pgrx test harness hooks.