|
| 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