fix: make the ambient scan root thread-isolated via ContextVar

_ACTIVE_SCAN_ROOT was a module global. Extraction runs concurrently
(ThreadPoolExecutor in tests, process pools in production), and
overlapping set/restore pairs in _safe_extract_with_xaml_root
interleaved: the second call saved the first one's root and restored it
last, leaving the ambient root set after extract() returned. Nine tests
downstream failed in any non-default order
(#4602, diagnosis by Deepjyoti Sarmah).

Replace the global with a contextvars.ContextVar: every thread (and
async task) gets its own value, so save/restore pairs nest correctly by
construction and the set/return-previous API is unchanged.

Proves the old failure: tests/test_scan_root_contextvar.py asserts each
thread sees its own root at the race window. under the global both
threads read the last setter's value, and the loser of the restore race
leaked the winner's root. Fails on the global, passes with the fix.

Fixes #4602

(cherry picked from commit 2c51667211)
This commit is contained in:
Wyatt Au authored and safishamsi committed 2026-11-05 12:11:26 +00:00
1 parent d329bcdfdb
commit e93821ff3c
2 files changed
+89 -5

No files matched your search

+15 -5
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import sys
from contextvars import ContextVar
from pathlib import Path
from graphify.ids import make_id
@@ -15,15 +16,24 @@ from graphify.ids import make_id
# function-local `import graphify.extract` + getattr(..., None) was a package ->
# parent dependency that also failed silently if the module global were renamed
# (#3666). None outside extract().
_ACTIVE_SCAN_ROOT: "Path | None" = None
#
# A ContextVar rather than a module global: extraction runs concurrently
# (ThreadPoolExecutor in tests, process pools in production), and a plain
# global lets overlapping save/restore pairs interleave — the second call
# saves the first one's root and restores it last, leaving the ambient root
# set after extract() returns (#4602). ContextVar gives every thread (and
# async task) its own value, so save/restore pairs nest correctly without a
# lock.
_ACTIVE_SCAN_ROOT: "ContextVar[Path | None]" = ContextVar(
"_ACTIVE_SCAN_ROOT", default=None
)
def set_active_scan_root(root: "Path | None") -> "Path | None":
"""Set the in-flight scan root, returning the previous value so the caller
can restore it — extraction nests (a XAML shard re-enters extract())."""
global _ACTIVE_SCAN_ROOT
previous = _ACTIVE_SCAN_ROOT
_ACTIVE_SCAN_ROOT = root
previous = _ACTIVE_SCAN_ROOT.get()
_ACTIVE_SCAN_ROOT.set(root)
return previous
@@ -32,7 +42,7 @@ def active_scan_root() -> "Path | None":
A direct ``extract_markdown()`` / ``extract_xaml()`` call (no surrounding
``extract()``) sees None and the root-dependent behavior stays off."""
return _ACTIVE_SCAN_ROOT
return _ACTIVE_SCAN_ROOT.get()
# Language built-in globals that AST may classify as call targets when used as
# constructors or coercion functions (e.g. String(x), Number(x), Boolean(x)).
+74
View File
@@ -0,0 +1,74 @@
"""The ambient scan root save/restore pair must be thread-isolated.
Regression test for #4602: `_ACTIVE_SCAN_ROOT` was a module global, so
overlapping extractions on different threads interleaved their
save/restore pairs — the second call saved the first one's root and
restored it last, leaving the ambient root set after `extract()`
returned. Nine tests downstream failed in any non-default order.
A module global cannot be made race-free without a lock around every
read; a `contextvars.ContextVar` gives each thread its own value and
makes the pairs nest correctly by construction.
"""
from __future__ import annotations
import threading
from graphify.extractors import base as base_mod
def test_concurrent_save_restore_pairs_do_not_leak():
"""Two threads doing overlapping set/restore cycles must each see their
own root at the peak and return to the outer value (None) after
restore. The old module global failed both assertions: the peak read
was contaminated by the other thread's root, and the loser of the
save/restore race leaked the winner's root past extract()."""
barrier = threading.Barrier(2)
seen = {}
def worker(name: str, root_value: str) -> None:
previous = base_mod.set_active_scan_root(root_value)
barrier.wait() # both roots are set at this point — the race window
seen[name] = (base_mod.active_scan_root(), previous)
base_mod.set_active_scan_root(previous)
barrier.wait() # both restores have run
seen[name + ":after"] = base_mod.active_scan_root()
t1 = threading.Thread(target=worker, args=("A", "/root-a"))
t2 = threading.Thread(target=worker, args=("B", "/root-b"))
t1.start()
t2.start()
t1.join()
t2.join()
# Each thread sees ITS OWN root at the peak (a shared global would
# show the last setter's value in both).
assert seen["A"] == ("/root-a", None)
assert seen["B"] == ("/root-b", None)
# And after restore, each thread is back to the outer value — no
# leakage in either direction, whatever the interleaving.
assert seen["A:after"] is None
assert seen["B:after"] is None
def test_concurrent_workers_see_their_own_root():
"""Two threads setting different roots concurrently must each read
their own root back — the ContextVar isolates them."""
import concurrent.futures
observed = {}
def worker(name: str, root_value: str) -> None:
base_mod.set_active_scan_root(root_value)
observed[name] = base_mod.active_scan_root()
base_mod.set_active_scan_root(None)
threads = [
threading.Thread(target=worker, args=(name, value))
for name, value in [("t1", "/one"), ("t2", "/two")]
]
for t in threads:
t.start()
for t in threads:
t.join()
assert observed["t1"] == "/one"
assert observed["t2"] == "/two"