From e423e0a2ca41ed0039123ec140eb7d0b4c446595 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 4 Sep 2026 09:44:07 +0800 Subject: [PATCH 1/3] Fix Python lifetime scope thread affinity Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 4 +- bindings/py/README.md | 5 + bindings/py/src/lib.rs | 37 +++- bindings/py/tests/test_phase1.py | 170 +++++++++++++++++- .../src/codegen/winrt/python/generator/mod.rs | 25 ++- 5 files changed, 231 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 17edd114..d7d8847c 100644 --- a/README.md +++ b/README.md @@ -212,8 +212,8 @@ cargo run -p dynwinrt-codegen -- generate --namespace Windows.Foundation --cla Python [`dynwinrt`](https://pypi.org/project/dynwinrt/) runtime wheels target CPython 3.11–3.14 on Windows x64 and ARM64. The standalone -[`dynwinrt-codegen`](https://pypi.org/project/dynwinrt-codegen/) wheel runs on -Python 3.8–3.14 and needs no Rust installation at consumption time. +[`dynwinrt-codegen`](https://pypi.org/project/dynwinrt-codegen/) wheel includes +the prebuilt generator and requires no Rust installation. Python runtime, codegen, packaging, and WinUI readiness are tracked in [`docs/status/PYTHON_CHECKLIST.md`](docs/status/PYTHON_CHECKLIST.md). diff --git a/bindings/py/README.md b/bindings/py/README.md index 53e0db51..55104c20 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -260,6 +260,11 @@ with RoApartment(0), projected_lifetime_scope(): Scopes nest in LIFO order. Wrappers that survive a closed scope remain Python objects, but their native values are released and further WinRT calls fail. +Each scope is thread-affine: enter, use, and close it inside that thread's +`RoApartment`. Same-thread asyncio tasks inherit the active scope, while worker +threads must open their own ordered +`with RoApartment(...), projected_lifetime_scope():`. Generated delegate +callbacks invoked on foreign threads use a callback-local scope automatically. Normal construction remains unavailable for protected-only composable classes and system-returned classes without public activation metadata. Named Python diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index fff04792..224fa697 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -28,9 +28,9 @@ from collections.abc import ( ) from datetime import datetime as _datetime, timedelta as _timedelta, timezone as _timezone from itertools import count as _count -from contextvars import ContextVar as _ContextVar +from contextvars import ContextVar as _ContextVar, copy_context as _copy_context from operator import index as _index -from threading import get_ident as _thread_get_ident +from threading import current_thread as _thread_current_thread, get_ident as _thread_get_ident from types import TracebackType as _TracebackType from typing import Any as _Any, Awaitable as _Awaitable, Callable as _Callable from typing import Protocol as _Protocol, TypeVar as _TypeVar @@ -169,6 +169,7 @@ class ProjectedLifetimeScope: def __init__(self): self._registry = {} self._token = None + self._owner_thread = None self._active = False self._disposed = False self._retry_pending = False @@ -178,11 +179,24 @@ class ProjectedLifetimeScope: def disposed(self): return self._disposed + def _require_owner_thread(self, operation): + if ( + self._owner_thread is not None + and _thread_current_thread() is not self._owner_thread + ): + raise RuntimeError( + f'Cannot {operation} a projection lifetime scope from a different ' + 'thread. Worker threads must use their own ordered ' + '`with RoApartment(...), projected_lifetime_scope():`.' + ) + def __enter__(self): + self._require_owner_thread('enter') if self._disposed: raise RuntimeError('Cannot enter a disposed projection lifetime scope.') if self._active: raise RuntimeError('The projection lifetime scope is already active.') + self._owner_thread = _thread_current_thread() self._token = _active_projected_lifetime_scope.set(self) self._active = True return self @@ -198,6 +212,7 @@ class ProjectedLifetimeScope: return False def track(self, value, type_name=None): + self._require_owner_thread('track values in') if not self._active or self._disposed: raise RuntimeError('Cannot track values in an inactive projection lifetime scope.') for native in _dynwinrt_projected_native_values(value): @@ -205,6 +220,7 @@ class ProjectedLifetimeScope: return value def close(self): + self._require_owner_thread('close') if self._disposed: return if not self._active: @@ -247,6 +263,23 @@ def _dynwinrt_append_exception_cause(error, cleanup_error): def projected_lifetime_scope(): return ProjectedLifetimeScope() +def _dynwinrt_wrap_delegate_callback(callback): + context = _copy_context() + owner_thread = _thread_current_thread() + + def invoke(*args): + callback_context = context.copy() + if _thread_current_thread() is owner_thread: + return callback_context.run(callback, *args) + + def invoke_foreign_thread(): + with projected_lifetime_scope(): + return callback(*args) + + return callback_context.run(invoke_foreign_thread) + + return invoke + def _dynwinrt_track_projected(value, type_name=None): scope = _active_projected_lifetime_scope.get() if scope is not None and scope._active and not scope._disposed: diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index b4b68fe1..ef26b2b3 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -16,7 +16,7 @@ import asyncio from collections.abc import Coroutine -from contextvars import copy_context +from contextvars import ContextVar, copy_context from datetime import datetime, timedelta, timezone import gc import inspect @@ -61,6 +61,7 @@ _dynwinrt_ticks_to_datetime, _dynwinrt_ticks_to_timedelta, _dynwinrt_timedelta_to_ticks, + _dynwinrt_wrap_delegate_callback, ) @@ -1195,6 +1196,173 @@ def release(self): assert scope.disposed +def test_active_scope_rejects_asyncio_to_thread_tracking(): + class Native: + def __init__(self): + self.release_threads = [] + + def release(self): + self.release_threads.append(threading.get_ident()) + + native = Native() + owner_thread = threading.get_ident() + + async def track_on_worker(): + with pytest.raises(RuntimeError, match="different thread"): + await asyncio.to_thread( + _dynwinrt_track_projected, + SimpleNamespace(_obj=native), + "Foreign", + ) + + with projected_lifetime_scope(): + asyncio.run(track_on_worker()) + + assert native.release_threads == [] + assert threading.get_ident() == owner_thread + + +def test_copied_context_rejects_foreign_scope_tracking_and_close(): + class Native: + def __init__(self): + self.release_threads = [] + + def release(self): + self.release_threads.append(threading.get_ident()) + + owner_thread = threading.get_ident() + native = Native() + foreign_native = Native() + scope = projected_lifetime_scope() + scope.__enter__() + scope.track(SimpleNamespace(_obj=native), "Owner") + inherited_context = copy_context() + errors = [] + + def worker(): + for operation in ( + lambda: scope.track(SimpleNamespace(_obj=foreign_native), "Foreign"), + scope.close, + ): + try: + inherited_context.copy().run(operation) + except BaseException as error: + errors.append(error) + + thread = threading.Thread(target=worker) + thread.start() + thread.join() + + assert len(errors) == 2 + assert all( + isinstance(error, RuntimeError) and "different thread" in str(error) + for error in errors + ) + assert native.release_threads == [] + assert foreign_native.release_threads == [] + assert not scope.disposed + + scope.close() + assert native.release_threads == [owner_thread] + assert foreign_native.release_threads == [] + + +def test_generated_delegate_callback_uses_foreign_thread_lifetime_scope(): + marker = ContextVar("dynwinrt_test_callback_marker", default=None) + + class Native: + def __init__(self): + self.release_threads = [] + + def release(self): + self.release_threads.append(threading.get_ident()) + + owner_thread = threading.get_ident() + parent_native = Native() + callback_native = Native() + callback_state = {} + marker_token = marker.set("captured") + + try: + with projected_lifetime_scope() as parent_scope: + parent_scope.track(SimpleNamespace(_obj=parent_native), "Parent") + + def callback(): + callback_state["thread"] = threading.get_ident() + callback_state["marker"] = marker.get() + _dynwinrt_track_projected( + SimpleNamespace(_obj=callback_native), + "Callback", + ) + callback_state["released_during_callback"] = bool( + callback_native.release_threads + ) + + invoke = _dynwinrt_wrap_delegate_callback(callback) + + thread = threading.Thread(target=invoke) + thread.start() + thread.join() + + callback_thread = callback_state["thread"] + assert callback_thread != owner_thread + assert callback_state["marker"] == "captured" + assert not callback_state["released_during_callback"] + assert callback_native.release_threads == [callback_thread] + assert parent_native.release_threads == [] + + assert parent_native.release_threads == [owner_thread] + assert callback_native.release_threads == [callback_thread] + finally: + marker.reset(marker_token) + + +def test_generated_delegate_callback_preserves_same_thread_scope(): + class Native: + def __init__(self): + self.release_threads = [] + + def release(self): + self.release_threads.append(threading.get_ident()) + + owner_thread = threading.get_ident() + native = Native() + + def callback(): + _dynwinrt_track_projected(SimpleNamespace(_obj=native), "Callback") + + with projected_lifetime_scope(): + invoke = _dynwinrt_wrap_delegate_callback(callback) + invoke() + assert native.release_threads == [] + + assert native.release_threads == [owner_thread] + + +def test_same_thread_asyncio_task_inherits_projection_lifetime_scope(): + class Native: + def __init__(self): + self.release_threads = [] + + def release(self): + self.release_threads.append(threading.get_ident()) + + owner_thread = threading.get_ident() + native = Native() + + async def track_in_task(): + async def child(): + _dynwinrt_track_projected(SimpleNamespace(_obj=native), "Task") + + await asyncio.create_task(child()) + + with projected_lifetime_scope(): + asyncio.run(track_in_task()) + assert native.release_threads == [] + + assert native.release_threads == [owner_thread] + + def test_nested_cleanup_preserves_the_first_failure(): class FailingNative: def __init__(self, message): diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs index 704addde..c8f98364 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -58,7 +58,6 @@ from ._runtime import ( const RUNTIME_SUPPORT_BODY: &str = "\ from builtins import property as _property -from contextvars import copy_context as _copy_context from functools import lru_cache from importlib import import_module from collections.abc import ( @@ -77,6 +76,7 @@ from dynwinrt.dynwinrt import ( _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, _dynwinrt_ticks_to_timedelta, _dynwinrt_timedelta_to_ticks, _dynwinrt_cache_projected, _dynwinrt_projected_from_native, _dynwinrt_track_projected, _dynwinrt_uuid, _dynwinrt_vector, + _dynwinrt_wrap_delegate_callback, ) @@ -100,10 +100,11 @@ def _dynwinrt_enum(module, name, value): def _dynwinrt_create_delegate(iid, parameter_types, callback): - context = _copy_context() - def invoke(*args): - return context.copy().run(callback, *args) - return DynWinRtDelegate.create(iid, parameter_types, invoke) + return DynWinRtDelegate.create( + iid, + parameter_types, + _dynwinrt_wrap_delegate_callback(callback), + ) def _dynwinrt_delegate(value, iid, parameter_types): raw = getattr(value, '_obj', value) @@ -194,3 +195,17 @@ pub use index::{ }; pub use structs::generate_struct; pub use types::{generate_enum, generate_interface}; + +#[cfg(test)] +mod tests { + use super::generate_runtime_support_module; + + #[test] + fn generated_delegates_use_thread_affine_callback_contexts() { + let runtime = generate_runtime_support_module(); + + assert!(runtime.contains("_dynwinrt_wrap_delegate_callback,")); + assert!(runtime.contains("_dynwinrt_wrap_delegate_callback(callback),")); + assert!(!runtime.contains("copy_context")); + } +} From 571db161b8f0f0cba08d046789118e9f21514479 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 4 Sep 2026 09:51:19 +0800 Subject: [PATCH 2/3] Preserve retained callback projections Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/README.md | 7 +++++-- bindings/py/src/lib.rs | 5 ++++- bindings/py/tests/test_phase1.py | 36 ++++++++++++++++++++++++-------- 3 files changed, 36 insertions(+), 12 deletions(-) diff --git a/bindings/py/README.md b/bindings/py/README.md index 55104c20..0382c4d3 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -263,8 +263,11 @@ objects, but their native values are released and further WinRT calls fail. Each scope is thread-affine: enter, use, and close it inside that thread's `RoApartment`. Same-thread asyncio tasks inherit the active scope, while worker threads must open their own ordered -`with RoApartment(...), projected_lifetime_scope():`. Generated delegate -callbacks invoked on foreign threads use a callback-local scope automatically. +`with RoApartment(...), projected_lifetime_scope():`. A generated delegate +callback invoked on a foreign thread preserves other captured context but does +not inherit the creator thread's lifetime scope. Retained callback values remain +user-owned; open an explicit callback-local scope for deterministic temporary +cleanup. Normal construction remains unavailable for protected-only composable classes and system-returned classes without public activation metadata. Named Python diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 224fa697..bb9092c4 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -273,8 +273,11 @@ def _dynwinrt_wrap_delegate_callback(callback): return callback_context.run(callback, *args) def invoke_foreign_thread(): - with projected_lifetime_scope(): + token = _active_projected_lifetime_scope.set(None) + try: return callback(*args) + finally: + _active_projected_lifetime_scope.reset(token) return callback_context.run(invoke_foreign_thread) diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index ef26b2b3..3a8328a1 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -1267,7 +1267,7 @@ def worker(): assert foreign_native.release_threads == [] -def test_generated_delegate_callback_uses_foreign_thread_lifetime_scope(): +def test_generated_delegate_callback_masks_parent_scope_on_foreign_thread(): marker = ContextVar("dynwinrt_test_callback_marker", default=None) class Native: @@ -1277,10 +1277,15 @@ def __init__(self): def release(self): self.release_threads.append(threading.get_ident()) + def is_null(self): + return bool(self.release_threads) + owner_thread = threading.get_ident() parent_native = Native() callback_native = Native() callback_state = {} + retained_wrappers = [] + unretained_drop_threads = [] marker_token = marker.set("captured") try: @@ -1290,12 +1295,23 @@ def release(self): def callback(): callback_state["thread"] = threading.get_ident() callback_state["marker"] = marker.get() - _dynwinrt_track_projected( - SimpleNamespace(_obj=callback_native), - "Callback", + retained_wrappers.append( + _dynwinrt_track_projected( + SimpleNamespace(_obj=callback_native), + "RetainedCallbackValue", + ) ) - callback_state["released_during_callback"] = bool( - callback_native.release_threads + + class UnretainedNative: + def __del__(self): + unretained_drop_threads.append(threading.get_ident()) + + def release(self): + raise AssertionError("unretained value entered a lifetime scope") + + _dynwinrt_track_projected( + SimpleNamespace(_obj=UnretainedNative()), + "UnretainedCallbackValue", ) invoke = _dynwinrt_wrap_delegate_callback(callback) @@ -1307,12 +1323,14 @@ def callback(): callback_thread = callback_state["thread"] assert callback_thread != owner_thread assert callback_state["marker"] == "captured" - assert not callback_state["released_during_callback"] - assert callback_native.release_threads == [callback_thread] + assert not callback_native.is_null() + assert unretained_drop_threads == [callback_thread] assert parent_native.release_threads == [] assert parent_native.release_threads == [owner_thread] - assert callback_native.release_threads == [callback_thread] + assert not callback_native.is_null() + release_projected(retained_wrappers.pop()) + assert callback_native.release_threads == [owner_thread] finally: marker.reset(marker_token) From caf0a83ccf4e543d19807f1e86da72c4ca6e5d89 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 4 Sep 2026 10:48:23 +0800 Subject: [PATCH 3/3] Mask lifetime scopes in native callbacks Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 778823b5-9f70-4a61-95a9-19e3d37f95e9 --- bindings/py/README.md | 7 +- bindings/py/src/runtime.rs | 85 +++++++++---------- bindings/py/tests/test_e2e_winrt.py | 63 +++++++++++++- bindings/py/tests/test_phase1.py | 123 ++++++++++++++++++++++++++++ 4 files changed, 230 insertions(+), 48 deletions(-) diff --git a/bindings/py/README.md b/bindings/py/README.md index 0382c4d3..71347ff0 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -263,9 +263,10 @@ objects, but their native values are released and further WinRT calls fail. Each scope is thread-affine: enter, use, and close it inside that thread's `RoApartment`. Same-thread asyncio tasks inherit the active scope, while worker threads must open their own ordered -`with RoApartment(...), projected_lifetime_scope():`. A generated delegate -callback invoked on a foreign thread preserves other captured context but does -not inherit the creator thread's lifetime scope. Retained callback values remain +`with RoApartment(...), projected_lifetime_scope():`. Native callbacks invoked +on a foreign thread preserve other captured context but do not inherit the +creator thread's lifetime scope. This includes generated delegates, raw progress +handlers, and element-factory callbacks. Retained callback values remain user-owned; open an explicit callback-local scope for deterministic temporary cleanup. diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index c3c138e1..091b4d90 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -15,6 +15,14 @@ use crate::errors::{map_dynwinrt_error, map_dynwinrt_error_with_context, map_win static TABLE: std::sync::LazyLock> = std::sync::LazyLock::new(|| dynwinrt::MetadataTable::new()); +fn wrap_python_callback_context(py: Python<'_>, callback: Py) -> PyResult> { + Ok(py + .import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_wrap_delegate_callback")? + .call1((callback,))? + .unbind()) +} + fn checked_index(index: i64) -> PyResult { usize::try_from(index) .map_err(|_| PyIndexError::new_err(format!("index {index} out of bounds"))) @@ -1395,22 +1403,18 @@ impl DynWinRTValue { let handler_iid = async_info.progress_handler_iid().ok_or_else(|| { PyRuntimeError::new_err("on_progress: cannot compute progress handler IID") })?; - let callback_context = py - .import("contextvars")? - .getattr("copy_context")? - .call0()? - .unbind(); + let callback_for_error = callback.clone_ref(py); + let callback = wrap_python_callback_context(py, callback)?; let progress_cb: dynwinrt::ProgressCallback = Box::new(move |val: dynwinrt::WinRTValue| { Python::attach(|py| { let result = (|| -> PyResult<()> { let py_val = Py::new(py, DynWinRTValue(val))?; - let context = callback_context.call_method0(py, "copy")?; - context.call_method1(py, "run", (callback.clone_ref(py), py_val))?; + callback.call1(py, (py_val,))?; Ok(()) })(); if let Err(error) = result { - error.write_unraisable(py, Some(callback.bind(py))); + error.write_unraisable(py, Some(callback_for_error.bind(py))); } }); }); @@ -2326,10 +2330,14 @@ impl DynWinRtDelegate { // DynWinRtElementFactory — synchronous WinUI IElementFactory binding // ====================================================================== +struct ElementFactoryCallback { + invoke: Py, + error_target: Py, +} + struct ElementFactoryCallbacks { - get_element: Option>, - recycle_element: Option>, - context: Option>, + get_element: Option, + recycle_element: Option, } #[pyclass] @@ -2347,7 +2355,6 @@ impl DynWinRtElementFactory { ( callbacks.get_element.take(), callbacks.recycle_element.take(), - callbacks.context.take(), ) }; drop(released); @@ -2368,43 +2375,40 @@ impl DynWinRtElementFactory { const RO_E_CLOSED: windows::core::HRESULT = windows::core::HRESULT(0x80000013_u32 as i32); let element_iid = element_iid.0; - let context = py - .import("contextvars")? - .getattr("copy_context")? - .call0()? - .unbind(); + let get_element = ElementFactoryCallback { + error_target: get_element.clone_ref(py), + invoke: wrap_python_callback_context(py, get_element)?, + }; + let recycle_element = ElementFactoryCallback { + error_target: recycle_element.clone_ref(py), + invoke: wrap_python_callback_context(py, recycle_element)?, + }; let callbacks = Arc::new(Mutex::new(ElementFactoryCallbacks { get_element: Some(get_element), recycle_element: Some(recycle_element), - context: Some(context), })); let get_callbacks = callbacks.clone(); let get_callback: dynwinrt::ElementFactoryGetCallback = Box::new(move |args| { Python::attach(|py| { - let (callback, context) = { + let (callback, error_target) = { let callbacks = get_callbacks.lock().map_err(|_| E_FAIL)?; - let callback = callbacks - .get_element - .as_ref() - .ok_or(RO_E_CLOSED)? - .clone_ref(py); - let context = callbacks.context.as_ref().ok_or(RO_E_CLOSED)?.clone_ref(py); - (callback, context) + let callback = callbacks.get_element.as_ref().ok_or(RO_E_CLOSED)?; + ( + callback.invoke.clone_ref(py), + callback.error_target.clone_ref(py), + ) }; let result = (|| -> PyResult { let argument = Py::new(py, DynWinRTValue(args.clone()))?; - let context = context.call_method0(py, "copy")?; - let result = context - .bind(py) - .call_method1("run", (callback.clone_ref(py), argument))?; - let value = result.extract::>()?; + let result = callback.call1(py, (argument,))?; + let value = result.extract::>(py)?; value.0.cast(&element_iid).map_err(map_dynwinrt_error) })(); match result { Ok(value) => Ok(value), Err(error) => { - error.write_unraisable(py, Some(callback.bind(py))); + error.write_unraisable(py, Some(error_target.bind(py))); Err(E_FAIL) } } @@ -2414,7 +2418,7 @@ impl DynWinRtElementFactory { let recycle_callbacks = callbacks.clone(); let recycle_callback: dynwinrt::ElementFactoryRecycleCallback = Box::new(move |args| { Python::attach(|py| { - let (callback, context) = { + let (callback, error_target) = { let callbacks = match recycle_callbacks.lock() { Ok(callbacks) => callbacks, Err(_) => return E_FAIL, @@ -2422,23 +2426,20 @@ impl DynWinRtElementFactory { let Some(callback) = callbacks.recycle_element.as_ref() else { return RO_E_CLOSED; }; - let Some(context) = callbacks.context.as_ref() else { - return RO_E_CLOSED; - }; - (callback.clone_ref(py), context.clone_ref(py)) + ( + callback.invoke.clone_ref(py), + callback.error_target.clone_ref(py), + ) }; let result = (|| -> PyResult<()> { let argument = Py::new(py, DynWinRTValue(args.clone()))?; - let context = context.call_method0(py, "copy")?; - context - .bind(py) - .call_method1("run", (callback.clone_ref(py), argument))?; + callback.call1(py, (argument,))?; Ok(()) })(); match result { Ok(()) => windows::core::HRESULT(0), Err(error) => { - error.write_unraisable(py, Some(callback.bind(py))); + error.write_unraisable(py, Some(error_target.bind(py))); E_FAIL } } diff --git a/bindings/py/tests/test_e2e_winrt.py b/bindings/py/tests/test_e2e_winrt.py index e331b437..b9df955b 100644 --- a/bindings/py/tests/test_e2e_winrt.py +++ b/bindings/py/tests/test_e2e_winrt.py @@ -15,8 +15,10 @@ import asyncio from collections.abc import Coroutine +from contextvars import ContextVar import gc import http.server +import sys import threading import time import weakref @@ -29,11 +31,15 @@ DynWinRTValue, DynWinRTArray, DynWinRTStruct, + projected_lifetime_scope, WinGUID, ro_initialize, unbox_object, ) -from dynwinrt.dynwinrt import _DynWinRTAsyncWithProgress +from dynwinrt.dynwinrt import ( + _DynWinRTAsyncWithProgress, + _dynwinrt_track_projected, +) # Initialize WinRT once for the entire module ro_initialize(1) @@ -652,8 +658,59 @@ def test_struct_progress_survives_asyncio_dispatch(self): ), [DynWinRTValue.from_hstring(url)], ) - def create_operation(): - return client_type.method(11).invoke(client.cast(client_iid), [uri]) + def create_operation(target=uri): + return client_type.method(11).invoke(client.cast(client_iid), [target]) + + class GeneratedStyleProjection: + def __init__(self, value): + self._obj = value + _dynwinrt_track_projected(self, "GeneratedStyleProgress") + + raw_progress_threads = [] + progress_marker = ContextVar( + "dynwinrt_test_raw_progress_marker", + default=None, + ) + raw_progress_markers = [] + unraisable = [] + previous_unraisablehook = sys.unraisablehook + owner_thread = threading.get_ident() + marker_token = progress_marker.set("captured") + try: + sys.unraisablehook = unraisable.append + with projected_lifetime_scope(): + raw_uri = uri_factory.method(6).invoke( + DynWinRTValue.activation_factory( + "Windows.Foundation.Uri" + ).cast(uri_factory_iid), + [DynWinRTValue.from_hstring(f"{url}?raw-progress=1")], + ) + raw_operation = create_operation(raw_uri) + + def raw_progress(value): + progress = value.as_struct() + projection = GeneratedStyleProjection( + DynWinRTValue.from_i32(progress.get_i32(0)) + ) + assert not projection._obj.is_null() + raw_progress_threads.append(threading.get_ident()) + raw_progress_markers.append(progress_marker.get()) + + raw_operation.on_progress(raw_progress) + raw_result = raw_operation.wait() + raw_body = raw_result.to_string() + raw_result.release() + raw_operation.release() + raw_uri.release() + finally: + progress_marker.reset(marker_token) + sys.unraisablehook = previous_unraisablehook + + assert raw_body == payload + assert raw_progress_threads + assert all(thread != owner_thread for thread in raw_progress_threads) + assert all(marker == "captured" for marker in raw_progress_markers) + assert not unraisable operation = create_operation() diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index 3a8328a1..1a57ef06 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -20,6 +20,7 @@ from datetime import datetime, timedelta, timezone import gc import inspect +import sys import threading import warnings import weakref @@ -698,6 +699,128 @@ def test_com_identity_and_element_factory_callback_release(): factory.release() +def test_element_factory_callbacks_mask_parent_scope_on_foreign_thread(): + element_factory_iid = WinGUID.parse( + "75FABA47-2CF2-54AE-91E6-0581556FDDAA" + ) + element_factory_type = DynWinRTType.register_interface( + "IElementFactoryThreadAffinityTest", + element_factory_iid, + ) + element_factory_type = element_factory_type.add_method( + "GetElement", + DynWinRTMethodSig() + .add_in(DynWinRTType.object()) + .add_out(DynWinRTType.object()), + ) + element_factory_type = element_factory_type.add_method( + "RecycleElement", + DynWinRTMethodSig().add_in(DynWinRTType.object()), + ) + get_element = element_factory_type.method(6) + recycle_element = element_factory_type.method(7) + Wrapper = _projected_wrapper_type("ElementFactoryThreadWrapper") + marker = ContextVar("dynwinrt_test_element_factory_marker", default=None) + parent_release_threads = [] + retained = [] + callback_state = {} + worker_errors = [] + unraisable = [] + owner_thread = threading.get_ident() + previous_unraisablehook = sys.unraisablehook + marker_token = marker.set("captured") + + class ParentNative: + def release(self): + parent_release_threads.append(threading.get_ident()) + + try: + sys.unraisablehook = unraisable.append + with RoApartment(1), projected_lifetime_scope() as parent_scope: + parent_scope.track(SimpleNamespace(_obj=ParentNative()), "Parent") + uri_activation = DynWinRTValue.activation_factory( + "Windows.Foundation.Uri" + ) + uri_factory = uri_activation.cast(WinGUID.parse(IID_IURI_FACTORY)) + uri_factory_type = DynWinRTType.register_interface( + "IUriRuntimeClassFactoryElementFactoryThreadTest", + WinGUID.parse(IID_IURI_FACTORY), + ).add_method( + "CreateUri", + DynWinRTMethodSig() + .add_in(DynWinRTType.hstring()) + .add_out(DynWinRTType.object()), + ) + uri = uri_factory_type.method(6).invoke( + uri_factory, + [DynWinRTValue.from_hstring("https://example.com/")], + ) + + def get_callback(value): + callback_state["get"] = ( + threading.get_ident(), + marker.get(), + ) + retained.append(Wrapper._from_native(value)) + return uri.cast(WinGUID.parse(IID_IURI)) + + def recycle_callback(value): + callback_state["recycle"] = ( + threading.get_ident(), + marker.get(), + ) + retained.append(Wrapper._from_native(value)) + + implementation = DynWinRtElementFactory.create( + WinGUID.parse(IID_IURI), + get_callback, + recycle_callback, + ) + factory_value = implementation.to_value() + factory_interface = factory_value.cast(element_factory_iid) + + def worker(): + try: + with RoApartment(1): + with pytest.raises(OSError): + get_element.invoke( + factory_interface, + [factory_value], + ) + recycle_element.invoke(factory_interface, [uri]) + except BaseException as error: + worker_errors.append(error) + + thread = threading.Thread(target=worker) + thread.start() + thread.join() + + assert not worker_errors + assert not unraisable + assert callback_state["get"][0] != owner_thread + assert callback_state["recycle"][0] != owner_thread + assert callback_state["get"][1] == "captured" + assert callback_state["recycle"][1] == "captured" + assert all(not wrapper._obj.is_null() for wrapper in retained) + assert parent_release_threads == [] + + assert parent_release_threads == [owner_thread] + assert all(not wrapper._obj.is_null() for wrapper in retained) + for wrapper in retained: + release_projected(wrapper) + assert wrapper._obj.is_null() + + implementation.release() + factory_interface.release() + factory_value.release() + uri.release() + uri_factory.release() + uri_activation.release() + finally: + marker.reset(marker_token) + sys.unraisablehook = previous_unraisablehook + + def test_projected_identity_cache_reuses_live_wrappers_and_skips_released_ones(): Wrapper = _projected_wrapper_type("IdentityWrapper")