Skip to content

Commit 9ebb796

Browse files
authored
Release the GIL while parsing expressions of 32 bytes or more (#59)
compile(), and the parse inside evaluate(), run Program::compile with the GIL released for expressions of 32 bytes or more; shorter expressions parse attached because their parse costs about as much as re-acquiring a contended GIL. Execution still holds the GIL. Overlap-based tests detect the release without depending on core count. Claude-Session: https://claude.ai/code/session_019WbvXZFm8Nb2LXF2kiWoWW
1 parent 5de865d commit 9ebb796

4 files changed

Lines changed: 148 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1414
Windows x64. Importing `cel` leaves the GIL disabled
1515
([#45](https://github.com/hardbyte/python-common-expression-language/issues/45)).
1616

17+
### Performance
18+
19+
- **Parsing no longer holds the GIL.** `compile()`, and the parse inside
20+
`evaluate()`, release the GIL for expressions of 32 bytes or more, so threads
21+
that parse concurrently run in parallel: about 3× the throughput from 4 threads
22+
on a 4-core machine, with single-threaded cost unchanged. Executing a compiled
23+
program still holds the GIL
24+
([#45](https://github.com/hardbyte/python-common-expression-language/issues/45)).
25+
1726
### Changed
1827

1928
- `Program` and `OptionalValue` are immutable; attributes can no longer be

‎docs/reference/python-api.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ assert result2 == 30 # → 30
4141
- Use `evaluate()` for one-time evaluation or interactive/REPL usage
4242
- Use `compile()` + `execute()` when evaluating the same expression with many different contexts or in performance-critical loops
4343

44+
Parsing (`compile()`, and the parse inside `evaluate()`) runs with the GIL
45+
released for expressions of 32 bytes or more, so threads that parse concurrently
46+
run in parallel. Shorter expressions parse in a few microseconds, which is less
47+
than the cost of re-acquiring a contended GIL, so they keep it. Executing a
48+
compiled program also holds the GIL: evaluations are usually sub-microsecond.
49+
4450
## Classes
4551

4652
### Program

‎src/lib.rs‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -267,18 +267,37 @@ impl PyOptionalValue {
267267
/// >>> program.execute({"x": 10, "y": 20})
268268
/// 30
269269
#[pyfunction]
270-
fn compile(expression: String) -> PyResult<PyProgram> {
271-
let program = compile_program(&expression)?;
270+
fn compile(py: Python<'_>, expression: String) -> PyResult<PyProgram> {
271+
let program = compile_program(py, &expression)?;
272272
Ok(PyProgram {
273273
program,
274274
source: expression,
275275
})
276276
}
277277

278+
/// Expressions shorter than this (in bytes) are parsed with the GIL held.
279+
///
280+
/// A short parse costs about as much as re-acquiring a contended GIL, so
281+
/// releasing it for one is a net loss under contention. Parse time grows with
282+
/// expression length, which makes length a safe gate: erring long only forgoes a
283+
/// speedup. Benchmarks behind the bound are in issue #45.
284+
const PARSE_DETACH_MIN_LEN: usize = 32;
285+
278286
/// Parses `expression`, turning both parse errors and parser panics into
279287
/// `ValueError` so callers can rely on one exception type for a bad expression.
280-
fn compile_program(expression: &str) -> PyResult<Program> {
281-
panic::catch_unwind(|| Program::compile(expression))
288+
///
289+
/// The parse is pure Rust and cannot call back into Python, so it runs with the
290+
/// GIL released unless the expression is too short for that to pay off.
291+
/// `catch_unwind` sits inside the detached region so a parser panic is caught
292+
/// before control crosses back through PyO3's re-attach guard.
293+
fn compile_program(py: Python<'_>, expression: &str) -> PyResult<Program> {
294+
let parse = || panic::catch_unwind(|| Program::compile(expression));
295+
let parsed = if expression.len() >= PARSE_DETACH_MIN_LEN {
296+
py.detach(parse)
297+
} else {
298+
parse()
299+
};
300+
parsed
282301
.map_err(|_| {
283302
warn!("CEL parser panic for expression: '{}'", expression);
284303
PyValueError::new_err(format!(
@@ -1058,11 +1077,15 @@ impl TryIntoValue for RustyPyType<'_> {
10581077
/// - CEL Language Guide: For comprehensive language documentation
10591078
/// - Python API Reference: For detailed API documentation
10601079
#[pyfunction(signature = (src, evaluation_context=None))]
1061-
fn evaluate(src: String, evaluation_context: Option<&Bound<'_, PyAny>>) -> PyResult<RustyCelType> {
1080+
fn evaluate(
1081+
py: Python<'_>,
1082+
src: String,
1083+
evaluation_context: Option<&Bound<'_, PyAny>>,
1084+
) -> PyResult<RustyCelType> {
10621085
// Validate the context before parsing so a bad context and a bad expression
10631086
// report in the same order they always have.
10641087
let environment = prepare_environment(evaluation_context)?;
1065-
let program = compile_program(&src)?;
1088+
let program = compile_program(py, &src)?;
10661089
run_program(&program, &src, &environment).map(RustyCelType)
10671090
}
10681091

‎tests/test_gil_release.py‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
"""Parsing releases the GIL.
2+
3+
``cel.compile()`` and the parse inside ``cel.evaluate()`` run with the GIL
4+
released for expressions of 32 bytes or more, so other Python threads make
5+
progress while an expression is parsed. Shorter expressions parse in a few
6+
microseconds, comparable to the cost of re-acquiring a contended GIL, so they keep
7+
it. Execution of a compiled program still holds the GIL (see issue #45 for why: a
8+
sub-microsecond evaluation loses badly to the cost of re-acquiring a contended
9+
GIL, and a work-aware gate for execution is a separate change).
10+
11+
The tests below detect release by *overlap* rather than by speed: a spinning
12+
thread counts iterations while the main thread parses. With the GIL held for the
13+
whole parse the spinner cannot run and the count stays at essentially zero; with
14+
it released the spinner gets a core and the count climbs into the millions. That
15+
is a binary signal, so it does not depend on the runner's core count or load.
16+
"""
17+
18+
import sys
19+
import sysconfig
20+
import threading
21+
22+
import cel
23+
import pytest
24+
25+
# A list literal parses in time linear in its length; 20,000 elements is a few
26+
# hundred milliseconds of pure parsing, long enough for the spinner to show up.
27+
BIG_EXPRESSION = "[" + ", ".join(str(i) for i in range(20_000)) + "]"
28+
29+
# On a free-threaded build the spinner runs regardless, so overlap proves nothing;
30+
# the contract there is simply "still works", covered by the whole suite.
31+
requires_gil_build = pytest.mark.skipif(
32+
sys.implementation.name != "cpython" or bool(sysconfig.get_config_var("Py_GIL_DISABLED")),
33+
reason="overlap is only observable on a CPython build with a GIL",
34+
)
35+
36+
37+
def ticks_during(action):
38+
"""Run ``action`` on this thread while another thread spins; return the spinner's count."""
39+
ticks = 0
40+
started = threading.Event()
41+
stop = threading.Event()
42+
43+
def spin():
44+
nonlocal ticks
45+
started.set()
46+
while not stop.is_set():
47+
ticks += 1
48+
49+
spinner = threading.Thread(target=spin)
50+
spinner.start()
51+
started.wait()
52+
# Let the spinner settle so a switch-interval handoff right at the start does
53+
# not count as overlap.
54+
threading.Event().wait(0.02)
55+
before = ticks
56+
action()
57+
after = ticks
58+
stop.set()
59+
spinner.join()
60+
return after - before
61+
62+
63+
@requires_gil_build
64+
def test_compile_releases_the_gil():
65+
assert ticks_during(lambda: cel.compile(BIG_EXPRESSION)) > 10_000
66+
67+
68+
@requires_gil_build
69+
def test_evaluate_releases_the_gil_while_parsing():
70+
assert ticks_during(lambda: cel.evaluate(BIG_EXPRESSION)) > 10_000
71+
72+
73+
def test_parse_results_are_unchanged():
74+
"""Detaching changes where the parse runs, not what it produces or raises.
75+
76+
Covers both sides of the length threshold: short expressions parse attached,
77+
long ones detached, and errors surface identically from either path.
78+
"""
79+
assert cel.compile("1 + 2").execute() == 3
80+
assert cel.evaluate(BIG_EXPRESSION)[-1] == 19_999
81+
long_policy = 'user.role == "admin" || (resource.owner == user.id && size(user.groups) > 0)'
82+
assert len(long_policy) >= 32
83+
assert cel.evaluate(long_policy, {"user": {"role": "admin"}, "resource": {}}) is True
84+
with pytest.raises(ValueError, match="Failed to parse"):
85+
cel.compile("1 +")
86+
with pytest.raises(ValueError, match="Failed to parse"):
87+
cel.evaluate("'unterminated")
88+
with pytest.raises(ValueError, match="Failed to parse"):
89+
cel.compile(
90+
"this is a long enough expression to be parsed detached but it is not valid CEL !!"
91+
)
92+
93+
94+
def test_concurrent_compiles_are_independent():
95+
"""Many threads parsing at once each get their own correct program."""
96+
from concurrent.futures import ThreadPoolExecutor
97+
98+
def work(i):
99+
return cel.compile(f"{i} * 2 + 1").execute()
100+
101+
with ThreadPoolExecutor(max_workers=8) as pool:
102+
results = list(pool.map(work, range(400)))
103+
104+
assert results == [i * 2 + 1 for i in range(400)]

0 commit comments

Comments
 (0)