Public repository: timo / feel

Reader

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

docs: record ADR-20 and RD-4/5/6; document feel-py

public

docs: record ADR-20 and RD-4/5/6; document feel-py

ADR-20 (Python bindings) plus the three reversible boundary decisions: RD-4
(Python `re` regex dialect), RD-5 (temporal mapping with relativedelta), RD-6
(eager context mapping, rejecting a lazy Value::Foreign that would duck-type the
core). README gains the feel-py target in the layout, a build/usage section, and
the third target in the cardinal-rule invariant check.

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

modified DECISIONS.md +93 −0

@@ -502,6 +502,31 @@
502502
   nanosecond precision; matching would discard sub-second precision). Named-argument
503503
   call variants stay out of the slice (the AST is positional-only, ADR-15).
504504
 
505
+## ADR-20: Python bindings (`feel-py`, PyO3 + maturin)
506
+
507
+- **Context:** feel-core already has a Postgres wrapper (feel-pg) and a WASM wrapper
508
+  (feel-wasm); Python is a common host for decision logic and data pipelines. A
509
+  fourth wrapper should expose FEEL to Python without touching the pure core (ADR-1):
510
+  all target glue, including the JSON/native boundary mapping, lives in the wrapper.
511
+- **Decision (2026-06-16):** new `crates/feel-py`, built with **PyO3 0.28 + maturin**
512
+  (`abi3-py39` → a single wheel for every CPython ≥ 3.9). Surface mirrors feel-wasm:
513
+  free `evaluate(expr, context=None)` / `evaluate_strict(...)` plus a `compile(expr)`
514
+  returning a reusable `CompiledExpr` (parse-once / evaluate-many). The lenient/strict
515
+  null policy is ADR-14; a parse/eval error or a strict error-null raises
516
+  `feel.FeelError` (a subclass of `ValueError`). `now()`/`today()` read the system
517
+  clock as a fixed-offset UTC instant. The three boundary sub-decisions are recorded
518
+  as **RD-4** (regex dialect), **RD-5** (temporal mapping) and **RD-6** (context
519
+  mapping). `feel-py` keeps feel-core's default features (so `RustRegex` is available
520
+  as the `xpath-regex` provider, and the system tzdb resolves named zones) and is in
521
+  the workspace `members` but **not** `default-members` — it needs a PyO3 link context
522
+  (built via maturin), like feel-pg needs pgrx.
523
+- **Consequence:** a fourth target on the same core, verified by 21 pytest cases
524
+  (`crates/feel-py/tests`) plus a Rust unit test for the replacement-string
525
+  translation. Alongside it, **feel-wasm's `js_to_value` was hardened** with the same
526
+  cycle/depth guard feel-py uses: its recursion was previously unbounded, so a cyclic
527
+  JS object (`a.b = a`, legal in JS) could overflow the stack; a back-edge now maps to
528
+  `null` (no other behaviour change — own-enumerable getters still fire as before).
529
+
505530
 ## Revisable design decisions
506531
 
507532
 Softer than the ADRs above: deliberate, **reversible** choices that are not
@@ -581,6 +606,74 @@
581606
 - **If flipped:** add `iana-tz` to a `default` feature on feel-wasm (or document
582607
   building with it), accepting the larger default bundle.
583608
 
609
+### RD-4: feel-py uses the Python `re` regex dialect (`xpath-regex` to opt out)
610
+
611
+- **Weighed:** ADR-16 makes the three regex builtins host-pluggable. Unlike feel-pg
612
+  (RD-1, which kept `RustRegex` for TCK-dialect parity) and like feel-wasm (JS
613
+  dialect), Python ships its own `re` engine, and the FEEL/XPath flags `i s m x q`
614
+  all carry over — `i/s/m/x` as inline `(?…)` flags, `q` via `re.escape`, and inline
615
+  flags in the pattern pass straight through. So the host dialect is both available
616
+  and idiomatic for Python authors. Against: `re` is a third dialect that diverges
617
+  from feel-core/TCK in the corners (Python supports backreferences the Rust engine
618
+  rejects; class subtraction/XSD block names differ).
619
+- **Decision (2026-06-16):** feel-py defaults to the Python `re` dialect via a
620
+  `PyRegex` provider (it holds the GIL, since the builtins call back into Python). The
621
+  `xpath-regex` build feature instead compiles feel-core's `RustRegex`, for results
622
+  byte-identical to feel-core/TCK. XPath `$N` replacement references are translated to
623
+  `re`'s `\g<N>` form (`xpath_replacement_to_python`, the Python pendant of feel-core's
624
+  `xpath_replacement_to_rust`). Edge: a capturing group in a `split` delimiter makes
625
+  `re.split` emit the captures (XPath does not) → such a result is a FEEL null
626
+  (documented divergence).
627
+- **Revisit trigger:** users expect FEEL regex in Python to match feel-core/TCK by
628
+  default (e.g. patterns authored against the reference) rather than the `re` dialect.
629
+- **If flipped:** make `xpath-regex` the default feature (or document building with
630
+  it); the seam (`evaluate_with_env` + the `cfg` provider switch) is already in place.
631
+
632
+### RD-5: feel-py temporal mapping (native types; years-months via relativedelta)
633
+
634
+- **Weighed:** ADR-18's boundary is canonical ISO-8601. Python has native
635
+  `datetime.date`/`datetime`/`time`/`timedelta`, but **no** native years-months
636
+  duration. Options for that one type: an ISO string (as feel-wasm leaves durations),
637
+  `dateutil.relativedelta` (a real, arithmetic-capable type), or a bespoke class.
638
+- **Decision (2026-06-16):** map `date`→`date`, `date and time`→`datetime`,
639
+  `time`→`time`, days-time-duration→`timedelta`, and years-months-duration→
640
+  `dateutil.relativedelta` — adding `python-dateutil` as a runtime dependency. Input
641
+  is symmetric (a native temporal in the context maps back to the FEEL type; a
642
+  `relativedelta`'s years/months become a years-months duration, its other fields
643
+  ignored — FEEL has no mixed duration). The conversion goes through the ISO bridge
644
+  (`to_iso`/`temporal_from_iso`) except the two durations, which are built from
645
+  components.
646
+- **Revisit trigger:** a desire for zero runtime dependencies (drop `python-dateutil`).
647
+- **If flipped:** return years-months durations as an ISO-8601 string or a small
648
+  module-level class; drop the `python-dateutil` dependency.
649
+
650
+### RD-6: feel-py context mapping is eager, not lazy (no `Value::Foreign` in the core)
651
+
652
+- **Weighed:** FEEL has only the dot for member access (`Expr::Path`), resolved
653
+  **inside feel-core** against a fully materialised `Value` tree — there is no live
654
+  Python object at evaluation time. A *lazy* alternative (feel-core calling `getattr`
655
+  back into Python per path segment) was considered and **rejected**: it would need an
656
+  opaque `Value::Foreign` variant in the core, which duck-types the evaluator (every
657
+  type-inspecting op — `distinct`, arithmetic, comparison — would have to "force" the
658
+  value via the host) and lands the concept in *all* targets (pg/wasm) though only
659
+  Python would create such values — against the spirit of ADR-1. Lazy `getattr` would
660
+  also fire `@property`/descriptors, i.e. side effects / lazy DB loads on ORM rows.
661
+- **Decision (2026-06-16):** convert **eagerly** at the boundary. A `dict` maps by its
662
+  keys; any other object maps from its instance `__dict__` (`vars(obj)`) — instance
663
+  data only, so descriptors/properties/methods are **never** invoked (no side effects),
664
+  mirroring feel-wasm's `Object.keys` model. Keys beginning with `_` (dunders and
665
+  internal bookkeeping like `_sa_instance_state`) are skipped. A `__dict__`-less object
666
+  (`__slots__`) is not introspectable → null. An `id()`-based cycle guard plus a depth
667
+  cap break reference cycles (a back-edge → null), since loaded bidirectional ORM
668
+  graphs / parent-child trees can be cyclic; on acyclic dict data neither triggers.
669
+- **Revisit trigger:** a real need to evaluate against very large or genuinely live
670
+  object graphs where an eager snapshot is too costly — *and* a way to do it without a
671
+  foreign value in the core.
672
+- **If flipped:** add a `HostPath` resolver trait to `EvalEnv` plus a
673
+  `Value::Foreign(handle)` variant in feel-core (an ADR-16-style seam), with
674
+  force-on-consume rules for non-path operations — a feel-core change warranting its
675
+  own ADR.
676
+
584677
 ## Roadmap: deferred scope (recorded, not yet built)
585678
 
586679
 These were considered and deliberately deferred to keep the slice thin. Listed so

modified README.md +55 −9

@@ -1,15 +1,17 @@
11
 # rust-s-feel — a dual-target (S-)FEEL engine slice
22
 
33
 A deliberately thin vertical slice of an (S-)FEEL expression engine in Rust. The
4
-point is **not** FEEL completeness — it is to prove a dual-target architecture:
5
-one pure core crate compiled into **two** targets (PostgreSQL via pgrx, WASM via
6
-wasm-bindgen) that produce the **same result** for the same expression, plus a
7
-closed ingestion loop from the official DMN-TCK test suite into core unit tests.
4
+point is **not** FEEL completeness — it is to prove a multi-target architecture:
5
+one pure core crate compiled into **three** targets (PostgreSQL via pgrx, WASM via
6
+wasm-bindgen, Python via PyO3) that produce the **same result** for the same
7
+expression, plus a closed ingestion loop from the official DMN-TCK test suite into
8
+core unit tests.
89
 
