From f8467dbdf9ebe7993ee0836a171f5f4b1aa8031a Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Thu, 29 Oct 2026 21:17:42 +0800 Subject: [PATCH 1/4] Add Python AsyncEventScope for same-thread notifications Compose TaskGroup with existing event subscriptions, preserve typed handlers and native lifetimes, and cover installed wheels and real PropertySet notifications. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/README.md | 84 +++ bindings/py/dynwinrt.pyi | 22 +- bindings/py/python/dynwinrt/__init__.py | 3 +- bindings/py/python/dynwinrt/_events.py | 137 +++++ bindings/py/tests/test_async_event_scope.py | 532 ++++++++++++++++++ bindings/py/tests/test_async_event_typing.py | 67 +++ bindings/py/tests/test_typing_package.py | 10 + .../python/test_python_runtime_wheel.ps1 | 12 +- samples/python/README.md | 3 +- samples/python/async-events/.gitignore | 2 + samples/python/async-events/README.md | 27 + samples/python/async-events/app.py | 59 ++ tests/e2e/runners/py_async_events.py | 300 ++++++++++ tests/e2e/runners/py_runner.py | 16 + tests/e2e/typecheck/python_generated_api.py | 24 + 15 files changed, 1294 insertions(+), 4 deletions(-) create mode 100644 bindings/py/python/dynwinrt/_events.py create mode 100644 bindings/py/tests/test_async_event_scope.py create mode 100644 bindings/py/tests/test_async_event_typing.py create mode 100644 samples/python/async-events/.gitignore create mode 100644 samples/python/async-events/README.md create mode 100644 samples/python/async-events/app.py create mode 100644 tests/e2e/runners/py_async_events.py diff --git a/bindings/py/README.md b/bindings/py/README.md index 69e72aba..cbf328c1 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -283,6 +283,90 @@ def changed(sender: IObservableMap_String_Object, args: IMapChangedEventArgs_Str unsubscribe = properties.subscribe_map_changed(changed) ``` +### Async notification handlers + +Use the public `AsyncEventScope` to attach an async handler to an existing +`subscribe_*` method: + +```python +import asyncio +from dynwinrt import AsyncEventScope, RoApartment, projected_lifetime_scope +from generated.windows.foundation.collections import ( + IMapChangedEventArgs_String, IObservableMap_String_Object, PropertySet, +) + +async def on_changed( + sender: IObservableMap_String_Object, args: IMapChangedEventArgs_String, +) -> None: + await asyncio.sleep(0) + print(args.key, len(sender)) + +async def main() -> None: + with RoApartment(), projected_lifetime_scope(): + properties = PropertySet() + async with AsyncEventScope(loop=asyncio.get_running_loop()) as events: + unsubscribe = events.subscribe(properties.subscribe_map_changed, on_changed) + properties["first"] = None + unsubscribe() # Stop future notifications; the accepted task still runs. + properties["not-delivered"] = None + # Subscriptions are removed and all accepted tasks have finished here. + # Only now may the projection scope and COM apartment close. + +asyncio.run(main()) +``` + +The [async-events sample](../../samples/python/async-events/) runs real +`PropertySet.MapChanged` notifications and native asynchronous file I/O, +including an optional handler-failure path. + +`AsyncEventScope` composes `asyncio.TaskGroup`: normal exit first stops +accepting notifications and removes subscriptions, then **waits for accepted +tasks without cancelling them**. A handler failure or exception in the body +cancels siblings and waits for their `finally` blocks before propagating the +standard task-group exception; external cancellation also waits for cleanup. +A handler's own `CancelledError` has the standard TaskGroup meaning, not an +instruction to cancel all siblings. Handlers run concurrently; completion +order is not guaranteed, and there is no backpressure, throttling or retry +policy. Handlers must cooperate with cancellation. + +The returned unsubscribe callable is idempotent after successful removal and +does not cancel accepted tasks. A native removal failure is raised to its +caller, leaves delivery disabled, and can be retried with the same callable +on the owner loop/thread while native owners are still live. Scope exit +attempts **every** remaining removal in reverse registration order. Removal +failures (and any body exception) are preserved in an exception group passed +to TaskGroup, cancelling outstanding work rather than hanging in a normal +drain. Save unsubscribe callables if your application needs to recover from +native removal failures; recovery must happen before closing native lifetimes. + +The scope is single-use and must exit in the task that entered it. Its +constructor binds it to the creating OS thread; entry, subscription, callbacks, +task execution, and unsubscription require that thread and the supplied +**actually running** loop. Keep the outer `RoApartment` and any captured +`projected_lifetime_scope()` alive through task cleanup. Existing subscription +context-variable and projection-lifetime behavior is preserved, not bypassed. +Wrong-thread delivery fails through the existing synchronous native callback +error path (`sys.unraisablehook` and a failing delegate HRESULT); the event +source decides whether that HRESULT fails the originating invocation. No +native arguments are marshalled or queued to another thread. Registration and +task-creation failures likewise remain synchronous callback/subscription errors. + +This is only for ordinary same-thread notifications whose work may be deferred. +The application must drive asyncio: the scope does not create a loop, start a +thread, integrate a WinUI message pump, or make a blocking `Application.start()` +advance asyncio. It does not implement synchronous return values, `Handled`, +`Cancel`, or deferral semantics, and is not a general async adapter for WinUI +buttons or all Windows events. With an eager task factory, a handler may start +before the native callback returns, including during subscription. +Native reentrancy restrictions still apply: for example, yield before mutating +the same `PropertySet` from its handler when using an eager factory. + +The handler may be an `async def` or a callable returning an awaitable; it is +called inside an owned task and its result is awaited. Passing a bare +`async def` directly to the old `subscribe_*` API instead merely creates an +unawaited coroutine. Existing synchronous callbacks, native delegates, and +synchronous callbacks returning an already TaskGroup-owned task are unchanged. + Async-operation arguments deliberately stay raw. A work item can inspect its `IAsyncInfo` status without installing another completion handler: diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index c6627b6d..04bcdba6 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -1,7 +1,9 @@ +from asyncio import AbstractEventLoop from collections.abc import Coroutine from datetime import datetime, timedelta from os import PathLike -from typing import Any, Awaitable, Callable, Final, Generic, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload +from types import TracebackType +from typing import Any, Awaitable, Callable, Final, Generic, List, Literal, Mapping, Optional, ParamSpec, Protocol, Sequence, TypeVar, Union, final, overload from uuid import UUID _T = TypeVar("_T", covariant=True) @@ -10,6 +12,7 @@ _Tracked = TypeVar("_Tracked") _Projected_co = TypeVar("_Projected_co", covariant=True) _ProjectableClass = TypeVar("_ProjectableClass", bound="_DynWinRTProjectableClass") _Handlers_contra = TypeVar("_Handlers_contra", contravariant=True) +_EventArgs = ParamSpec("_EventArgs") class _DynWinRTProjector(Protocol[_Projected_co]): @@ -24,6 +27,7 @@ class _DynWinRTRuntimeClass(_DynWinRTProjectableClass): ... __all__ = [ + "AsyncEventScope", "WinAppSDKContext", "RoApartment", "RO_INIT_SINGLETHREADED", @@ -66,6 +70,22 @@ __all__ = [ "get_computer_name", ] +@final +class AsyncEventScope: + def __init__(self, *, loop: AbstractEventLoop) -> None: ... + async def __aenter__(self) -> AsyncEventScope: ... + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: ... + def subscribe( + self, + subscribe: Callable[[Callable[_EventArgs, object]], Callable[[], None]], + handler: Callable[_EventArgs, Awaitable[object]], + ) -> Callable[[], None]: ... + @final class WinAppSDKContext: def resource_pri_path(self) -> str: ... diff --git a/bindings/py/python/dynwinrt/__init__.py b/bindings/py/python/dynwinrt/__init__.py index 4330b92f..6c119c26 100644 --- a/bindings/py/python/dynwinrt/__init__.py +++ b/bindings/py/python/dynwinrt/__init__.py @@ -4,7 +4,8 @@ from . import dynwinrt as dynwinrt from .dynwinrt import * from . import values as values +from ._events import AsyncEventScope as AsyncEventScope from ._winappsdk import init_winappsdk as init_winappsdk __doc__ = dynwinrt.__doc__ -__all__ = dynwinrt.__all__ +__all__ = [*dynwinrt.__all__, "AsyncEventScope"] diff --git a/bindings/py/python/dynwinrt/_events.py b/bindings/py/python/dynwinrt/_events.py new file mode 100644 index 00000000..a684e811 --- /dev/null +++ b/bindings/py/python/dynwinrt/_events.py @@ -0,0 +1,137 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Structured concurrency for same-thread, asynchronous notification handlers.""" + +from __future__ import annotations + +import asyncio as _asyncio +import threading as _threading +from collections.abc import Awaitable as _Awaitable, Callable as _Callable +from types import TracebackType as _TracebackType +from typing import ParamSpec as _ParamSpec, final as _final + +_Args = _ParamSpec("_Args") + + +@_final +class AsyncEventScope: + """Own notification subscriptions and their concurrent TaskGroup tasks. + + The application must drive ``loop`` on the creating OS thread and keep its + COM apartment and projected lifetimes alive until this context has exited. + Only ordinary notifications that may be handled later are supported. + """ + + def __init__(self, *, loop: _asyncio.AbstractEventLoop) -> None: + self._loop = loop + self._thread = _threading.current_thread() + self._group = _asyncio.TaskGroup() + self._state = "new" + self._owner_task: _asyncio.Task[object] | None = None + self._subscriptions: list[_Callable[[], None]] = [] + + def _check_owner(self) -> None: + if _threading.current_thread() is not self._thread: + raise RuntimeError("AsyncEventScope requires its owner OS thread") + if _asyncio.get_running_loop() is not self._loop: + raise RuntimeError("AsyncEventScope requires its running asyncio loop") + + async def __aenter__(self) -> AsyncEventScope: + self._check_owner() + if self._state != "new": + raise RuntimeError("AsyncEventScope cannot be re-entered or reused") + await self._group.__aenter__() + self._owner_task = _asyncio.current_task() + self._state = "active" + return self + + def subscribe( + self, + subscribe: _Callable[[_Callable[_Args, object]], _Callable[[], None]], + handler: _Callable[_Args, _Awaitable[object]], + ) -> _Callable[[], None]: + """Register a handler; return a retryable, idempotent unsubscribe. + + Unsubscribing stops new deliveries before attempting native removal. + Already accepted tasks remain owned by the scope, even if removal fails. + The handler is called inside a group task and its result is awaited. + """ + self._check_owner() + if self._state != "active": + raise RuntimeError("AsyncEventScope is not accepting subscriptions") + if not callable(subscribe) or not callable(handler): + raise TypeError("subscribe and handler must be callable") + accepting = True + removing = False + remove: _Callable[[], None] | None = None + + async def invoke(*args: _Args.args, **kwargs: _Args.kwargs) -> None: + self._check_owner() + await handler(*args, **kwargs) + + def callback(*args: _Args.args, **kwargs: _Args.kwargs) -> None: + self._check_owner() + if not accepting or self._state != "active": + return + coroutine = invoke(*args, **kwargs) + try: + self._group.create_task(coroutine) + except BaseException: + # TaskGroup only closes rejected coroutines on Python 3.13+. + coroutine.close() + raise + + def unsubscribe() -> None: + nonlocal accepting, removing, remove + self._check_owner() + accepting = False + if remove is None or removing: + return + removing = True + try: + remove() + remove = None + self._subscriptions.remove(unsubscribe) + finally: + removing = False + + try: + remove = subscribe(callback) + if not callable(remove): + raise TypeError("subscribe must return an unsubscribe callable") + except BaseException: + accepting = False + raise + self._subscriptions.append(unsubscribe) + return unsubscribe + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: _TracebackType | None, + ) -> None: + self._check_owner() + if self._state != "active": + raise RuntimeError("AsyncEventScope is not active") + if _asyncio.current_task() is not self._owner_task: + raise RuntimeError("AsyncEventScope must exit in the task that entered it") + self._state = "closing" + errors: list[BaseException] = [] + for unsubscribe in reversed(self._subscriptions.copy()): + try: + unsubscribe() + except BaseException as error: + errors.append(error) + if errors: + if exc_value is not None: + errors.insert(0, exc_value) + exc_value = BaseExceptionGroup("AsyncEventScope unsubscribe failed", errors) + exc_type = type(exc_value) + traceback = exc_value.__traceback__ + try: + await self._group.__aexit__(exc_type, exc_value, traceback) + finally: + self._state = "closed" + self._owner_task = None diff --git a/bindings/py/tests/test_async_event_scope.py b/bindings/py/tests/test_async_event_scope.py new file mode 100644 index 00000000..2ed43204 --- /dev/null +++ b/bindings/py/tests/test_async_event_scope.py @@ -0,0 +1,532 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import asyncio +from contextvars import ContextVar +import gc +import threading +import weakref + +import pytest + +from dynwinrt import AsyncEventScope + + +class Notification: + def __init__(self, *, during_registration=False, failures=0): + self.callback = None + self.during_registration = during_registration + self.failures = failures + self.removals = 0 + self.removing = lambda: None + + def subscribe(self, callback): + self.callback = callback + if self.during_registration: + self.emit(0) + + def remove(): + self.removals += 1 + self.removing() + if self.failures: + self.failures -= 1 + raise OSError("native removal failed") + self.callback = None + + return remove + + def emit(self, value): + if self.callback is not None: + return self.callback(value) + + +def leaves(error): + if isinstance(error, BaseExceptionGroup): + return [leaf for child in error.exceptions for leaf in leaves(child)] + return [error] + + +@pytest.fixture(params=["default", "eager"]) +def task_factory(request): + if request.param == "eager" and not hasattr(asyncio, "eager_task_factory"): + pytest.skip("eager task factories require Python 3.12") + return getattr(asyncio, "eager_task_factory", None) if request.param == "eager" else None + + +def run_with_factory(coroutine, factory): + async def run(): + loop = asyncio.get_running_loop() + previous = loop.get_task_factory() + loop.set_task_factory(factory) + try: + return await coroutine + finally: + loop.set_task_factory(previous) + + return asyncio.run(run()) + + +def test_normal_exit_unsubscribes_then_drains_accepted_tasks(task_factory): + async def run(): + event = Notification(during_registration=True) + finished = [] + + async def changed(value): + await asyncio.sleep(0) + assert event.callback is None + finished.append(value) + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + stop = scope.subscribe(event.subscribe, changed) + event.emit(1) + stop() + stop() + event.emit(2) + assert finished == [] + assert sorted(finished) == [0, 1] + assert event.removals == 1 + stop() + + run_with_factory(run(), task_factory) + + +@pytest.mark.parametrize("after_await", [False, True]) +def test_handler_failure_cancels_siblings_and_waits_for_finally(task_factory, after_await): + async def run(): + event = Notification() + started = asyncio.Event() + finished = [] + + async def changed(value): + if value == 0: + try: + started.set() + await asyncio.Event().wait() + finally: + await asyncio.sleep(0) + finished.append("finally") + else: + if after_await: + await asyncio.sleep(0) + raise ValueError("handler failed") + + with pytest.raises(ExceptionGroup) as failure: + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + scope.subscribe(event.subscribe, changed) + event.emit(0) + await started.wait() + event.emit(1) + await asyncio.Event().wait() + assert [str(error) for error in leaves(failure.value)] == ["handler failed"] + assert finished == ["finally"] + assert event.removals == 1 + + run_with_factory(run(), task_factory) + + +@pytest.mark.parametrize("cancel_during_exit", [False, True]) +def test_external_cancel_waits_for_finally(task_factory, cancel_during_exit): + async def run(): + event = Notification() + started = asyncio.Event() + finished = [] + + async def changed(value): + try: + started.set() + await asyncio.Event().wait() + finally: + await asyncio.sleep(0) + finished.append(value) + + async def parent(): + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + scope.subscribe(event.subscribe, changed) + event.emit(1) + if not cancel_during_exit: + await asyncio.Event().wait() + + task = asyncio.create_task(parent()) + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert finished == [1] + assert event.removals == 1 + + run_with_factory(run(), task_factory) + + +def test_concurrent_handlers_can_reenter_notification_source(task_factory): + async def run(): + event = Notification() + reentered = asyncio.Event() + done = [] + + async def changed(value): + if value == 0: + event.emit(1) + await reentered.wait() + else: + reentered.set() + done.append(value) + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + scope.subscribe(event.subscribe, changed) + event.emit(0) + await reentered.wait() + assert done == [1, 0] + + run_with_factory(run(), task_factory) + + +def test_contextvars_are_inherited_without_clearing_projection_context(task_factory): + marker = ContextVar("marker") + + async def run(): + event = Notification() + observed = [] + + async def changed(value): + await asyncio.sleep(0) + observed.append(marker.get()) + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + scope.subscribe(event.subscribe, changed) + marker.set("delivery") + event.emit(1) + marker.set("parent changed") + assert observed == ["delivery"] + + run_with_factory(run(), task_factory) + + +def test_awaitable_callable_and_keyword_parameters(task_factory): + async def run(): + callbacks = [] + results = [] + + def subscribe(callback): + callbacks.append(callback) + return callbacks.clear + + class Handler: + def __call__(self, sender, *, value): + async def work(): + await asyncio.sleep(0) + results.append((sender, value)) + return work() + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + scope.subscribe(subscribe, Handler()) + callbacks[0]("sender", value=42) + assert results == [("sender", 42)] + + run_with_factory(run(), task_factory) + + +def test_sync_handler_result_failure_belongs_to_taskgroup(): + async def run(): + event = Notification() + with pytest.raises(ExceptionGroup) as failure: + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + scope.subscribe(event.subscribe, lambda value: None) + event.emit(0) + assert isinstance(leaves(failure.value)[0], TypeError) + assert event.removals == 1 + + asyncio.run(run()) + + +def test_failed_manual_unsubscribe_stays_stopped_and_is_retryable(task_factory): + async def run(): + event = Notification(failures=1) + received = [] + + async def changed(value): + received.append(value) + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + stop = scope.subscribe(event.subscribe, changed) + event.emit(1) + event.removing = lambda: (stop(), event.emit(2)) + with pytest.raises(OSError, match="native removal"): + stop() + event.emit(3) + stop() + stop() + assert received == [1] + assert event.removals == 2 + + run_with_factory(run(), task_factory) + + +@pytest.mark.parametrize("body_error", [None, ValueError("body"), asyncio.CancelledError()]) +def test_exit_attempts_all_removals_and_preserves_errors_for_retry(body_error): + async def run(): + events = [Notification(failures=1), Notification(), Notification(failures=1)] + stops = [] + + async def changed(value): + await asyncio.sleep(0) + + with pytest.raises(BaseExceptionGroup) as failure: + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + stops.extend(scope.subscribe(event.subscribe, changed) for event in events) + if body_error: + raise body_error + errors = leaves(failure.value) + assert sum(isinstance(error, OSError) for error in errors) == 2 + if body_error: + assert body_error in errors + assert [event.removals for event in events] == [1, 1, 1] + for event, stop in zip(events, stops): + event.emit(1) + stop() + stop() + assert event.callback is None + + asyncio.run(run()) + + +def test_cleanup_error_cancels_tasks_instead_of_hanging(): + async def run(): + event = Notification(failures=1) + started = asyncio.Event() + finished = [] + + async def changed(value): + try: + started.set() + await asyncio.Event().wait() + finally: + await asyncio.sleep(0) + finished.append(value) + + with pytest.raises(ExceptionGroup): + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + stop = scope.subscribe(event.subscribe, changed) + event.emit(1) + await started.wait() + assert finished == [1] + stop() + + asyncio.run(run()) + + +def test_registration_failure_disables_its_callback_and_drains_accepted_work(): + async def run(): + received = [] + callbacks = [] + + async def changed(value): + received.append(value) + + def subscribe(callback): + callbacks.append(callback) + callback(1) + raise OSError("registration failed") + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + with pytest.raises(OSError, match="registration failed"): + scope.subscribe(subscribe, changed) + callbacks[0](2) + assert received == [1] + + asyncio.run(run()) + + +def test_invalid_scope_lifecycle_and_wrong_exit_task(): + async def run(): + scope = AsyncEventScope(loop=asyncio.get_running_loop()) + event = Notification() + + async def changed(value): + pass + + with pytest.raises(RuntimeError, match="not accepting"): + scope.subscribe(event.subscribe, changed) + with pytest.raises(RuntimeError, match="not active"): + await scope.__aexit__(None, None, None) + async with scope: + with pytest.raises(RuntimeError, match="re-entered"): + await scope.__aenter__() + with pytest.raises(RuntimeError, match="task that entered"): + await asyncio.create_task(scope.__aexit__(None, None, None)) + with pytest.raises(TypeError, match="must be callable"): + scope.subscribe(event.subscribe, None) + with pytest.raises(TypeError, match="unsubscribe callable"): + scope.subscribe(lambda callback: None, changed) + with pytest.raises(RuntimeError, match="re-entered"): + await scope.__aenter__() + with pytest.raises(RuntimeError, match="not accepting"): + scope.subscribe(event.subscribe, changed) + + asyncio.run(run()) + + +def test_wrong_loop_and_no_running_loop_fail_before_registration(): + loop = asyncio.new_event_loop() + scope = AsyncEventScope(loop=loop) + with pytest.raises(RuntimeError, match="no running event loop"): + scope.subscribe(lambda callback: lambda: None, lambda: None) + + async def run(): + with pytest.raises(RuntimeError, match="running asyncio loop"): + await scope.__aenter__() + + asyncio.run(run()) + loop.close() + asyncio.run(run()) + + +def test_wrong_thread_entry_subscription_callback_unsubscribe_and_exit(): + async def run(): + event = Notification() + + async def changed(value): + raise AssertionError("wrong-thread delivery was accepted") + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + stop = scope.subscribe(event.subscribe, changed) + errors = [] + + def foreign(): + for action in ( + lambda: asyncio.run(scope.__aenter__()), + lambda: scope.subscribe(event.subscribe, changed), + lambda: event.emit(1), + stop, + lambda: asyncio.run(scope.__aexit__(None, None, None)), + ): + try: + action() + except RuntimeError as error: + errors.append(str(error)) + + thread = threading.Thread(target=foreign) + thread.start() + thread.join(5) + assert not thread.is_alive() + assert len(errors) == 5 + assert all("owner OS thread" in message for message in errors) + assert event.removals == 0 + + asyncio.run(run()) + + +def test_task_creation_failure_closes_coroutine_without_calling_handler(): + async def run(): + loop = asyncio.get_running_loop() + event = Notification() + captured = [] + calls = [] + + def fail_factory(loop, coroutine, **kwargs): + captured.append(coroutine) + raise RuntimeError("factory failed") + + async def changed(value): + calls.append(value) + + async with AsyncEventScope(loop=loop) as scope: + scope.subscribe(event.subscribe, changed) + loop.set_task_factory(fail_factory) + try: + with pytest.raises(RuntimeError, match="factory failed"): + event.emit(1) + finally: + loop.set_task_factory(None) + assert len(captured) == 1 and captured[0].cr_frame is None + assert calls == [] + + asyncio.run(run()) + + +def test_stopped_loop_does_not_run_handlers_until_application_resumes_it(): + loop = asyncio.new_event_loop() + event = Notification() + received = [] + entered = loop.create_future() + finish = loop.create_future() + + async def changed(value): + received.append(value) + + async def run(): + async with AsyncEventScope(loop=loop) as scope: + scope.subscribe(event.subscribe, changed) + entered.set_result(None) + await finish + + try: + task = loop.create_task(run()) + loop.run_until_complete(entered) + with pytest.raises(RuntimeError, match="no running event loop"): + event.emit(0) + assert received == [] + loop.call_soon(event.emit, 1) + loop.call_soon(finish.set_result, None) + loop.run_until_complete(task) + assert received == [1] + finally: + loop.close() + + +def test_handler_execution_rejects_loop_moved_to_another_os_thread(): + loop = asyncio.new_event_loop() + event = Notification() + received = [] + + async def changed(value): + received.append(value) + + async def run(): + async with AsyncEventScope(loop=loop) as scope: + scope.subscribe(event.subscribe, changed) + event.emit(1) + await asyncio.Event().wait() + + def foreign(): + loop.call_soon(loop.stop) + loop.run_forever() + + try: + # Stop immediately after scheduling the handler, before it can run. + task = loop.create_task(run()) + loop.call_soon(loop.stop) + loop.run_forever() + thread = threading.Thread(target=foreign) + thread.start() + thread.join(5) + assert not thread.is_alive() + assert received == [] + with pytest.raises(ExceptionGroup) as failure: + loop.run_until_complete(task) + assert "owner OS thread" in str(leaves(failure.value)[0]) + assert event.callback is None + finally: + loop.close() + + +def test_completed_scope_does_not_retain_handler_arguments(): + class Value: + pass + + async def run(): + event = Notification() + value = Value() + reference = weakref.ref(value) + + async def changed(arg): + await asyncio.sleep(0) + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + scope.subscribe(event.subscribe, changed) + event.emit(value) + del value + assert reference() is not None + gc.collect() + assert reference() is None + + asyncio.run(run()) diff --git a/bindings/py/tests/test_async_event_typing.py b/bindings/py/tests/test_async_event_typing.py new file mode 100644 index 00000000..b8507c40 --- /dev/null +++ b/bindings/py/tests/test_async_event_typing.py @@ -0,0 +1,67 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import subprocess +import sys + +import pytest + + +SOURCE = """ +import asyncio +from collections.abc import Awaitable, Callable +from dynwinrt import AsyncEventScope + +class Sender: + size: int + +class Args: + key: str + +def subscribe(callback: Callable[[Sender, Args], object]) -> Callable[[], None]: + return lambda: None + +async def changed(sender: Sender, args: Args) -> None: + await asyncio.sleep(0) + size: int = sender.size + key: str = args.key + +def awaitable_handler(sender: Sender, args: Args) -> Awaitable[None]: + return changed(sender, args) + +async def wrong_sender(sender: str, args: Args) -> None: + pass + +async def wrong_args(sender: Sender, args: int) -> None: + pass + +async def wrong_arity(sender: Sender) -> None: + pass + +def synchronous(sender: Sender, args: Args) -> None: + pass + +async def run() -> None: + async with AsyncEventScope(loop=asyncio.get_running_loop()) as events: + stop: Callable[[], None] = events.subscribe(subscribe, HANDLER) + stop() +""" + + +@pytest.mark.parametrize( + "handler", ["changed", "awaitable_handler", "wrong_sender", "wrong_args", "wrong_arity", "synchronous"], +) +def test_installed_scope_preserves_handler_parameter_and_return_types(tmp_path, handler): + consumer = tmp_path / "consumer.py" + consumer.write_text(SOURCE.replace("HANDLER", handler), encoding="utf-8") + result = subprocess.run( + [sys.executable, "-m", "mypy", "--strict", "--no-incremental", + "--cache-dir", str(tmp_path / "cache"), str(consumer)], + capture_output=True, text=True, timeout=60, + ) + if handler in ("changed", "awaitable_handler"): + assert result.returncode == 0, result.stdout + result.stderr + else: + assert result.returncode == 1, result.stdout + result.stderr + assert result.stdout.count("error:") == 1, result.stdout + assert "[arg-type]" in result.stdout, result.stdout diff --git a/bindings/py/tests/test_typing_package.py b/bindings/py/tests/test_typing_package.py index 93674704..aafc8761 100644 --- a/bindings/py/tests/test_typing_package.py +++ b/bindings/py/tests/test_typing_package.py @@ -14,6 +14,16 @@ def test_wheel_contains_typing_metadata(): assert (package_dir / "py.typed").is_file() +def test_wheel_exports_async_event_scope_without_changing_native_exports(): + stub = (Path(dynwinrt.__file__).parent / "__init__.pyi").read_text(encoding="utf-8") + assert "class AsyncEventScope:" in stub + assert "AsyncEventScope" in dynwinrt.__all__ + assert "AsyncEventScope" not in dynwinrt.dynwinrt.__all__ + assert inspect.signature(dynwinrt.AsyncEventScope).parameters["loop"].kind == ( + inspect.Parameter.KEYWORD_ONLY + ) + + def test_wheel_exports_typed_implementation_surface(): stub = (Path(dynwinrt.__file__).parent / "__init__.pyi").read_text(encoding="utf-8") for name in ( diff --git a/eng/release/python/test_python_runtime_wheel.ps1 b/eng/release/python/test_python_runtime_wheel.ps1 index cce05d8c..7daee098 100644 --- a/eng/release/python/test_python_runtime_wheel.ps1 +++ b/eng/release/python/test_python_runtime_wheel.ps1 @@ -26,6 +26,10 @@ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } & $venvPython -m pip install --disable-pip-version-check --no-index ` --find-links $CodegenWheelDirectory "dynwinrt-codegen==$Version" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +& $venvPython -m pip install --disable-pip-version-check "pytest>=8.3.5" --quiet +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +& $venvPython -m pytest (Join-Path $repoRoot 'bindings\py\tests\test_async_event_scope.py') -q +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $native = @(Get-ChildItem (Join-Path $root 'venv\Lib\site-packages\dynwinrt') -Filter *.pyd -File) if ($native.Count -ne 1) { throw 'Expected exactly one installed production Python extension' } @@ -38,7 +42,8 @@ $env:PATH = "$scripts;$env:SystemRoot\System32;$env:SystemRoot" $env:PYTHONPATH = '' $codegen = Join-Path $scripts 'dynwinrt-codegen.exe' $generated = Join-Path $root 'generated_uri' -& $codegen generate --namespace Windows.Foundation --class-name Uri ` +& $codegen generate ` + --class-name "Windows.Foundation.Uri,Windows.Foundation.Collections.PropertySet,Windows.Storage.StorageFolder" ` --lang py --output $generated if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } @@ -73,6 +78,11 @@ Push-Location $root try { & $venvPython -c $test $Architecture $PythonMinor $PythonPackageVersion if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + foreach ($mode in @(0, 1)) { + & $venvPython -I (Join-Path $repoRoot 'tests\e2e\runners\py_async_events.py') ` + --generated $generated --mode $mode + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } } finally { Pop-Location } diff --git a/samples/python/README.md b/samples/python/README.md index 58d9fafe..669d724c 100644 --- a/samples/python/README.md +++ b/samples/python/README.md @@ -2,11 +2,12 @@ All Python samples use generated bindings and an installed `dynwinrt` runtime. Install `dynwinrt` and `dynwinrt-codegen` from PyPI, or build both from this -checkout, then run each sample's `generate.ps1` before `run.ps1`. +checkout, then follow the sample's README (usually `generate.ps1` before `run.ps1`). | Sample | Demonstrates | | --- | --- | | [`async-file-io`](async-file-io/) | Temporary files, storage interfaces, and native `asyncio` | +| [`async-events`](async-events/) | Same-thread notifications, TaskGroup cleanup, and native async file I/O | | [`ocr-image`](ocr-image/) | Self-contained image creation, bitmap decoding, and Windows OCR | | [`app-lifecycle-single-instance`](app-lifecycle-single-instance/) | Multi-process activation redirection with Windows App SDK AppLifecycle | | [`cryptography`](cryptography/) | SHA-256, `IBuffer`, text encoding, and hex conversion | diff --git a/samples/python/async-events/.gitignore b/samples/python/async-events/.gitignore new file mode 100644 index 00000000..8b84a8c0 --- /dev/null +++ b/samples/python/async-events/.gitignore @@ -0,0 +1,2 @@ +generated/ +__pycache__/ diff --git a/samples/python/async-events/README.md b/samples/python/async-events/README.md new file mode 100644 index 00000000..179cfc0a --- /dev/null +++ b/samples/python/async-events/README.md @@ -0,0 +1,27 @@ +# Async notification scope + +Requires Windows 10/11, CPython 3.11-3.14, a Windows SDK, and a `dynwinrt` +runtime build containing `AsyncEventScope`. No WinUI, package identity, +network, or Windows App SDK is needed. + +From this directory, with `dynwinrt-codegen` on PATH and the matching runtime +installed in your Python environment: + +```powershell +dynwinrt-codegen generate --class-name "Windows.Foundation.Collections.PropertySet,Windows.Storage.StorageFolder,Windows.Storage.FileIO" --lang py --output .\generated +python .\app.py +python .\app.py --fail +``` + +The application owns the asyncio loop. Inside its COM apartment and projection +scope, it registers an async `PropertySet.MapChanged` handler, mutates the map +on that same thread, and unsubscribes immediately. The accepted handler still +finishes its native asynchronous temporary-file I/O before the event scope +exits; later notifications are ignored. `--fail` demonstrates a handler error +reaching the enclosing `except*` only after task cleanup. + +This is a concurrent TaskGroup adapter for notifications that allow deferred +work, not a WinUI pump, cross-thread COM bridge, or deferral implementation. +Keep native lifetimes outside the event scope. A custom eager task factory can +start a handler during the native callback; no completion ordering or +backpressure policy is provided. See the [runtime contract](../../../bindings/py/README.md#async-notification-handlers). diff --git a/samples/python/async-events/app.py b/samples/python/async-events/app.py new file mode 100644 index 00000000..0944a6c9 --- /dev/null +++ b/samples/python/async-events/app.py @@ -0,0 +1,59 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import argparse +import asyncio +import tempfile + +from dynwinrt import AsyncEventScope, RoApartment, projected_lifetime_scope +from generated.windows.foundation.collections import ( + IMapChangedEventArgs_String, + IObservableMap_String_Object, + PropertySet, +) +from generated.windows.storage import FileIO, StorageFolder + + +async def run(*, fail: bool = False) -> None: + with tempfile.TemporaryDirectory(prefix="dynwinrt-events-") as directory: + with RoApartment(), projected_lifetime_scope(): + folder = await StorageFolder.get_folder_from_path_async(directory) + properties = PropertySet() + completed: list[str] = [] + finalized: list[str] = [] + + async def on_changed( + sender: IObservableMap_String_Object, args: IMapChangedEventArgs_String, + ) -> None: + key = args.key + try: + file = await folder.create_file_async(f"{key}.txt") + await FileIO.write_text_async(file, key) + assert await FileIO.read_text_async(file) == key + # Both projected callback arguments are still usable after await. + assert args.key in sender + if fail: + raise ValueError("notification handler failed") + completed.append(key) + finally: + finalized.append(key) + + try: + async with AsyncEventScope(loop=asyncio.get_running_loop()) as events: + unsubscribe = events.subscribe(properties.subscribe_map_changed, on_changed) + properties["accepted"] = None + unsubscribe() + properties["not-delivered"] = None + except* ValueError as errors: + if not fail: + raise + print("Handler failure propagated:", errors) + assert finalized == ["accepted"] + assert completed == ([] if fail else ["accepted"]) + print("async-events-ok", {"completed": completed, "finalized": finalized}) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fail", action="store_true", help="Demonstrate handler error propagation") + asyncio.run(run(fail=parser.parse_args().fail)) diff --git a/tests/e2e/runners/py_async_events.py b/tests/e2e/runners/py_async_events.py new file mode 100644 index 00000000..a4b5c1d1 --- /dev/null +++ b/tests/e2e/runners/py_async_events.py @@ -0,0 +1,300 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Headless AsyncEventScope regressions against generated, real PropertySet APIs.""" + +import argparse +import asyncio +from contextvars import ContextVar +import gc +import importlib +from pathlib import Path +import sys +import tempfile +import threading +import warnings + + +async def check_native(g, dw, mode): + collections = importlib.import_module(f"{g.__name__}.windows.foundation.collections") + owner = threading.current_thread() + context = ContextVar("async-event-context") + with tempfile.TemporaryDirectory(prefix="dynwinrt-event-test-") as directory: + with dw.RoApartment(mode), dw.projected_lifetime_scope() as lifetime: + folder = await g.StorageFolder.get_folder_from_path_async(directory) + properties = g.PropertySet() + observed = [] + retained = [] + context.set("subscription") + + async def changed(sender, args): + assert threading.current_thread() is owner + file = await folder.create_file_async(f"{args.key}.txt") + assert Path(file.path).is_file() + assert threading.current_thread() is owner + assert context.get() == "subscription" + assert not lifetime.disposed + assert args.key in sender + assert sender.size == 3 + observed.append(args.key) + retained.append((sender, args)) + + def register(callback): + stop = properties.subscribe_map_changed(callback) + properties["registration"] = None + return stop + + async with dw.AsyncEventScope(loop=asyncio.get_running_loop()) as events: + stop = events.subscribe(register, changed) + context.set("body") + properties["accepted"] = None + stop() + stop() + properties["ignored"] = None + assert sorted(observed) == ["accepted", "registration"] + # Event args are not agile. Test the args, not just the agile sender. + errors = [] + + def foreign_read(): + with dw.RoApartment(): + try: + _ = retained[0][1].key + except RuntimeError as error: + errors.append(str(error)) + + thread = threading.Thread(target=foreign_read) + thread.start() + thread.join(5) + assert not thread.is_alive() and len(errors) == 1, errors + assert "thread" in errors[0], errors + assert retained[0][1].key in properties + + # Native synchronous callbacks and already-owned Task results stay valid. + synchronous = [] + stop = properties.subscribe_map_changed( + lambda sender, args: synchronous.append(args.key) + ) + properties["sync"] = None + stop() + assert synchronous == ["sync"] + owned = [] + + async def legacy_handler(sender, args): + await asyncio.sleep(0) + owned.append(args.key) + + async with asyncio.TaskGroup() as group: + stop = properties.subscribe_map_changed( + lambda sender, args: group.create_task(legacy_handler(sender, args)) + ) + properties["owned-task"] = None + stop() + assert owned == ["owned-task"] + + raw = [] + delegate = dw.DynWinRtDelegate.create( + collections.IID_MapChangedEventHandler_String_Object, + collections.MapChangedEventHandler_String_Object_PARAM_TYPES, + lambda sender, args: raw.append((sender, args)), + ) + stop = properties.subscribe_map_changed(delegate) + properties["raw"] = None + stop() + assert len(raw) == 1 + assert all(isinstance(value, dw.DynWinRTValue) for value in raw[0]) + delegate.release() + + called = [] + + async def bare_handler(sender, args): + called.append(args.key) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + stop = properties.subscribe_map_changed(bare_handler) + properties["bare"] = None + stop() + gc.collect() + assert called == [] + assert any("was never awaited" in str(w.message) for w in caught) + + loop = asyncio.get_running_loop() + factory = loop.get_task_factory() + unraisable = [] + rejected = [] + hook = sys.unraisablehook + + def fail_factory(loop, coroutine, **kwargs): + rejected.append(coroutine) + raise RuntimeError("native callback task creation failed") + + async with dw.AsyncEventScope(loop=loop) as events: + events.subscribe(properties.subscribe_map_changed, bare_handler) + sys.unraisablehook = lambda error: unraisable.append(str(error.exc_value)) + loop.set_task_factory(fail_factory) + try: + try: + properties["task-creation"] = None + except OSError as error: + assert error.winerror & 0xFFFFFFFF == 0xA0EE4005 + finally: + loop.set_task_factory(factory) + sys.unraisablehook = hook + assert unraisable == ["native callback task creation failed"] + assert len(rejected) == 1 and rejected[0].cr_frame is None + assert called == [] + + for after_await in (False, True): + started = asyncio.Event() + cleaned = [] + + async def failing(sender, args): + key = args.key + if key == "waiting": + try: + started.set() + await asyncio.Event().wait() + finally: + await asyncio.sleep(0) + assert args.key in sender + assert not lifetime.disposed + cleaned.append(key) + else: + if after_await: + await asyncio.sleep(0) + raise ValueError("native event handler failed") + + try: + async with dw.AsyncEventScope(loop=asyncio.get_running_loop()) as events: + events.subscribe(properties.subscribe_map_changed, failing) + properties["waiting"] = None + await started.wait() + properties["failure"] = None + await asyncio.Event().wait() + except ExceptionGroup as error: + assert len(error.exceptions) == 1 + assert str(error.exceptions[0]) == "native event handler failed" + else: + raise AssertionError("handler failure was lost") + assert cleaned == ["waiting"] + properties["after-failure"] = None + + started = asyncio.Event() + cleaned = [] + + async def cancellable(sender, args): + try: + started.set() + await asyncio.Event().wait() + finally: + await asyncio.sleep(0) + assert args.key in sender and not lifetime.disposed + cleaned.append(args.key) + + async def parent(): + async with dw.AsyncEventScope(loop=asyncio.get_running_loop()) as events: + events.subscribe(properties.subscribe_map_changed, cancellable) + properties["cancel"] = None + await asyncio.Event().wait() + + task = asyncio.create_task(parent()) + await started.wait() + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + else: + raise AssertionError("external cancellation was lost") + assert cleaned == ["cancel"] + + reentered = asyncio.Event() + keys = [] + + async def reentrant(sender, args): + # PropertySet rejects mutation inside its native notification. + # This yield is also needed with an eager task factory. + await asyncio.sleep(0) + if args.key == "outer": + properties["inner"] = None + await reentered.wait() + else: + reentered.set() + keys.append(args.key) + + async with dw.AsyncEventScope(loop=asyncio.get_running_loop()) as events: + events.subscribe(properties.subscribe_map_changed, reentrant) + properties["outer"] = None + await reentered.wait() + assert keys == ["inner", "outer"] + + # Context captured by the generated delegate must not be cleared by + # the helper to make early native-owner disposal appear safe. + captured = [] + inner = dw.projected_lifetime_scope() + with inner: + captured_folder = await g.StorageFolder.get_folder_from_path_async(directory) + async with dw.AsyncEventScope(loop=asyncio.get_running_loop()) as events: + async def observe_scope(sender, args): + await asyncio.sleep(0) + captured.append(captured_folder.path) + events.subscribe(properties.subscribe_map_changed, observe_scope) + properties["lifetime"] = None + assert captured == [directory] + try: + _ = captured_folder.path + except RuntimeError as error: + assert "released" in str(error) + else: + raise AssertionError("projection scope was bypassed") + + try: + async with dw.AsyncEventScope(loop=loop) as events: + with dw.projected_lifetime_scope(): + early_folder = await g.StorageFolder.get_folder_from_path_async(directory) + + async def invalid_lifetime(sender, args): + await asyncio.sleep(0) + _ = early_folder.path + + events.subscribe(properties.subscribe_map_changed, invalid_lifetime) + properties["early-release"] = None + except ExceptionGroup as error: + assert len(error.exceptions) == 1 + assert "released" in str(error.exceptions[0]) + else: + raise AssertionError("AsyncEventScope extended a released projection lifetime") + try: + _ = retained[0][1].key + except RuntimeError as error: + assert "released" in str(error) or "initialized" in str(error) + else: + raise AssertionError("event arguments survived final apartment release") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--generated", required=True) + parser.add_argument("--mode", type=int, choices=(0, 1), required=True) + options = parser.parse_args() + generated = Path(options.generated).resolve() + sys.path.insert(0, str(generated.parent)) + g = importlib.import_module(generated.name) + import dynwinrt as dw + + async def run(): + loop = asyncio.get_running_loop() + await check_native(g, dw, options.mode) + if hasattr(asyncio, "eager_task_factory"): + loop.set_task_factory(asyncio.eager_task_factory) + try: + await check_native(g, dw, options.mode) + finally: + loop.set_task_factory(None) + + asyncio.run(run()) + print(f"PASS async-events apartment={options.mode}") + + +if __name__ == "__main__": + main() diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index fe399e54..c6e156c0 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -1561,6 +1561,22 @@ def observe_null(sender, args): dw.release_projected(null_events[0][0]) del obj['null-element'] if cls.__name__ == 'PropertySet': + for mode in (dw.RO_INIT_SINGLETHREADED, dw.RO_INIT_MULTITHREADED): + child = subprocess.run( + [ + sys.executable, '-I', + os.path.join(os.path.dirname(__file__), 'py_async_events.py'), + '--generated', generated_dir, '--mode', str(mode), + ], + capture_output=True, text=True, timeout=60, check=False, + ) + if child.returncode or f'PASS async-events apartment={mode}' not in child.stdout: + cr['error'] = ( + f'async-events apartment={mode} failed with ' + f'0x{child.returncode & 0xffffffff:08X}: ' + f'{child.stdout} {child.stderr}' + ) + return cr runner = os.path.join( os.path.dirname(__file__), 'py_apartment_reentrancy.py' ) diff --git a/tests/e2e/typecheck/python_generated_api.py b/tests/e2e/typecheck/python_generated_api.py index d2b61024..0e13ced9 100644 --- a/tests/e2e/typecheck/python_generated_api.py +++ b/tests/e2e/typecheck/python_generated_api.py @@ -8,6 +8,7 @@ from uuid import UUID from dynwinrt import ( + AsyncEventScope, DynWinRTArray, DynWinRtDelegate, WinRTAsync, @@ -331,6 +332,29 @@ def on_strings( unsubscribe() +async def check_async_event_scope(properties: PropertySet, strings: StringMap) -> None: + async def changed( + sender: IObservableMap_String_Object, args: IMapChangedEventArgs_String, + ) -> None: + await asyncio.sleep(0) + assert_type(sender[args.key], DynWinRTValue | None) + + def awaitable_handler( + sender: IObservableMap_String_Object, args: IMapChangedEventArgs_String, + ) -> Awaitable[None]: + return changed(sender, args) + + def synchronous(sender: IObservableMap_String_Object, args: IMapChangedEventArgs_String) -> None: + pass + + async with AsyncEventScope(loop=asyncio.get_running_loop()) as events: + stop: Callable[[], None] = events.subscribe(properties.subscribe_map_changed, changed) + events.subscribe(properties.subscribe_map_changed, awaitable_handler)() + events.subscribe(strings.subscribe_map_changed, changed) # type: ignore[arg-type] + events.subscribe(properties.subscribe_map_changed, synchronous) # type: ignore[arg-type] + stop() + + def check_delegate_callback_parameters() -> None: inferred_work: WinRTCoroutine[None] = ThreadPool.run_async( lambda operation: assert_type(operation, DynWinRTValue) From 988c8cc29169f2c98199c67b641a0efde1d7ddbb Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 30 Oct 2026 08:38:47 +0800 Subject: [PATCH 2/4] Compare native event test paths by directory identity Keep exact callback cardinality and native lifetime checks while accepting Windows path aliases. Exercise a dot-dot temp-root alias in every native run so canonicalization is covered even without NTFS short names. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/e2e/runners/py_async_events.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/tests/e2e/runners/py_async_events.py b/tests/e2e/runners/py_async_events.py index a4b5c1d1..81df9006 100644 --- a/tests/e2e/runners/py_async_events.py +++ b/tests/e2e/runners/py_async_events.py @@ -15,11 +15,11 @@ import warnings -async def check_native(g, dw, mode): +async def check_native(g, dw, mode, *, temp_root): collections = importlib.import_module(f"{g.__name__}.windows.foundation.collections") owner = threading.current_thread() context = ContextVar("async-event-context") - with tempfile.TemporaryDirectory(prefix="dynwinrt-event-test-") as directory: + with tempfile.TemporaryDirectory(prefix="dynwinrt-event-test-", dir=temp_root) as directory: with dw.RoApartment(mode), dw.projected_lifetime_scope() as lifetime: folder = await g.StorageFolder.get_folder_from_path_async(directory) properties = g.PropertySet() @@ -240,7 +240,8 @@ async def observe_scope(sender, args): captured.append(captured_folder.path) events.subscribe(properties.subscribe_map_changed, observe_scope) properties["lifetime"] = None - assert captured == [directory] + assert len(captured) == 1, captured + assert Path(captured[0]).samefile(directory), (captured[0], directory) try: _ = captured_folder.path except RuntimeError as error: @@ -284,13 +285,16 @@ def main(): async def run(): loop = asyncio.get_running_loop() - await check_native(g, dw, options.mode) - if hasattr(asyncio, "eager_task_factory"): - loop.set_task_factory(asyncio.eager_task_factory) - try: - await check_native(g, dw, options.mode) - finally: - loop.set_task_factory(None) + with tempfile.TemporaryDirectory(prefix="dynwinrt-event-root-") as root: + # Exercise native path normalization without requiring NTFS 8.3 names. + temp_root = str(Path(root) / ".." / Path(root).name) + await check_native(g, dw, options.mode, temp_root=temp_root) + if hasattr(asyncio, "eager_task_factory"): + loop.set_task_factory(asyncio.eager_task_factory) + try: + await check_native(g, dw, options.mode, temp_root=temp_root) + finally: + loop.set_task_factory(None) asyncio.run(run()) print(f"PASS async-events apartment={options.mode}") From c50d707f04e2df8302ab5a3a6077c42319d1a269 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 30 Oct 2026 08:53:13 +0800 Subject: [PATCH 3/4] Use a version-safe path alias in async event regression Python 3.11 preserves dot segments in tempfile paths, unlike 3.12+, and StorageFolder can reject them. Exercise equivalent directory spelling through case instead; retain exact callback count and samefile validation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/e2e/runners/py_async_events.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/tests/e2e/runners/py_async_events.py b/tests/e2e/runners/py_async_events.py index 81df9006..2656b52a 100644 --- a/tests/e2e/runners/py_async_events.py +++ b/tests/e2e/runners/py_async_events.py @@ -15,11 +15,11 @@ import warnings -async def check_native(g, dw, mode, *, temp_root): +async def check_native(g, dw, mode): collections = importlib.import_module(f"{g.__name__}.windows.foundation.collections") owner = threading.current_thread() context = ContextVar("async-event-context") - with tempfile.TemporaryDirectory(prefix="dynwinrt-event-test-", dir=temp_root) as directory: + with tempfile.TemporaryDirectory(prefix="dynwinrt-event-test-") as directory: with dw.RoApartment(mode), dw.projected_lifetime_scope() as lifetime: folder = await g.StorageFolder.get_folder_from_path_async(directory) properties = g.PropertySet() @@ -233,7 +233,10 @@ async def reentrant(sender, args): captured = [] inner = dw.projected_lifetime_scope() with inner: - captured_folder = await g.StorageFolder.get_folder_from_path_async(directory) + # Exercise an equivalent spelling without dot segments, which + # StorageFolder does not support on all Windows versions. + lookup_path = str(Path(directory).with_name(Path(directory).name.upper())) + captured_folder = await g.StorageFolder.get_folder_from_path_async(lookup_path) async with dw.AsyncEventScope(loop=asyncio.get_running_loop()) as events: async def observe_scope(sender, args): await asyncio.sleep(0) @@ -285,16 +288,13 @@ def main(): async def run(): loop = asyncio.get_running_loop() - with tempfile.TemporaryDirectory(prefix="dynwinrt-event-root-") as root: - # Exercise native path normalization without requiring NTFS 8.3 names. - temp_root = str(Path(root) / ".." / Path(root).name) - await check_native(g, dw, options.mode, temp_root=temp_root) - if hasattr(asyncio, "eager_task_factory"): - loop.set_task_factory(asyncio.eager_task_factory) - try: - await check_native(g, dw, options.mode, temp_root=temp_root) - finally: - loop.set_task_factory(None) + await check_native(g, dw, options.mode) + if hasattr(asyncio, "eager_task_factory"): + loop.set_task_factory(asyncio.eager_task_factory) + try: + await check_native(g, dw, options.mode) + finally: + loop.set_task_factory(None) asyncio.run(run()) print(f"PASS async-events apartment={options.mode}") From 5d48ca6904125d311e4898a4da21fa876e5a790e Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 30 Oct 2026 09:27:08 +0800 Subject: [PATCH 4/4] Preserve TaskGroup cancellation semantics during unsubscribe failures Keep incoming cancellation out of the cleanup exception group while retaining removal errors. Compare combined internal/external cancellation cases with the running Python version's TaskGroup, including native PropertySet delivery and retryable unsubscription. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/README.md | 12 ++- bindings/py/python/dynwinrt/_events.py | 3 +- bindings/py/tests/test_async_event_scope.py | 88 ++++++++++++++++++- tests/e2e/runners/py_async_events.py | 94 +++++++++++++++++++++ 4 files changed, 190 insertions(+), 7 deletions(-) diff --git a/bindings/py/README.md b/bindings/py/README.md index cbf328c1..4ddc4924 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -334,10 +334,14 @@ does not cancel accepted tasks. A native removal failure is raised to its caller, leaves delivery disabled, and can be retried with the same callable on the owner loop/thread while native owners are still live. Scope exit attempts **every** remaining removal in reverse registration order. Removal -failures (and any body exception) are preserved in an exception group passed -to TaskGroup, cancelling outstanding work rather than hanging in a normal -drain. Save unsubscribe callables if your application needs to recover from -native removal failures; recovery must happen before closing native lifetimes. +failures (and non-cancellation body exceptions) are preserved in an exception +group passed to TaskGroup, cancelling outstanding work rather than hanging in +a normal drain. A body's `CancelledError` is TaskGroup control flow, not an +extra leaf added to that cleanup error group. When cancellation coincides with +other errors, their propagation and cancellation bookkeeping follow the running +Python version's TaskGroup semantics. Save unsubscribe callables if your +application needs to recover from native removal failures; recovery must happen +before closing native lifetimes. The scope is single-use and must exit in the task that entered it. Its constructor binds it to the creating OS thread; entry, subscription, callbacks, diff --git a/bindings/py/python/dynwinrt/_events.py b/bindings/py/python/dynwinrt/_events.py index a684e811..00a768bc 100644 --- a/bindings/py/python/dynwinrt/_events.py +++ b/bindings/py/python/dynwinrt/_events.py @@ -125,7 +125,8 @@ async def __aexit__( except BaseException as error: errors.append(error) if errors: - if exc_value is not None: + # TaskGroup handles cancellation separately from ordinary errors. + if exc_value is not None and not isinstance(exc_value, _asyncio.CancelledError): errors.insert(0, exc_value) exc_value = BaseExceptionGroup("AsyncEventScope unsubscribe failed", errors) exc_type = type(exc_value) diff --git a/bindings/py/tests/test_async_event_scope.py b/bindings/py/tests/test_async_event_scope.py index 2ed43204..b00469d4 100644 --- a/bindings/py/tests/test_async_event_scope.py +++ b/bindings/py/tests/test_async_event_scope.py @@ -270,14 +270,16 @@ async def run(): async def changed(value): await asyncio.sleep(0) - with pytest.raises(BaseExceptionGroup) as failure: + with pytest.raises(ExceptionGroup) as failure: async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: stops.extend(scope.subscribe(event.subscribe, changed) for event in events) if body_error: raise body_error errors = leaves(failure.value) assert sum(isinstance(error, OSError) for error in errors) == 2 - if body_error: + if isinstance(body_error, asyncio.CancelledError): + assert not any(isinstance(error, asyncio.CancelledError) for error in errors) + elif body_error: assert body_error in errors assert [event.removals for event in events] == [1, 1, 1] for event, stop in zip(events, stops): @@ -314,6 +316,88 @@ async def changed(value): asyncio.run(run()) +@pytest.mark.parametrize("failure", ["handler", "external", "both", "cancel_during_cleanup"]) +@pytest.mark.parametrize("cleanup_fails", [False, True]) +def test_cleanup_and_cancellation_match_taskgroup(task_factory, failure, cleanup_fails): + async def exercise(use_scope): + event = Notification(failures=int(cleanup_fails)) + started = asyncio.Event() + fail_handler = asyncio.Event() + finalized = [] + + async def changed(value): + try: + started.set() + await fail_handler.wait() + raise ValueError("handler failed") + finally: + finalized.append(value) + + async def owner(): + task = asyncio.current_task() + if failure == "cancel_during_cleanup": + event.removing = task.cancel + result = {} + try: + if use_scope: + async with AsyncEventScope(loop=asyncio.get_running_loop()) as scope: + stop = scope.subscribe(event.subscribe, changed) + event.emit(1) + await asyncio.Event().wait() + else: + async with asyncio.TaskGroup() as group: + stop = event.subscribe(lambda value: group.create_task(changed(value))) + try: + event.emit(1) + await asyncio.Event().wait() + finally: + stop() + except BaseException as error: + result["exception"] = type(error) + result["leaves"] = sorted( + (type(leaf).__name__, str(leaf)) for leaf in leaves(error) + ) + result["ordinary_exception"] = isinstance(error, Exception) + else: + raise AssertionError("expected handler failure or cancellation") + result["cancelling"] = task.cancelling() + try: + await asyncio.sleep(0) + except asyncio.CancelledError: + result["next_await_cancelled"] = True + else: + result["next_await_cancelled"] = False + assert finalized == [1] + assert event.removals == 1 + event.removing = lambda: None + if cleanup_fails: + stop() + assert event.removals == 2 + assert event.callback is None + return result + + task = asyncio.create_task(owner()) + await started.wait() + if failure != "external": + fail_handler.set() + if failure in ("external", "both"): + task.cancel() + return await task + + async def run(): + expected = await exercise(False) + actual = await exercise(True) + assert actual == expected + if cleanup_fails: + assert actual["ordinary_exception"] + assert ("OSError", "native removal failed") in actual["leaves"] + assert all(name != "CancelledError" for name, _ in actual["leaves"]) + elif failure == "external": + assert actual["exception"] is asyncio.CancelledError + + run_with_factory(run(), task_factory) + + def test_registration_failure_disables_its_callback_and_drains_accepted_work(): async def run(): received = [] diff --git a/tests/e2e/runners/py_async_events.py b/tests/e2e/runners/py_async_events.py index 2656b52a..61c7bed5 100644 --- a/tests/e2e/runners/py_async_events.py +++ b/tests/e2e/runners/py_async_events.py @@ -15,6 +15,99 @@ import warnings +async def check_cleanup_cancellation(g, dw): + def leaves(error): + if isinstance(error, BaseExceptionGroup): + return [leaf for child in error.exceptions for leaf in leaves(child)] + return [(type(error).__name__, str(error))] + + async def exercise(use_scope, failure): + properties = g.PropertySet() + started = asyncio.Event() + fail_handler = asyncio.Event() + finalized = [] + removals = 0 + + def subscribe(callback): + native_stop = properties.subscribe_map_changed(callback) + + def stop(): + nonlocal removals + removals += 1 + if removals == 1: + raise OSError("induced native unsubscribe failure") + native_stop() + + return stop + + async def changed(sender, args): + try: + started.set() + await fail_handler.wait() + assert args.key == "trigger" and args.key in sender + raise ValueError("native handler failed") + finally: + finalized.append(args.key) + + async def owner(): + task = asyncio.current_task() + try: + if use_scope: + async with dw.AsyncEventScope(loop=asyncio.get_running_loop()) as events: + stop = events.subscribe(subscribe, changed) + properties["trigger"] = None + await asyncio.Event().wait() + else: + async with asyncio.TaskGroup() as group: + stop = subscribe( + lambda sender, args: group.create_task(changed(sender, args)) + ) + try: + properties["trigger"] = None + await asyncio.Event().wait() + finally: + stop() + except BaseException as error: + result = { + "exception": type(error).__name__, + "leaves": sorted(leaves(error)), + "ordinary_exception": isinstance(error, Exception), + "cancelling": task.cancelling(), + } + else: + raise AssertionError("expected notification/cleanup errors") + try: + await asyncio.sleep(0) + except asyncio.CancelledError: + result["next_await_cancelled"] = True + else: + result["next_await_cancelled"] = False + assert finalized == ["trigger"] and removals == 1 + stop() + properties["unsubscribed"] = None + assert finalized == ["trigger"] and removals == 2 + return result + + task = asyncio.create_task(owner()) + await started.wait() + if failure != "external": + fail_handler.set() + if failure in ("external", "both"): + task.cancel() + return await task + + comparisons = [] + for failure in ("handler", "external", "both"): + expected = await exercise(False, failure) + actual = await exercise(True, failure) + assert actual == expected, (failure, actual, expected) + assert actual["ordinary_exception"], actual + assert ("OSError", "induced native unsubscribe failure") in actual["leaves"] + assert all(name != "CancelledError" for name, _ in actual["leaves"]), actual + comparisons.append({"failure": failure, "actual": actual, "expected": expected}) + return comparisons + + async def check_native(g, dw, mode): collections = importlib.import_module(f"{g.__name__}.windows.foundation.collections") owner = threading.current_thread() @@ -268,6 +361,7 @@ async def invalid_lifetime(sender, args): assert "released" in str(error.exceptions[0]) else: raise AssertionError("AsyncEventScope extended a released projection lifetime") + await check_cleanup_cancellation(g, dw) try: _ = retained[0][1].key except RuntimeError as error: