Skip to content

Commit 409b1e0

Browse files
authored
Merge pull request #1 from OpenHCSDev/fix/durable-decorator-context-20260929
Keep runtime GPU context handles out of retained callable history
2 parents fddd985 + 06837ec commit 409b1e0

3 files changed

Lines changed: 66 additions & 12 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ all = [
7575
]
7676
dev = [
7777
"pytest>=7.0",
78+
"dill>=0.3.8",
7879
"pytest-cov>=4.0",
7980
"build>=1.0",
8081
"twine>=5.0",

‎src/arraybridge/decorators.py‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -264,12 +264,22 @@ def _insertion_index(parameters: list[inspect.Parameter]) -> int:
264264
return len(parameters)
265265

266266

267-
# Thread-local storage for GPU streams and contexts
268-
_thread_gpu_contexts = threading.local()
267+
class ThreadGPUContext:
268+
"""Runtime-owned thread-local streams keyed by framework/device identity.
269269
270+
Keep the runtime handle on its importable owner, not in decorator function
271+
globals. A retained, unpublished decorated callable is serialized by value;
272+
its durable closure must not pull a ``threading.local`` into history.
273+
"""
270274

271-
class ThreadGPUContext:
272-
"""Thread-local streams keyed by framework-local device identity."""
275+
_contexts: ClassVar[threading.local] = threading.local()
276+
277+
@classmethod
278+
def current(cls) -> "ThreadGPUContext":
279+
"""Return this thread's runtime context without serializing its handle."""
280+
if not hasattr(cls._contexts, "context"):
281+
cls._contexts.context = cls()
282+
return cls._contexts.context
273283

274284
def __init__(self):
275285
self._streams: dict[tuple[MemoryType, int], Any] = {}
@@ -301,13 +311,6 @@ def stream_for(
301311
return device_id, self._streams[key]
302312

303313

304-
def _get_thread_gpu_context():
305-
"""Get or create thread-local GPU context."""
306-
if not hasattr(_thread_gpu_contexts, "context"):
307-
_thread_gpu_contexts.context = ThreadGPUContext()
308-
return _thread_gpu_contexts.context
309-
310-
311314
def memory_types(
312315
input_type: str | MemoryType,
313316
output_type: str | MemoryType,
@@ -461,7 +464,7 @@ def gpu_wrapper(*args, **kwargs):
461464
# Check if GPU is available for this framework
462465
if framework is not None and mem_type.available_device_ids(framework):
463466
# Get thread-local context
464-
ctx = _get_thread_gpu_context()
467+
ctx = ThreadGPUContext.current()
465468

466469
device_id, stream = ctx.stream_for(mem_type, framework)
467470

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""Retained callable declarations exclude thread-local GPU lifecycle handles."""
2+
3+
import threading
4+
from concurrent.futures import ThreadPoolExecutor
5+
6+
import dill
7+
import numpy as np
8+
import pytest
9+
10+
from arraybridge.decorators import ThreadGPUContext, cupy, numpy
11+
from arraybridge.types import MemoryType
12+
13+
14+
def test_context_is_stable_per_thread_and_never_shared_between_threads():
15+
current = ThreadGPUContext.current()
16+
with ThreadPoolExecutor(max_workers=1) as executor:
17+
other, repeated = executor.submit(
18+
lambda: (ThreadGPUContext.current(), ThreadGPUContext.current())
19+
).result()
20+
assert ThreadGPUContext.current() is current
21+
assert other is repeated
22+
assert other is not current
23+
24+
25+
@pytest.mark.parametrize("decorator", [numpy, cupy])
26+
def test_unpublished_decorated_callable_serializes_without_runtime_context(decorator):
27+
# Like a replaced custom function retained by an undo snapshot, this
28+
# declaration has no importable public alias. Dill must persist its body.
29+
@decorator
30+
def declared(image, scale=3):
31+
return image * scale
32+
33+
context = ThreadGPUContext.current()
34+
key = (MemoryType.CUPY, -1)
35+
handle = threading.local()
36+
context._streams[key] = handle
37+
try:
38+
restored = dill.loads(dill.dumps(declared))
39+
assert restored.__name__ == declared.__name__
40+
assert restored.__wrapped__.__name__ == declared.__wrapped__.__name__
41+
# CPU NumPy invocation checks actual restored behavior. GPU behavior
42+
# keeps its existing focused tests; this receipt starts no GPU runtime.
43+
if decorator is numpy:
44+
np.testing.assert_array_equal(
45+
restored(np.array([1, 2], dtype=np.uint16), scale=4), [4, 8]
46+
)
47+
assert ThreadGPUContext.current() is context
48+
assert context._streams[key] is handle
49+
finally:
50+
del context._streams[key]

0 commit comments

Comments
 (0)