Skip to content

Lock the Python string cache once per parse - #289

Merged
samuelcolvin merged 9 commits into
mainfrom
string-cache-lock-per-parse
Sep 12, 2026
Merged

samuelcolvin merged 9 commits into
mainfrom
string-cache-lock-per-parse

Conversation

@samuelcolvin

@samuelcolvin samuelcolvin commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Every cached string used to lock and unlock the global cache mutex individually. The parser now holds the lock for the rest of the parse from the first string of cacheable length, so parses with no such string never touch the mutex. The lock is taken with try_lock; if another thread holds it the parse falls back to uncached strings instead of blocking.

cache_clear() and cache_usage() panic with a clear message if called from a Python callback while the parsing thread holds the lock (GC callbacks and __del__ on CPython <= 3.11), rather than deadlocking. Other threads still block as before.

This is the minimal change split out of #280, without the release profile, single-character string and benchmark script changes. Taking the lock lazily rather than at parser construction avoids the regression #280 showed on python_parse_x100 and python_parse_other.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Qm4KCoN9xWsA4HRCL3Lx63


Summary by cubic

Reworks the Python string cache so each parse borrows a cache from a pool instead of locking the global cache mutex for every cached string.

  • The parser takes a cache on its first string of cacheable length and returns it when the parse ends; parses without such strings never touch the pool.
  • No lock is held while Python code runs, so cache_clear() and cache_usage() are safe to call from Python callbacks during a parse.
  • cache_clear() now leaves a cache in use by a parse untouched, and cache_usage() counts entries in the idle caches.
  • Under the GIL parses never overlap and the pool stays at one cache; free-threaded builds grow the pool up to 8 caches, after which a returned cache is dropped.

Written for commit 2029f6a. Summary will update on new commits.

Review in cubic

@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.84615% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/jiter/src/py_string_cache.rs 93.44% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found and verified against the latest diff

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="crates/jiter-python/tests/test_jiter.py">

<violation number="1" location="crates/jiter-python/tests/test_jiter.py:442">
P2: This test never actually exercises the re-entrancy check in CI. The only job that runs `uv run pytest crates/jiter-python/tests` is `test-python`, whose matrix is `python-version: ['3.14', '3.14t', 'graalpy3.12']` (ci.yml). On all of those, per the comment on line 417, GC is deferred to the eval loop and never fires inside `jiter.from_json`, so the `callback` is never invoked mid-parse, `unraisable` stays empty, and the `for u in unraisable` loop body never runs — the test passes vacuously. A regression that reintroduces the deadlock (or drops the panic) would go undetected, so this gives false confidence that the PR's central safety feature is protected. Assert that the hook actually captured something (e.g. `assert unraisable` on CPython <= 3.11) and/or add CPython <= 3.11 to the CI matrix that runs these tests.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread crates/jiter-python/tests/test_jiter.py Outdated
gc.set_threshold(*thresholds)

assert len(result) == 50_000
for u in unraisable:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This test never actually exercises the re-entrancy check in CI. The only job that runs uv run pytest crates/jiter-python/tests is test-python, whose matrix is python-version: ['3.14', '3.14t', 'graalpy3.12'] (ci.yml). On all of those, per the comment on line 417, GC is deferred to the eval loop and never fires inside jiter.from_json, so the callback is never invoked mid-parse, unraisable stays empty, and the for u in unraisable loop body never runs — the test passes vacuously. A regression that reintroduces the deadlock (or drops the panic) would go undetected, so this gives false confidence that the PR's central safety feature is protected. Assert that the hook actually captured something (e.g. assert unraisable on CPython <= 3.11) and/or add CPython <= 3.11 to the CI matrix that runs these tests.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At crates/jiter-python/tests/test_jiter.py, line 441:

<comment>This test never actually exercises the re-entrancy check in CI. The only job that runs `uv run pytest crates/jiter-python/tests` is `test-python`, whose matrix is `python-version: ['3.14', '3.14t', 'graalpy3.12']` (ci.yml). On all of those, per the comment on line 417, GC is deferred to the eval loop and never fires inside `jiter.from_json`, so the `callback` is never invoked mid-parse, `unraisable` stays empty, and the `for u in unraisable` loop body never runs — the test passes vacuously. A regression that reintroduces the deadlock (or drops the panic) would go undetected, so this gives false confidence that the PR's central safety feature is protected. Assert that the hook actually captured something (e.g. `assert unraisable` on CPython <= 3.11) and/or add CPython <= 3.11 to the CI matrix that runs these tests.</comment>

