Skip to content

Make under_cached_property and cached_property safe for free-threading - #297

Merged
bdraco merged 9 commits into
masterfrom
ft_safe
Sep 15, 2026
Merged

bdraco merged 9 commits into
masterfrom
ft_safe

Conversation

@bdraco

@bdraco bdraco commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Fixes a use-after-free in the C cached_property and under_cached_property descriptors on free-threaded Python. The cached value was read through a borrowed reference from PyDict_GetItem, so another thread evicting it could free it before __get__ returned it. The descriptors now use PyDict_GetItemRef from cpython.dict on all builds.

On GIL builds the hit path is as fast as before or slightly faster, since PyDict_GetItem saves and restores the pending exception on every call. Errors raised while looking up the cache now propagate like they do in the pure Python implementation, instead of being reported as unraisable and treated as a miss. The miss path also no longer leaks the computed value when storing it in the cache fails.

Are there changes in behavior for the user?

Free-threaded builds no longer crash when a cached value is evicted concurrently. Errors raised while looking up the cache, such as from a colliding key whose __eq__ raises, are now propagated by the C extension.

Related issue number

N/A

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes (N/A)
  • Add a new news fragment into the CHANGES/ folder

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 15, 2026
Comment thread src/propcache/_helpers_c.pyx Resolved
@bdraco bdraco changed the title Make under_cached_property.__get__ safe for free-threading Make under_cached_property and cached_property safe for free-threading Sep 15, 2026
At 20,000 iterations the cached_property test only crashed the
unpatched free-threaded build in 2 of 3 runs; at 100,000 both tests
crash it in 5 of 5 runs while still finishing in well under a second.
@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@bdraco

bdraco commented Sep 15, 2026

Copy link
Copy Markdown
Member Author
  1. Cython already ships a PyDict_GetItemRef backport, so most of the custom C block can go

Will need to benchmark that. The idea was to keep the instructions byte identical from master on GIL

@codspeed

codspeed Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 4 untouched benchmarks


Comparing ft_safe (064a3f3) with master (c48781a)

Open in CodSpeed

Cython's cpython.dict.PyDict_GetItemRef replaces the custom lookup
helper. Lookup errors now propagate on GIL builds too, matching the
pure Python implementation, instead of being reported as unraisable
and treated as a miss. PyDict_GetItem saves and restores the pending
exception on every call, so the hit path is no slower on GIL builds.

The miss path is plain Cython again, which also releases the computed
value when storing it in the cache fails.
@codecov

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (c48781a) to head (064a3f3).

Additional details and impacted files
@@            Coverage Diff            @@
##            master      #297   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           10        10           
  Lines          437       532   +95     
  Branches        17        27   +10     
