Skip to content

Guard ContextVar call-stack tracking against GC re-entry (#596) - #637

Open
Bukzie wants to merge 3 commits into
boxed:mainfrom
bukzie-opensource:fix/596-contextvar-reentrancy
Open

Bukzie wants to merge 3 commits into
boxed:mainfrom
bukzie-opensource:fix/596-contextvar-reentrancy

Conversation

@Bukzie

@Bukzie Bukzie commented Nov 13, 2026

Copy link
Copy Markdown

Summary

  • Guard MutmutCallStack access on Python < 3.12 when a finalizer interrupts a ContextVar.set() or reset().
  • Avoid changing process-wide GC state. A finalizer that interrupts an update is left out of caller dependency tracking.
  • Add deterministic unit tests and end-to-end regressions for a trampolined __del__, a finalizer that calls another tracked function, and a multithreaded non-regression case.

Fixes #596.

Verification

  • On macOS arm64 with Python 3.11.16, the direct regression exits -11 on the unmodified base and passes with this patch.
  • pre-commit run --all-files --show-diff-on-failure passed, including Ruff and mypy.
  • Full local suite on Python 3.10.21, 3.11.16, and 3.12.13: each had 493 passed, 2 skipped, and 1 failed. The failure is test_setproctitle_crashes_after_fork_with_corefoundation_loaded, which also fails on the current unmodified upstream head on this Mac.
  • Linux CI is pending.

The precise CPython failure mechanism and the 3.12 version boundary are inferred from the reproduction and linked CPython reports, rather than independently proven here. The interrupted finalizer's caller edge is intentionally omitted.

AI tooling assisted the investigation, patch preparation, and validation. I will own follow-up and review on this PR.

…dates

On CPython < 3.12 the cyclic GC can run inside ContextVar.set()/reset().
A garbage object with a trampolined __del__ then touches the half-updated
ContextVar, which corrupts it and segfaults stats collection (boxed#596).

Track a per-thread "busy" flag around set()/reset(). While it is set,
get() reports no caller and set()/reset() do nothing, so such a finalizer
is simply not tracked. No process-wide GC state is touched.
Independent review asked for the CPython root cause to be worded as
believed, not established, and for the reset() re-entrancy branch to be
covered by a test.
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.

Stats collection crashes on Python 3.11 when a trampolined __del__ runs during GC (ContextVar re-entry)

1 participant