<file context>
@@ -413,3 +414,29 @@ def assert_jiter_ok(data: bytes, expected: Any) -> bool:
+        gc.set_threshold(*thresholds)
+
+    assert len(result) == 50_000
+    for u in unraisable:
+        assert 'locked by a parse in progress' in str(u.exc_value)
</file context>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 1 file (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread crates/jiter/src/py_string_cache.rs Resolved
@codspeed

codspeed Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 2 benchmarks

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 4 improved benchmarks
❌ 2 regressed benchmarks
✅ 61 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ python_parse_other 358 ns 401 ns -10.72%
❌ python_parse_numeric 1.3 µs 1.4 µs -10.09%
⚡ python_parse_string_array 13.3 µs 10.3 µs +29.85%
⚡ python_parse_string_array_unique 1.6 ms 1.3 ms +23.56%
⚡ python_parse_true_object 26.2 µs 22.7 µs +14.96%
⚡ python_parse_medium_response 25.7 µs 22.4 µs +14.83%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing string-cache-lock-per-parse (2029f6a) with main (e9c1cab)

Open in CodSpeed

@jessekrubin

Copy link
Copy Markdown
Contributor

@samuelcolvin very cool!

Do you think it could ever make sense to have a cache impl/instance be provided so that caches could be PER parse and immediately nuked? or only live as long as a single parse?

@samuelcolvin

Copy link
Copy Markdown
Member Author

could do, but in Python I don't think anyone cares, we just need to make it good.

@jessekrubin

jessekrubin commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

could do, but in Python I don't think anyone cares, we just need to make it good.

Totally agree from the python side, but from the rust side I could see scenarios where I would would want more fine grained control over the cache.

Any which way food for thought!

samuelcolvin and others added 6 commits September 12, 2026 11:34
Every cached string used to lock and unlock the global cache mutex
individually. The parser now holds the lock for the rest of the parse
from the first string of cacheable length, so parses with no such string
(a single long string, arrays of numbers or bools) never touch the mutex.
The lock is taken with try_lock: if another thread holds it, the parse
falls back to creating uncached strings instead of blocking.

Holding the lock across the parse means a Python callback that runs
while the parser allocates (GC callbacks and __del__ on CPython <= 3.11,
the decimal import in decimal mode) would deadlock if it called
jiter.cache_clear() or cache_usage(). A thread-local flag records that
the lock is held by the current thread, and those functions panic with a
clear message instead of blocking on their own lock; other threads still
block as before.

Split out of #280 as the minimal change, without the release profile,
single-character string and benchmark script changes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4KCoN9xWsA4HRCL3Lx63
GraalPy's gc module has no get_threshold, and the test only exercises
the check on CPython anyway.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4KCoN9xWsA4HRCL3Lx63
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4KCoN9xWsA4HRCL3Lx63
The guard's state moves into a private enum behind a private field, so
the cache type no longer has to be visible outside its module.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4KCoN9xWsA4HRCL3Lx63
@samuelcolvin
samuelcolvin force-pushed the string-cache-lock-per-parse branch from 935f38f to fa67c23 Compare September 12, 2026 10:34
samuelcolvin and others added 2 commits September 12, 2026 11:52
A parse takes a cache out of a pool on its first cacheable string and
puts it back when it ends, so no lock is ever held while Python code can
run and the thread-local re-entrancy flag goes. Under the GIL parses never
overlap and there is only ever one cache; on free-threaded builds a parse
that finds the pool empty builds another, which joins the pool afterwards.

cache_clear now leaves a cache that a parse is using untouched, and
cache_usage returns None when every cache is in use.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4KCoN9xWsA4HRCL3Lx63
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4KCoN9xWsA4HRCL3Lx63

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 6 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread crates/jiter/src/py_string_cache.rs Resolved
It counts the entries in the caches no parse is using, which under the
GIL is the one cache there is.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4KCoN9xWsA4HRCL3Lx63
@samuelcolvin
samuelcolvin merged commit 819dc92 into main Sep 12, 2026
29 of 30 checks passed
@samuelcolvin
samuelcolvin deleted the string-cache-lock-per-parse branch September 12, 2026 11:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants