#8765·RustPython

`ContextVar` values leak between interpreters

Author: YangSiJun528Created Sep 21, 2026Updated Sep 21, 2026
LabelsC-bugz-ca-2026

Summary

Values set in a subinterpreter remain in the main interpreter's context after the subinterpreter is destroyed and GC runs.

The reproduction runs both interpreters on the same OS thread without explicitly passing any context or variables between them. The main interpreter's context should remain unchanged.

python
import _interpreters
import contextvars
import gc

child = _interpreters.create()
try:
    assert _interpreters.run_string(child, """
import contextvars
contextvars.ContextVar('child_marker').set(42)
""") is None
finally:
    _interpreters.destroy(child)

gc.collect()
print([
    (var.name, value)
    for var, value in contextvars.copy_context().items()
    if var.name == 'child_marker'
])

Expected

CPython 3.14.6:

[]

Actual

RustPython 803520930:

[('child_marker', 42)]

Creating and destroying three subinterpreters, each setting a different variable, leaves [1, 2, 3] variables from those subinterpreters in the main interpreter's context after successive GC calls. CPython leaves [0, 0, 0]. The destroyed subinterpreters were also confirmed absent from _interpreters.list_all().

RustPython's CONTEXTS stack is stored per OS thread. PyContext::current() reuses it without distinguishing interpreters, and interpreter finalization does not remove the subinterpreter's entries.

Python Documentation

AI assistance: Codex (gpt-6-astra) investigated the code, prepared and ran the reproductions, compared the results with CPython, and drafted this report.