910
 ```text
1011
 crates/feel-core   pure engine (lalrpop grammar + AST + evaluator); no target deps
1112
 crates/feel-pg     pgrx wrapper:  feel_eval(text, jsonb) RETURNS jsonb
1213
 crates/feel-wasm   wasm-bindgen wrapper:  evaluate(expr, context) -> JS value
14
+crates/feel-py     PyO3 wrapper:  evaluate(expr, context) -> Python value
1315
 tools/ingest_tck.py  DMN-TCK literal-expression -> feel-core fixture (with deviations)
1416
 ```
1517
 
@@ -33,7 +35,7 @@
3335
   `.time offset`, …), the temporal constructor and component built-ins
3436
   (`date(…)`, `day of week(…)`, …), and `now()` / `today()` (ADR-18). Values
3537
   cross the boundary as canonical ISO-8601 (native PostgreSQL `date`/`timestamptz`/
36
-  `interval` casts; WASM `Date` objects). Named zones (`@Europe/Paris`) need the
38
+  `interval` casts; WASM `Date` objects; Python `datetime`/`dateutil` types). Named zones (`@Europe/Paris`) need the
3739
   IANA tzdb: bundled on native / feel-pg, and in WASM via an opt-in feature —
3840
   `wasm-pack build crates/feel-wasm --target nodejs -- --features iana-tz` (~723 KB
3941
   vs the ~479 KB offset-only default, where a named zone evaluates to null).
@@ -46,10 +48,10 @@
4648
 
4749
 ## Architecture invariant (Cardinal Rule)
4850
 
49
-`feel-core` must never depend on pgrx or wasm-bindgen. Verify:
50
-
51
-```sh
52
-cargo tree -p feel-core --edges normal,build | grep -E 'pgrx|wasm-bindgen' && echo VIOLATION || echo OK
51
+`feel-core` must never depend on pgrx, wasm-bindgen or pyo3. Verify:
52
+
53
+```sh
54
+cargo tree -p feel-core --edges normal,build | grep -E 'pgrx|wasm-bindgen|pyo3' && echo VIOLATION || echo OK
5355
 ```
5456
 
5557
 ## Toolchain
@@ -58,6 +60,8 @@
5860
   validated on rustc 1.96. Update with `rustup update stable` if needed.
5961
 - Python 3 (standard library only) for the ingestion script.
6062
 - For the WASM target: `rustup target add wasm32-unknown-unknown` and `wasm-pack`.
63
+- For the Python target: a Python ≥ 3.9 (virtual) environment and `maturin`
64
+  (PyO3 builds the extension module; one abi3 wheel covers all CPython ≥ 3.9).
6165
 - For the PostgreSQL target: PostgreSQL 13–18 with `pg_config`, plus `libclang`
6266
   (pgrx uses bindgen), and `cargo-pgrx`.
6367
 
@@ -221,6 +225,48 @@
221225
 cargo build -p feel-wasm --target wasm32-unknown-unknown
222226
 ```
223227
 
228
+## python — module (PyO3 / maturin)
229
+
230
+```sh
231
+pip install maturin
232
+cd crates/feel-py && maturin develop      # builds + installs into the active venv
233
+pytest tests                              # 21 smoke tests
234
+```
235
+
236
+The context is a native Python value and the result is a native Python value.
237
+Parse/eval errors raise `feel.FeelError`; `evaluate_strict` also raises on a null
238
+that arose from a type/domain error.
239
+
240
+```python
241
+import feel
242
+
243
+feel.evaluate("1 + 1")                          # => 2  (int, not 2.0)
244
+feel.evaluate("person.age", {"person": {"age": 42}})  # => 42
245
+feel.evaluate("{a: 1, b: a + 1}")               # => {"a": 1, "b": 2}
246
+feel.evaluate("1 + true")                       # => None   (lenient)
247
+feel.evaluate_strict("1 + true")                # raises    (strict)
248
+
249
+# Parse once, evaluate many times:
250
+prog = feel.compile("a + 1")
251
+prog.evaluate({"a": 1})                          # => 2
252
+prog.evaluate({"a": 41})                         # => 42
253
+```
254
+
255
+Besides `dict`s, a context may be any object: its instance `__dict__` is read
256
+(plain data only — `@property`/methods are never invoked, so no side effects),
257
+and reference cycles are broken (back-edge → `None`). Temporal values map to
258
+`datetime`/`dateutil` types (years-months durations to `relativedelta`).
259
+
260
+The `matches`/`replace`/`split` builtins run on the **host** regex engine, so in
261
+Python the **`re`** dialect applies (DECISIONS.md ADR-16/RD-4) — the FEEL/XPath
262
+flags `i s m x q` carry over (as inline `(?…)` flags / `re.escape`), as do inline
263
+flags in the pattern. For results byte-identical to feel-core/TCK, build with the
264
+Rust engine instead:
265
+
266
+```sh
267
+maturin develop --features xpath-regex
268
+```
269
+
224270
 ## benchmarks
225271
 
226272
 Two harnesses quantify the parse-once / evaluate-many win and a cross-engine