Repository navigation
Open
Labels
enhancementNew feature or request
Description
Problem
evaluate() and Program.execute() hold the GIL for the entire Rust-side evaluation. A Python program that evaluates CEL from several threads therefore serialises on the interpreter even though the work is pure Rust once the context has been converted. This matters for the policy-engine style of use (many rules × many requests) that the README leads with.
Proposal
- Release the GIL around
program.execute()withpy.detach(|| ...)(PyO3 0.29's spelling ofallow_threads). The pieces already have the right bounds:cel::Programis a plain AST,cel::Context<'static>isSend + Sync(itsVal,FunctionandVariableResolvertraits all require it), and the Python-callback wrappers already do their ownPython::attach, so a callback simply re-acquires the GIL when it runs. Conversion of the result back to Python happens after re-attaching. - Measure the fixed cost. Detach/attach is on the order of tens of nanoseconds, but a trivial
x + yexecutes in ~0.15 µs, so unconditional detaching could be a visible relative slowdown for tiny expressions while being a large absolute win for anything heavier or for multi-threaded callers. Options, in order of preference:- detach unconditionally if the overhead measures under ~10% on the
compile_execute_benchmark.pycases; - otherwise detach only when the context has no Python functions and no resolver (that's when the evaluation cannot need the GIL), which is cheap to know from the
Context; - an explicit
execute(ctx, release_gil=...)knob is a last resort.
- detach unconditionally if the overhead measures under ~10% on the
- Free-threaded Python. PyO3 0.29 supports the free-threaded build when the module opts in with
#[pymodule(gil_used = false)]. Before doing that, audit:Contextmutators are&mut self(PyO3's borrow checker turns concurrent mutation into an error rather than a data race), the shared stdlibEnvis aLazyLock, and the per-Contextcache proposed in the Context-reuse PR is behind aMutex. Then addcp314twheels to the CI matrix (maturin-action needs the interpreter listed explicitly;--find-interpreterwon't pick it up).
Non-goals
Context itself is documented as not thread-safe for concurrent mutation; that stays. Concurrent evaluation against a shared Context is already fine and is now pinned by tests.
Metadata
Metadata
Assignees
Labels
enhancementNew feature or request
Activity
hardbyte commentedon Sep 15, 2026
Direction, after measuring
Two independent prototypes were built and benchmarked (release builds, 4 cores, Python 3.11; full test suite passes identically with the GIL released), plus a source-level read of PyO3 0.29.2 and a survey of the ecosystem. The proposal in the issue body was wrong in two places, and the corrected direction has two independent tracks.
Finding 1: free-threaded support is already shipping, untested
PyO3 0.28 made
gil_used = falsethe default, so the bare#[pymodule]insrc/lib.rshas declared this module GIL-free on 3.13t+ since the 0.7.0 upgrade. And because the manylinux images carrypython3.14t/python3.15tand maturin ≥ 1.14's--find-interpreterpicks them up, 0.10.0 already publishescp314tandcp315twheels for every Linux architecture (check the file list on PyPI). Only macOS and Windows lack them, because those runners have no free-threaded interpreter installed. No CI leg has ever run the tests underPYTHON_GIL=0.Ecosystem context: six of eight comparable Rust extensions ship free-threaded wheels (pydantic-core, cryptography, rpds-py, jiter, watchfiles, tiktoken); the two that don't are blocked by being abi3-only. cibuildwheel and maturin both build them by default now. PyO3 0.29 dropped 3.13t, so
cp314t/cp315tis the whole target. CPython 3.15 (final 2026-10-01) addsabi3t(PEP 803); abi3 wheels cannot be installed on a free-threaded interpreter before that, which is relevant to #46: switching to abi3 would silently remove the free-threaded wheels we ship today.Finding 2: releasing the GIL around
execute()is a throughput cliff, not a 50 ns taxUncontended, a detach/attach round trip costs ~47–75 ns. Under contention it is a different regime: a thread re-acquiring the GIL waits for whoever grabbed it meanwhile, ~14 µs at 4 threads. For sub-microsecond evaluations that is the whole cost.
x + yx + y, context also holds a 20k listfilter(...).size()over 512 items (3.5 ms)filter/map/sizeover 2k items (63 ms)Break-even, measured by sweeping list length with
items.filter(i, i % 3 == 0).size(): detaching starts winning at ~7–8 µs of work per call, reaches 2× at ~13 µs, and saturates at the core count (~3.9×) from ~65 µs. One octave either side of the crossing is the difference between 0.34× and 1.5×. Single-thread benchmarks give no warning of any of this, which is why the issue body's "measure the fixed cost" plan would have shipped a 55× regression for the most common workload.Both cheap gates fail in both directions. Gating on "no Python callbacks" still detaches
x + y. Gating on context size detachesx + ywhen a big list happens to be in the context (52× worse) and fails to detach a 3.5 ms filter over a 512-element list (misses a 3.9× win). The question that matters is "how much work will this call do", and neither proxy answers it.Two things do work:
Program::compileis pure Rust and costs 14–72 µs (98% ofevaluate()for a policy-sized expression), well past break-even.evaluate()goes from 0.94× to 2.6× at 4 threads with no downside.Programgate. Time the attached execution for the first 3 calls (excludingprepare_environment, whose first call may build the cel context); if any sample exceeds ~16 µs (≈2× the crossing), latch thatPrograminto detaching. Prototyped with anAtomicU8onPyProgram, relaxed ordering:x + yx + y, 20k list in contextSteady-state overhead is one relaxed atomic load (0.242 vs 0.240 µs single-thread); sampling adds at most ~0.5 µs to each of the first three calls. Known limits: a program whose cost varies wildly across contexts latches on its first samples, and
evaluate()has no persistent object to learn on, so its execute stays attached (its cost is the parse anyway).Semantics, verified rather than argued
Under detach: callbacks re-attach via
Python::attach(correct in PyO3'sSuspendAttachdesign, verified against the source); exceptions from callbacks propagate with identical messages; a callback mutating its ownContextsees the same snapshot semantics as today (theArcfrom #51 is what makes this work); re-entrantevaluate()from a callback works;pyo3_logre-attaches; panics are caught inside the detached region; Ctrl-C behaviour is unchanged either way (Python signal handlers run only in the main thread's eval loop). 8 threads × 2000 executions on oneProgramand 3 readers + 2 writers × 20kadd_variableon oneContext: zero errors.&cel::Program,&cel::Context<'static>andPyResult<Value>all satisfy PyO3's stableUngil(=Send) bound because cel-rust requiresVal,FunctionandVariableResolverto beSend + Sync. No unsafe, no wrappers.The plan
PR 1 — own the free-threading we already ship (small, do first):
3.14ttest leg (uv python install 3.14t, pytest withPYTHON_GIL=0so a dependency can't quietly re-enable the GIL).#[pymodule(gil_used = false)]explicit;pyo3_log::init()→try_init()(a second module exec panics today);#[pyclass(frozen)]onProgramandOptionalValue;MutexExt::lock_py_attachedfor theContextcache lock, sinceclone_refruns under it; compile-timeSend + Syncassertions on the cel types so an upstream bump can't silently break this.setup-pythonwith3.14t(and3.15tafter Oct 1) on the macOS and Windows jobs with an explicit interpreter, one interpreter per job on Windows; bump the maturin floor to ≥ 1.14.Programis immutable and shareable; aContextis safe to evaluate against from many threads; concurrent mutation of oneContextraisesRuntimeError: Already borrowedrather than racing, so build it before sharing. MakingContextfrozenwith an internalRwLockis the eventual fix, as a follow-up.abi3t; decide the two together.PR 2 — release the GIL where it pays:
Program::compileincompile()andevaluate().Program.execute()as above, with an explicit override for people who know their workload:cel.compile(expr, release_gil: bool | None = None)(None= adaptive). No per-call knob onexecute(), to keep the hot path flat.evaluate()'s execute stays attached.Program._releases_gilprobe (x + ysettles attached, a heavy filter latches detached); the existing re-entrancy and mutation tests already cover the semantic edges.x + yto parallelise.Not doing: unconditional detach, the callback gate, the context-size gate, or claiming improved Ctrl-C responsiveness.
Found along the way: cel-rust 0.14.5's comprehensions are O(n²) (20k-element
filter/maptakes 5.8 s); tracked in #57, upstream fix formapis on master.Generated by Claude Code
hardbyte commentedon Sep 15, 2026
Preserving the prototype artefacts here so PR 2 can start from them rather than from scratch (the worktree they were built in is temporary).
Two notes on the diff before anyone lifts it:
Environment.detachable) from the earlier variant in addition to the timing latch. The measurements above say the timing latch alone is the right gate: a heavy expression that calls a Python function per element still gained 1.3–1.5× on 2 threads when detached, and the latch already captures whether such a call is cheap or expensive. PR 2 should dropdetachableand rely on the latch, keeping only the parse detach as unconditional.release_giloverride oncompile(), no CHANGELOG, and thePyProgramdocstring does not yet describe the behaviour.adaptive.diff— adaptive per-Program gate + unconditional parse detach (applies to 0.10.0'ssrc/lib.rs)bench.py— the benchmark behind the tables (run aspython bench.py <label>against each build)Generated by Claude Code
Trim the parse-gate comments to the decision, not the benchmark
hardbyte commentedon Sep 15, 2026
Status: two of the three pieces above have merged.
python3.14tin CI, free-threaded wheels build for macOS and Windows x64 as well as Linux,ProgramandOptionalValueare frozen, and theContextthreading contract is documented and tested. The new leg found and fixed a misleadingValueErrorwhen an evaluation raced aContextmutation.compile()and the parse insideevaluate()release the GIL for expressions of 32 bytes or more.evaluate()of a policy-sized expression from 4 threads went from 0.96× to about 3× single-thread throughput on 4 cores.Still open: releasing the GIL around
Program.execute(). The measurements above show a fixed threshold tuned on one machine is only half adaptive, since it measures the program's work but assumes the machine's contended re-acquire cost. The direction I'd take: measure the handoff overhead actually paid by detached executions and revert when it exceeds the work, start from a conservative prior of a few times the measured re-acquire latency, re-sample with hysteresis rather than latching, and keep an explicitrelease_giloverride oncompile(). On free-threaded builds none of this applies and the gate should compile out.Generated by Claude Code