=========================================
+ Hits           437       532   +95     
Flag Coverage Δ
CI-GHA 98.30% <100.00%> (+0.36%) ⬆️
OS-Linux 98.30% <100.00%> (+0.36%) ⬆️
OS-Windows 95.86% <100.00%> (+0.89%) ⬆️
OS-macOS 95.86% <100.00%> (+0.89%) ⬆️
Py-3.10 95.86% <100.00%> (+0.89%) ⬆️
Py-3.11 97.18% <100.00%> (+0.61%) ⬆️
Py-3.12 97.18% <100.00%> (+0.61%) ⬆️
Py-3.13 97.18% <100.00%> (+0.61%) ⬆️
Py-3.14 97.16% <100.00%> (+0.62%) ⬆️
Py-3.14t 97.16% <100.00%> (+0.62%) ⬆️
Py-pypy-3.10 82.33% <100.00%> (+3.84%) ⬆️
VM-macos-latest 95.86% <100.00%> (+0.89%) ⬆️
VM-ubuntu-latest 98.30% <100.00%> (+0.36%) ⬆️
VM-windows-11-arm 95.67% <100.00%> (+0.93%) ⬆️
VM-windows-latest 95.86% <100.00%> (+0.89%) ⬆️
pytest 98.30% <100.00%> (+0.36%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@aiolibsbot

Copy link
Copy Markdown
Contributor

@bdraco: > 1. Cython already ships a PyDict_GetItemRef backport, so most of the custom C block can go

Adopted in 4233aff. Hit path no longer byte-identical to master. Cython maps PyDict_GetItemRef to __Pyx_PyDict_GetItemRef. On 3.13+: real PyDict_GetItemRef. On 3.10 to 3.12: PyDict_GetItemWithError plus Py_INCREF. Old PyDict_GetItem saved and restored exception state per lookup. New path skips that. Probably equal or faster. Check CodSpeed to confirm. Update PR body wording.

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

The race the test guards against cannot happen with the GIL, so GIL
and PyPy legs run 1,000 iterations instead of 100,000.
@aiolibsbot

Copy link
Copy Markdown
Contributor

PR Review — Make under_cached_property and cached_property safe for free-threading

Ready to merge. Both notes from the last review are resolved, and I found no new issues.

What the PR does well:

  • Error handling is correct. Cython 3.3.0's cpython/dict.pxd declares PyDict_GetItemRef with except -1. A lookup error is therefore raised before the if, and -1 can never reach propcache_steal. On a hit, the one strong reference goes straight to Cython. On a miss, PyObject_CallOneArg returns object, so a failed store is cleaned up without leaking.
  • C and pure Python match. _helpers_py.under_cached_property subscripts the cache inside try/except KeyError, and functools.cached_property uses dict.get. Both already let lookup errors propagate, so the C extension now matches them.
  • The tests would actually catch the bug. pytest.ini sets filterwarnings = error, so a failed assert inside a reader thread fails the test instead of just printing. The CI matrix includes 3.14t on Ubuntu, macOS and Windows, so the race is exercised where it exists.
  • CollidingKey.__eq__ is fully covered. Both branches run, which satisfies the repo's rule that test code is covered too. The cached_property test calls __get__ directly, which correctly avoids the instance dict lookup.

Resolved since the last review:

  • PR description: it now says PyDict_GetItemRef is used on every build and lists the error propagation and leak fix as user-visible changes.
  • Test cost: the new eviction_iterations session fixture in tests/conftest.py runs 100k iterations only when Py_GIL_DISABLED is set, and 1k on GIL and PyPy runs. It fits on one line, so coverage has no untaken branch to flag.
  • Duplication: dropped. tests/test_cached_property.py and tests/test_under_cached_property.py already mirror each other on purpose (for example *_no_refcount_leak), so a copy in each file follows the repo's pattern.

Not verified:

  • That master crashes reliably on 3.14t with this test. I couldn't build the extension on a free-threaded interpreter in a read-only review.
  • That the GIL hit path is as fast or slightly faster. It's plausible, since PyDict_GetItem saves and restores the pending exception on every call, but the CodSpeed results are the real check.

✅ Resolved since last review (1)

Previously-flagged issues verified fixed
  • tests/test_under_cached_property.py:258 Concurrent eviction test runs 100k iterations on every CI leg and is duplicated across two files


Checklist

  • No hardcoded secrets
  • Reference counting correct on hit, miss and store-failure paths
  • Lookup errors propagate consistently across GIL and free-threaded builds
  • C and pure-Python implementations stay behaviourally identical
  • New behaviour covered by tests, no unreachable test lines
  • Tests sized for the legs they run on
  • CHANGES fragment present and follows conventions
  • PR description matches diff

Automated review by Kōan (Claude) HEAD=311f94e 3 min 10s

@bdraco
bdraco marked this pull request as ready for review September 15, 2026 16:50
@greptile-apps

greptile-apps Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5

Safe to merge.

Reviews (2): Last reviewed commit: "Keep the new tests out of the mypy impre..." | Re-trigger Greptile

Comment thread src/propcache/_helpers_c.pyx Resolved
Annotate the instance dict, reach the descriptor through the class
instead of __dict__, and build the thread list in one comprehension,
so the added lines do not lower the type preciseness score.
@bdraco
bdraco merged commit 3447e83 into master Sep 15, 2026
61 checks passed
@bdraco
bdraco deleted the ft_safe branch September 15, 2026 17:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants