From 5661fd3530ac16d012e63b6074e4f3d2bcb7a57c Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 2 Sep 2026 23:54:08 +0800 Subject: [PATCH 1/4] Support Python async operations in create_task Implement the coroutine driving protocol for generated WinRT async operations while preserving repeatable direct awaits, cancellation, progress, blocking safeguards, and release semantics. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/README.md | 14 + bindings/py/dynwinrt.pyi | 12 +- bindings/py/src/async_runtime.rs | 326 +++++++++++++++++++- bindings/py/src/lib.rs | 39 ++- bindings/py/tests/test_e2e_winrt.py | 59 +++- bindings/py/tests/test_phase1.py | 210 ++++++++++++- tests/e2e/runners/py_runner.py | 20 +- tests/e2e/typecheck/python_generated_api.py | 16 +- 8 files changed, 668 insertions(+), 28 deletions(-) diff --git a/bindings/py/README.md b/bindings/py/README.md index 10efae75..7e1112ae 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -26,6 +26,12 @@ Generated async methods return typed, asyncio-compatible operation objects: ```python operation = writer.store_async() stored_bytes = await operation + +task = asyncio.create_task(writer.store_async()) +stored_bytes = await task + +async with asyncio.TaskGroup() as group: + task = group.create_task(writer.store_async()) ``` Their public types are `WinRTAsync[T]` and @@ -39,6 +45,14 @@ WinRT operation. Operations with supported progress values also expose `operation.progress(callback)`. Fast operations can finish before registration; in that case no future progress exists and registration is a no-op. +An operation can be awaited directly more than once; every direct await observes +the same converted completion, failure, or cancellation. Its coroutine driver is +one-shot like a native Python coroutine, so pass a given operation to +`create_task()`, `TaskGroup.create_task()`, or `ensure_future()` only once. +Directly awaiting that operation after its task completes remains supported. +Calling `close()` cancels pending WinRT work and permanently closes the coroutine +driver. + For scripts without an event loop, `operation.wait()` remains available as an explicit blocking API. It rejects started operations when called from a running asyncio loop or an STA thread, where blocking could freeze or deadlock the diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 6522169f..dcec08f1 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -1,4 +1,6 @@ -from typing import Awaitable, Callable, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload +from abc import ABCMeta, abstractmethod +from collections.abc import Coroutine +from typing import Any, Callable, Generic, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload from uuid import UUID _T = TypeVar("_T", covariant=True) @@ -378,13 +380,17 @@ class DynWinRTValue: def __str__(self) -> str: ... -class WinRTAsync(Awaitable[_T], Protocol[_T]): +class WinRTAsync(Coroutine[Any, Any, _T], metaclass=ABCMeta): + @abstractmethod def wait(self) -> _T: ... + @abstractmethod def cancel(self) -> None: ... + @abstractmethod def release(self) -> None: ... -class WinRTAsyncWithProgress(WinRTAsync[_T], Protocol[_T, _P]): +class WinRTAsyncWithProgress(WinRTAsync[_T], Generic[_T, _P], metaclass=ABCMeta): + @abstractmethod def progress(self, callback: Callable[[_P], object]) -> None: ... diff --git a/bindings/py/src/async_runtime.rs b/bindings/py/src/async_runtime.rs index 39106fb7..ade9bc72 100644 --- a/bindings/py/src/async_runtime.rs +++ b/bindings/py/src/async_runtime.rs @@ -9,7 +9,7 @@ use crate::errors::{ map_dynwinrt_error, map_dynwinrt_error_with_context, map_windows_error_with_context, }; use crate::runtime::DynWinRTValue; -use pyo3::exceptions::PyRuntimeError; +use pyo3::exceptions::{PyRuntimeError, PyTypeError}; use pyo3::prelude::*; use windows::Win32::Foundation::CO_E_NOTINITIALIZED; use windows::Win32::System::Com::{ @@ -140,6 +140,258 @@ enum ExecutionState { Future(Py), } +enum CoroutineExecutionState { + New, + Executing(Py), + Suspended { + owner: Py, + coroutine: Py, + }, + Finished, + Closed, +} + +struct CoroutineProtocol { + state: Mutex, +} + +impl CoroutineProtocol { + fn new() -> Self { + Self { + state: Mutex::new(CoroutineExecutionState::New), + } + } + + fn lock_state(&self) -> PyResult> { + self.state + .lock() + .map_err(|_| PyRuntimeError::new_err("coroutine state lock was poisoned")) + } + + fn ensure_awaitable(&self) -> PyResult<()> { + if matches!(*self.lock_state()?, CoroutineExecutionState::Closed) { + return Err(PyRuntimeError::new_err( + "cannot reuse closed WinRT async coroutine", + )); + } + Ok(()) + } + + fn current_owner(&self, py: Python<'_>) -> PyResult> { + Ok(py.import("asyncio")?.call_method0("current_task")?.unbind()) + } + + fn begin_call( + &self, + operation: Option<&AsyncOperation>, + py: Python<'_>, + require_started: bool, + ) -> PyResult<(Py, Py)> { + let owner = self.current_owner(py)?; + let existing = { + let mut state = self.lock_state()?; + match &*state { + CoroutineExecutionState::New => None, + CoroutineExecutionState::Suspended { + owner: current_owner, + .. + } if !current_owner.bind(py).is(owner.bind(py)) => { + return Err(PyRuntimeError::new_err( + "WinRT async coroutine is already being awaited by another task", + )); + } + CoroutineExecutionState::Suspended { .. } => { + match std::mem::replace( + &mut *state, + CoroutineExecutionState::Executing(owner.clone_ref(py)), + ) { + CoroutineExecutionState::Suspended { coroutine, .. } => Some(coroutine), + _ => unreachable!(), + } + } + CoroutineExecutionState::Executing(_) => { + return Err(PyRuntimeError::new_err( + "WinRT async coroutine is already executing", + )); + } + CoroutineExecutionState::Finished | CoroutineExecutionState::Closed => { + return Err(PyRuntimeError::new_err( + "cannot reuse already awaited WinRT async coroutine", + )); + } + } + }; + + if let Some(coroutine) = existing { + return Ok((owner, coroutine)); + } + if require_started { + return Err(PyTypeError::new_err( + "can't send non-None value to a just-started coroutine", + )); + } + + let operation = operation.ok_or_else(|| { + PyRuntimeError::new_err("the WinRT async operation has been released") + })?; + let future = operation.future(py)?; + let coroutine = py + .import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_drive_future")? + .call1((future,))? + .unbind(); + *self.lock_state()? = CoroutineExecutionState::Executing(owner.clone_ref(py)); + Ok((owner, coroutine)) + } + + fn finish_call( + &self, + py: Python<'_>, + owner: Py, + coroutine: Py, + result: &PyResult>, + ) -> PyResult<()> { + let mut state = self.lock_state()?; + match &*state { + CoroutineExecutionState::Executing(current_owner) + if current_owner.bind(py).is(owner.bind(py)) => {} + _ => { + return Err(PyRuntimeError::new_err( + "WinRT async coroutine execution state changed unexpectedly", + )); + } + } + *state = if result.is_ok() { + CoroutineExecutionState::Suspended { owner, coroutine } + } else { + CoroutineExecutionState::Finished + }; + Ok(()) + } + + fn send( + &self, + operation: Option<&AsyncOperation>, + py: Python<'_>, + value: Py, + ) -> PyResult> { + let require_started = !value.bind(py).is_none(); + let (owner, coroutine) = self.begin_call(operation, py, require_started)?; + let result = coroutine.call_method1(py, "send", (value,)); + self.finish_call(py, owner, coroutine, &result)?; + result + } + + fn throw( + &self, + operation: Option<&AsyncOperation>, + py: Python<'_>, + typ: Py, + value: Option>, + traceback: Option>, + ) -> PyResult> { + let validation_value = value + .as_ref() + .map(|value| value.clone_ref(py)) + .unwrap_or_else(|| py.None()); + let validation_traceback = traceback + .as_ref() + .map(|traceback| traceback.clone_ref(py)) + .unwrap_or_else(|| py.None()); + py.import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_validate_throw")? + .call1((typ.clone_ref(py), validation_value, validation_traceback))?; + + if operation.is_none() && matches!(*self.lock_state()?, CoroutineExecutionState::New) { + let coroutine = py + .import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_empty_coroutine")? + .call0()?; + return match (value, traceback) { + (None, None) => coroutine.call_method1("throw", (typ,)).map(Bound::unbind), + (Some(value), None) => coroutine + .call_method1("throw", (typ, value)) + .map(Bound::unbind), + (value, Some(traceback)) => coroutine + .call_method1( + "throw", + (typ, value.unwrap_or_else(|| py.None()), traceback), + ) + .map(Bound::unbind), + }; + } + + let (owner, coroutine) = self.begin_call(operation, py, false)?; + let result = match (value, traceback) { + (None, None) => coroutine.call_method1(py, "throw", (typ,)), + (Some(value), None) => coroutine.call_method1(py, "throw", (typ, value)), + (value, Some(traceback)) => coroutine.call_method1( + py, + "throw", + (typ, value.unwrap_or_else(|| py.None()), traceback), + ), + }; + self.finish_call(py, owner, coroutine, &result)?; + if let Err(primary_error) = &result { + if let Some(operation) = operation { + if !operation.future_is_done(py)? { + if let Err(cleanup_error) = operation.stop(py) { + append_cleanup_error(py, primary_error, &cleanup_error)?; + } + } + } + } + result + } + + fn close(&self, operation: &AsyncOperation, py: Python<'_>) -> PyResult<()> { + let coroutine = { + let mut state = self.lock_state()?; + match &*state { + CoroutineExecutionState::Closed => None, + CoroutineExecutionState::Finished => return Ok(()), + CoroutineExecutionState::Executing(_) => { + return Err(PyRuntimeError::new_err( + "cannot close a WinRT async coroutine while it is executing", + )); + } + CoroutineExecutionState::New => { + *state = CoroutineExecutionState::Closed; + None + } + CoroutineExecutionState::Suspended { .. } => { + match std::mem::replace(&mut *state, CoroutineExecutionState::Closed) { + CoroutineExecutionState::Suspended { coroutine, .. } => Some(coroutine), + _ => unreachable!(), + } + } + } + }; + + let close_result = match coroutine { + Some(coroutine) => coroutine.call_method0(py, "close").map(|_| ()), + None => Ok(()), + }; + let cleanup_result = operation.stop(py); + match (close_result, cleanup_result) { + (Ok(()), Ok(())) => Ok(()), + (Ok(()), Err(cleanup_error)) => Err(cleanup_error), + (Err(primary_error), Ok(())) => Err(primary_error), + (Err(primary_error), Err(cleanup_error)) => { + append_cleanup_error(py, &primary_error, &cleanup_error)?; + Err(primary_error) + } + } + } +} + +fn append_cleanup_error(py: Python<'_>, primary: &PyErr, cleanup: &PyErr) -> PyResult<()> { + py.import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_append_exception_cause")? + .call1((primary.value(py), cleanup.value(py)))?; + Ok(()) +} + struct AsyncOperation { value: dynwinrt::WinRTValue, converter: Py, @@ -162,7 +414,7 @@ impl AsyncOperation { .map_err(|_| PyRuntimeError::new_err("async operation state lock was poisoned")) } - fn release(&self, py: Python<'_>) -> PyResult<()> { + fn stop(&self, py: Python<'_>) -> PyResult<()> { let _ = self.cancel(); let future = { let mut state = self.lock_state()?; @@ -177,6 +429,20 @@ impl AsyncOperation { Ok(()) } + fn future_is_done(&self, py: Python<'_>) -> PyResult { + let future = { + let state = self.lock_state()?; + match &*state { + ExecutionState::Future(future) => Some(future.clone_ref(py)), + ExecutionState::Idle | ExecutionState::Blocking => None, + } + }; + match future { + Some(future) => future.call_method0(py, "done")?.extract(py), + None => Ok(false), + } + } + fn future<'py>(&self, py: Python<'py>) -> PyResult> { let mut state = self.lock_state()?; match &*state { @@ -276,6 +542,7 @@ pub(crate) fn finish_progress_registration( #[pyclass(name = "_DynWinRTAsync")] pub struct DynWinRTAsync { operation: Option>, + coroutine: CoroutineProtocol, } impl DynWinRTAsync { @@ -292,11 +559,34 @@ impl DynWinRTAsync { fn new(value: &DynWinRTValue, result_converter: Py) -> PyResult { Ok(Self { operation: Some(Arc::new(AsyncOperation::new(value, result_converter)?)), + coroutine: CoroutineProtocol::new(), }) } fn __await__<'py>(&self, py: Python<'py>) -> PyResult> { - self.operation()?.await_iter(py) + let operation = self.operation()?; + self.coroutine.ensure_awaitable()?; + operation.await_iter(py) + } + + fn send(&self, py: Python<'_>, value: Py) -> PyResult> { + self.coroutine.send(self.operation.as_deref(), py, value) + } + + #[pyo3(signature = (typ, value=None, traceback=None))] + fn throw( + &self, + py: Python<'_>, + typ: Py, + value: Option>, + traceback: Option>, + ) -> PyResult> { + self.coroutine + .throw(self.operation.as_deref(), py, typ, value, traceback) + } + + fn close(&self, py: Python<'_>) -> PyResult<()> { + self.coroutine.close(self.operation()?, py) } fn wait(&self, py: Python<'_>) -> PyResult> { @@ -309,7 +599,7 @@ impl DynWinRTAsync { fn release(&mut self, py: Python<'_>) -> PyResult<()> { if let Some(operation) = &self.operation { - operation.release(py)?; + operation.stop(py)?; } self.operation = None; Ok(()) @@ -323,6 +613,7 @@ impl DynWinRTAsync { #[pyclass(name = "_DynWinRTAsyncWithProgress")] pub struct DynWinRTAsyncWithProgress { operation: Option>, + coroutine: CoroutineProtocol, progress_converter: Py, } @@ -354,12 +645,35 @@ impl DynWinRTAsyncWithProgress { } Ok(Self { operation: Some(operation), + coroutine: CoroutineProtocol::new(), progress_converter, }) } fn __await__<'py>(&self, py: Python<'py>) -> PyResult> { - self.operation()?.await_iter(py) + let operation = self.operation()?; + self.coroutine.ensure_awaitable()?; + operation.await_iter(py) + } + + fn send(&self, py: Python<'_>, value: Py) -> PyResult> { + self.coroutine.send(self.operation.as_deref(), py, value) + } + + #[pyo3(signature = (typ, value=None, traceback=None))] + fn throw( + &self, + py: Python<'_>, + typ: Py, + value: Option>, + traceback: Option>, + ) -> PyResult> { + self.coroutine + .throw(self.operation.as_deref(), py, typ, value, traceback) + } + + fn close(&self, py: Python<'_>) -> PyResult<()> { + self.coroutine.close(self.operation()?, py) } fn wait(&self, py: Python<'_>) -> PyResult> { @@ -372,7 +686,7 @@ impl DynWinRTAsyncWithProgress { fn release(&mut self, py: Python<'_>) -> PyResult<()> { if let Some(operation) = &self.operation { - operation.release(py)?; + operation.stop(py)?; } self.operation = None; Ok(()) diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 5fadc18c..7d673482 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -17,7 +17,9 @@ mod dynwinrt { super::async_runtime::init_async_runtime(); m.py().run( c" +from abc import abstractmethod as _abstractmethod from collections.abc import ( + Coroutine as _Coroutine, Iterable as _Iterable, Iterator as _Iterator, Mapping as _Mapping, @@ -30,8 +32,8 @@ from itertools import count as _count from contextvars import ContextVar as _ContextVar from operator import index as _index from threading import get_ident as _thread_get_ident -from typing import Protocol as _Protocol, TypeVar as _TypeVar -from typing import Awaitable as _Awaitable, Callable as _Callable +from types import TracebackType as _TracebackType +from typing import Any as _Any, Callable as _Callable, Generic as _Generic, TypeVar as _TypeVar from uuid import UUID as _UUID from weakref import WeakValueDictionary as _WeakValueDictionary @@ -39,12 +41,16 @@ _T = _TypeVar('_T', covariant=True) _P = _TypeVar('_P', covariant=True) _WINRT_EPOCH = _datetime(1601, 1, 1, tzinfo=_timezone.utc) -class WinRTAsync(_Awaitable[_T], _Protocol[_T]): +class WinRTAsync(_Coroutine[_Any, _Any, _T]): + @_abstractmethod def wait(self) -> _T: ... + @_abstractmethod def cancel(self) -> None: ... + @_abstractmethod def release(self) -> None: ... -class WinRTAsyncWithProgress(WinRTAsync[_T], _Protocol[_T, _P]): +class WinRTAsyncWithProgress(WinRTAsync[_T], _Generic[_T, _P]): + @_abstractmethod def progress(self, callback: _Callable[[_P], object]) -> None: ... _active_projected_lifetime_scope = _ContextVar( @@ -462,6 +468,23 @@ async def _dynwinrt_convert_future(future, converter): future.cancel() raise +async def _dynwinrt_drive_future(future): + return await future + +async def _dynwinrt_empty_coroutine(): + return None + +def _dynwinrt_validate_throw(typ, value, traceback): + if isinstance(typ, BaseException): + if value is not None: + raise TypeError('instance exception may not have a separate value') + elif not isinstance(typ, type) or not issubclass(typ, BaseException): + raise TypeError( + 'exceptions must be classes or instances deriving from BaseException' + ) + if traceback is not None and not isinstance(traceback, _TracebackType): + raise TypeError('throw() third argument must be a traceback object') + def _dynwinrt_link_cancellation(task, future): def cancel_inner(completed): if completed.cancelled() and not future.done(): @@ -491,6 +514,14 @@ def _dynwinrt_dispatch_progress(callback, converter, value): m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.py().run( + c" +WinRTAsync.register(_DynWinRTAsync) +WinRTAsyncWithProgress.register(_DynWinRTAsyncWithProgress) +", + Some(&m.dict()), + None, + )?; // Functions m.add_function(wrap_pyfunction!(super::runtime::init_winappsdk, m)?)?; diff --git a/bindings/py/tests/test_e2e_winrt.py b/bindings/py/tests/test_e2e_winrt.py index 18d0e6dd..2de40883 100644 --- a/bindings/py/tests/test_e2e_winrt.py +++ b/bindings/py/tests/test_e2e_winrt.py @@ -14,9 +14,14 @@ """ import asyncio +from collections.abc import Coroutine +import gc import http.server import threading import time +import weakref + +import pytest from dynwinrt import ( DynWinRTType, @@ -72,10 +77,13 @@ def do_GET(self): self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Connection", "close") self.end_headers() - for offset in range(0, len(payload), 8_192): - self.wfile.write(payload[offset : offset + 8_192]) - self.wfile.flush() - time.sleep(0.005) + try: + for offset in range(0, len(payload), 8_192): + self.wfile.write(payload[offset : offset + 8_192]) + self.wfile.flush() + time.sleep(0.005) + except (BrokenPipeError, ConnectionResetError): + pass self.close_connection = True def log_message(self, _format, *_args): @@ -644,7 +652,10 @@ def test_struct_progress_survives_asyncio_dispatch(self): ), [DynWinRTValue.from_hstring(url)], ) - operation = client_type.method(11).invoke(client.cast(client_iid), [uri]) + def create_operation(): + return client_type.method(11).invoke(client.cast(client_iid), [uri]) + + operation = create_operation() async def run_operation(): snapshots = [] @@ -670,11 +681,43 @@ def convert_progress(value): convert_progress, ) projected.progress(snapshots.append) - body = await projected + assert isinstance(projected, Coroutine) + body = await asyncio.create_task(projected) await asyncio.sleep(0.05) - return body, snapshots - body, snapshots = asyncio.run(run_operation()) + cancel_raw = create_operation() + cancel_projected = _DynWinRTAsyncWithProgress( + cancel_raw, + lambda value: value.to_string(), + convert_progress, + ) + progress_seen = asyncio.Event() + + class ProgressObserver: + def __call__(self, _value): + progress_seen.set() + + observer = ProgressObserver() + observer_ref = weakref.ref(observer) + cancel_projected.progress(observer) + cancel_task = asyncio.create_task(cancel_projected) + await asyncio.wait_for(progress_seen.wait(), timeout=5) + assert cancel_task.cancel() + with pytest.raises(asyncio.CancelledError): + await cancel_task + with pytest.raises(asyncio.CancelledError): + await cancel_projected + cancel_projected.release() + del observer, cancel_projected, cancel_task + await asyncio.sleep(0) + return body, snapshots, cancel_raw, observer_ref + + body, snapshots, cancel_raw, observer_ref = asyncio.run(run_operation()) + with pytest.raises(asyncio.CancelledError): + cancel_raw.wait() + cancel_raw.release() + gc.collect() + assert observer_ref() is None finally: server.shutdown() server.server_close() diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index 3152b552..973cc66b 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -14,10 +14,13 @@ """ import asyncio +from collections.abc import Coroutine from contextvars import copy_context from datetime import datetime, timedelta, timezone import gc +import inspect import threading +import warnings import weakref from types import SimpleNamespace @@ -177,7 +180,7 @@ def test_sync_hresult_maps_to_os_error_with_winerror(): assert exc_info.value.strerror -def _missing_storage_file_operation_value(path: str): +def _storage_file_operation_value(path: str): statics_iid = WinGUID.parse(IID_ISTORAGE_FILE_STATICS) storage_file_type = DynWinRTType.runtime_class( "Windows.Storage.StorageFile", @@ -204,7 +207,7 @@ def _missing_storage_file_operation_value(path: str): def _missing_storage_file_operation(path: str): return _DynWinRTAsync( - _missing_storage_file_operation_value(path), + _storage_file_operation_value(path), lambda value: value, ) @@ -232,6 +235,207 @@ def test_blocking_async_hresult_maps_to_os_error_with_winerror(tmp_path): assert exc_info.value.strerror +def test_async_wrapper_is_a_public_coroutine(tmp_path): + path = tmp_path / "dynwinrt-coroutine.txt" + path.write_text("coroutine") + operation = _DynWinRTAsync( + _storage_file_operation_value(str(path)), + lambda value: value, + ) + + assert inspect.isawaitable(operation) + assert asyncio.iscoroutine(operation) + assert isinstance(operation, Coroutine) + assert isinstance(operation, WinRTAsync) + operation.release() + + +def test_create_task_task_group_ensure_future_and_wait_for(tmp_path): + path = tmp_path / "dynwinrt-asyncio-entry-points.txt" + path.write_text("asyncio") + + def operation(): + return _DynWinRTAsync( + _storage_file_operation_value(str(path)), + lambda value: value, + ) + + async def run_operations(): + create_task_operation = operation() + with pytest.raises( + TypeError, + match="can't send non-None value to a just-started coroutine", + ): + create_task_operation.send(1) + created = asyncio.create_task(create_task_operation) + created_result = await created + assert await create_task_operation is created_result + + ensured_result = await asyncio.ensure_future(operation()) + waited_result = await asyncio.wait_for(operation(), timeout=5) + + async with asyncio.TaskGroup() as group: + grouped = group.create_task(operation()) + + assert not created_result.is_null() + assert not ensured_result.is_null() + assert not waited_result.is_null() + assert not grouped.result().is_null() + + asyncio.run(run_operations()) + + +def test_task_driver_is_one_shot_but_direct_await_remains_repeatable(tmp_path): + path = tmp_path / "dynwinrt-repeated-await.txt" + path.write_text("repeat") + operation = _DynWinRTAsync( + _storage_file_operation_value(str(path)), + lambda value: value, + ) + + async def run_operation(): + first = await asyncio.create_task(operation) + second = await operation + assert second is first + + repeated_task = asyncio.create_task(operation) + with pytest.raises( + RuntimeError, + match="cannot reuse already awaited WinRT async coroutine", + ): + await repeated_task + + assert await operation is first + + asyncio.run(run_operation()) + + +def test_task_failure_remains_repeatable_for_direct_await(tmp_path): + path = tmp_path / "dynwinrt-repeated-failure.txt" + path.write_text("failure") + conversions = 0 + + def fail_once(value): + nonlocal conversions + conversions += 1 + if conversions == 1: + raise LookupError("conversion failed") + return value + + operation = _DynWinRTAsync( + _storage_file_operation_value(str(path)), + fail_once, + ) + + async def run_operation(): + with pytest.raises(LookupError, match="conversion failed"): + await asyncio.create_task(operation) + with pytest.raises(LookupError, match="conversion failed"): + await operation + + asyncio.run(run_operation()) + assert conversions == 1 + + +def test_concurrent_task_attempt_is_rejected_without_hiding_winrt_failure(tmp_path): + operation = _missing_storage_file_operation( + str(tmp_path / "missing-concurrent-dynwinrt-file") + ) + + async def run_operation(): + first = asyncio.create_task(operation) + concurrent = asyncio.create_task(operation) + results = await asyncio.gather(first, concurrent, return_exceptions=True) + + assert isinstance(results[0], OSError) + assert results[0].winerror == -2147024894 + assert isinstance(results[1], RuntimeError) + assert "already being awaited by another task" in str(results[1]) + + asyncio.run(run_operation()) + + +def test_invalid_throw_does_not_consume_or_leak_coroutine(tmp_path): + path = tmp_path / "dynwinrt-invalid-throw.txt" + path.write_text("throw") + operation = _DynWinRTAsync( + _storage_file_operation_value(str(path)), + lambda value: value, + ) + + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + with pytest.raises( + TypeError, + match="exceptions must be classes or instances deriving from BaseException", + ): + operation.throw(123) + gc.collect() + + async def run_operation(): + assert not (await asyncio.create_task(operation)).is_null() + + asyncio.run(run_operation()) + + +def test_release_preserves_owning_task_cancellation(tmp_path): + path = tmp_path / "dynwinrt-release-cancellation.txt" + path.write_text("release") + operation = _DynWinRTAsync( + _storage_file_operation_value(str(path)), + lambda value: value, + ) + + async def run_operation(): + task = asyncio.create_task(operation) + await asyncio.sleep(0) + task.cancel() + operation.release() + with pytest.raises(asyncio.CancelledError): + await task + + asyncio.run(run_operation()) + + +def test_release_before_task_start_preserves_cancellation(tmp_path): + path = tmp_path / "dynwinrt-release-before-start.txt" + path.write_text("release") + operation = _DynWinRTAsync( + _storage_file_operation_value(str(path)), + lambda value: value, + ) + + async def run_operation(): + task = asyncio.create_task(operation) + task.cancel() + operation.release() + with pytest.raises(asyncio.CancelledError): + await task + + asyncio.run(run_operation()) + + +def test_close_is_idempotent_and_prevents_future_execution(tmp_path): + operation = _missing_storage_file_operation( + str(tmp_path / "missing-closed-dynwinrt-file") + ) + operation.close() + operation.close() + + async def run_operation(): + with pytest.raises(RuntimeError, match="closed WinRT async coroutine"): + await operation + task = asyncio.create_task(operation) + with pytest.raises( + RuntimeError, + match="cannot reuse already awaited WinRT async coroutine", + ): + await task + + asyncio.run(run_operation()) + operation.release() + + # ---------------------------------------------------------------------- # DynWinRTValue.cancel # ---------------------------------------------------------------------- @@ -267,7 +471,7 @@ def test_progress_wrapper_rejects_non_async_value(): def test_progress_wrapper_rejects_async_operation_without_progress(tmp_path): - raw_operation = _missing_storage_file_operation_value( + raw_operation = _storage_file_operation_value( str(tmp_path / "missing-dynwinrt-progress-file") ) with pytest.raises( diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index 59f2c6a6..f61e8daa 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -1013,8 +1013,25 @@ def fail(*_args): if not inspect.isawaitable(store_op): cr['error'] = 'store_async() did not return an awaitable' return cr - stored = await store_op + if not asyncio.iscoroutine(store_op): + cr['error'] = 'store_async() did not return a coroutine' + return cr + stored = await asyncio.create_task(store_op) stored_again = await store_op + try: + await asyncio.create_task(store_op) + cr['error'] = 'completed async operation was accepted by create_task twice' + return cr + except RuntimeError as error: + if 'cannot reuse already awaited WinRT async coroutine' not in str(error): + cr['error'] = f'unexpected repeated create_task error: {error}' + return cr + + writer.write_int32(write_val) + grouped_op = writer.store_async() + async with asyncio.TaskGroup() as group: + grouped_task = group.create_task(grouped_op) + grouped = grouped_task.result() stream.seek(0) reader = reader_cls.create_data_reader(stream.get_input_stream_at(0)) @@ -1149,6 +1166,7 @@ def progress_without_loop(): if ( stored < 4 or stored_again != stored + or grouped < 4 or loaded < 4 or blocked < 4 or read_val != write_val diff --git a/tests/e2e/typecheck/python_generated_api.py b/tests/e2e/typecheck/python_generated_api.py index 63a2758e..4765b730 100644 --- a/tests/e2e/typecheck/python_generated_api.py +++ b/tests/e2e/typecheck/python_generated_api.py @@ -1,8 +1,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -from collections.abc import Sequence -from typing import Awaitable, List, Tuple +import asyncio +from collections.abc import Coroutine, Sequence +from typing import Any, Awaitable, List, Tuple from dynwinrt import ( DynWinRTArray, @@ -91,10 +92,19 @@ def check_async_types( ) -> None: store: WinRTAsync[int] = writer.store_async() awaitable: Awaitable[int] = store + coroutine: Coroutine[Any, Any, int] = store + task: asyncio.Task[int] = asyncio.create_task(store) write: WinRTAsyncWithProgress[int, int] = output.write_async(buffer) write.progress(lambda value: value) progress_awaitable: Awaitable[int] = write - _: Tuple[Awaitable[int], Awaitable[int]] = (awaitable, progress_awaitable) + progress_task: asyncio.Task[int] = asyncio.TaskGroup().create_task(write) + _: Tuple[ + Awaitable[int], + Coroutine[Any, Any, int], + asyncio.Task[int], + Awaitable[int], + asyncio.Task[int], + ] = (awaitable, coroutine, task, progress_awaitable, progress_task) def check_ibuffer_bytes() -> None: From d0a3b9cb9795ebdef5631bfa805a5b0b115774ac Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Thu, 3 Sep 2026 00:15:18 +0800 Subject: [PATCH 2/4] Fix never-started async throw semantics Handle throw injection before asyncio owner resolution, close the coroutine protocol synchronously, and preserve WinRT cancellation cleanup failures. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/src/async_runtime.rs | 89 ++++++++++++++++++++++---------- bindings/py/tests/test_phase1.py | 39 ++++++++++++++ 2 files changed, 100 insertions(+), 28 deletions(-) diff --git a/bindings/py/src/async_runtime.rs b/bindings/py/src/async_runtime.rs index ade9bc72..0ea26328 100644 --- a/bindings/py/src/async_runtime.rs +++ b/bindings/py/src/async_runtime.rs @@ -302,35 +302,30 @@ impl CoroutineProtocol { .getattr("_dynwinrt_validate_throw")? .call1((typ.clone_ref(py), validation_value, validation_traceback))?; - if operation.is_none() && matches!(*self.lock_state()?, CoroutineExecutionState::New) { - let coroutine = py + let was_new = { + let mut state = self.lock_state()?; + if matches!(*state, CoroutineExecutionState::New) { + *state = CoroutineExecutionState::Closed; + true + } else { + false + } + }; + if was_new { + let result = py .import("dynwinrt.dynwinrt")? .getattr("_dynwinrt_empty_coroutine")? - .call0()?; - return match (value, traceback) { - (None, None) => coroutine.call_method1("throw", (typ,)).map(Bound::unbind), - (Some(value), None) => coroutine - .call_method1("throw", (typ, value)) - .map(Bound::unbind), - (value, Some(traceback)) => coroutine - .call_method1( - "throw", - (typ, value.unwrap_or_else(|| py.None()), traceback), - ) - .map(Bound::unbind), + .call0() + .and_then(|coroutine| throw_into_coroutine(py, &coroutine, typ, value, traceback)); + let cleanup_result = match operation { + Some(operation) => operation.stop(py), + None => Ok(()), }; + return finish_with_cleanup(py, result, cleanup_result); } let (owner, coroutine) = self.begin_call(operation, py, false)?; - let result = match (value, traceback) { - (None, None) => coroutine.call_method1(py, "throw", (typ,)), - (Some(value), None) => coroutine.call_method1(py, "throw", (typ, value)), - (value, Some(traceback)) => coroutine.call_method1( - py, - "throw", - (typ, value.unwrap_or_else(|| py.None()), traceback), - ), - }; + let result = throw_into_coroutine(py, coroutine.bind(py), typ, value, traceback); self.finish_call(py, owner, coroutine, &result)?; if let Err(primary_error) = &result { if let Some(operation) = operation { @@ -385,6 +380,43 @@ impl CoroutineProtocol { } } +fn throw_into_coroutine( + py: Python<'_>, + coroutine: &Bound<'_, PyAny>, + typ: Py, + value: Option>, + traceback: Option>, +) -> PyResult> { + match (value, traceback) { + (None, None) => coroutine.call_method1("throw", (typ,)).map(Bound::unbind), + (Some(value), None) => coroutine + .call_method1("throw", (typ, value)) + .map(Bound::unbind), + (value, Some(traceback)) => coroutine + .call_method1( + "throw", + (typ, value.unwrap_or_else(|| py.None()), traceback), + ) + .map(Bound::unbind), + } +} + +fn finish_with_cleanup( + py: Python<'_>, + result: PyResult, + cleanup_result: PyResult<()>, +) -> PyResult { + match (result, cleanup_result) { + (Ok(value), Ok(())) => Ok(value), + (Ok(_), Err(cleanup_error)) => Err(cleanup_error), + (Err(primary_error), Ok(())) => Err(primary_error), + (Err(primary_error), Err(cleanup_error)) => { + append_cleanup_error(py, &primary_error, &cleanup_error)?; + Err(primary_error) + } + } +} + fn append_cleanup_error(py: Python<'_>, primary: &PyErr, cleanup: &PyErr) -> PyResult<()> { py.import("dynwinrt.dynwinrt")? .getattr("_dynwinrt_append_exception_cause")? @@ -415,7 +447,7 @@ impl AsyncOperation { } fn stop(&self, py: Python<'_>) -> PyResult<()> { - let _ = self.cancel(); + let cancel_result = self.cancel(); let future = { let mut state = self.lock_state()?; match std::mem::replace(&mut *state, ExecutionState::Idle) { @@ -423,10 +455,11 @@ impl AsyncOperation { ExecutionState::Idle | ExecutionState::Blocking => None, } }; - if let Some(future) = future { - future.call_method0(py, "cancel")?; - } - Ok(()) + let future_result = match future { + Some(future) => future.call_method0(py, "cancel").map(|_| ()), + None => Ok(()), + }; + finish_with_cleanup(py, cancel_result, future_result) } fn future_is_done(&self, py: Python<'_>) -> PyResult { diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index 973cc66b..185d8702 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -378,6 +378,45 @@ async def run_operation(): asyncio.run(run_operation()) +@pytest.mark.parametrize( + ("throw_args", "message"), + [ + ((ValueError("injected"),), "injected"), + ((ValueError, "legacy injection"), "legacy injection"), + ], +) +def test_throw_before_start_is_synchronous_and_closes_coroutine( + tmp_path, throw_args, message +): + path = tmp_path / f"dynwinrt-new-throw-{len(throw_args)}.txt" + path.write_text("throw") + operation = _DynWinRTAsync( + _storage_file_operation_value(str(path)), + lambda value: value, + ) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + with pytest.raises(ValueError, match=message): + operation.throw(*throw_args) + + operation.close() + operation.close() + with pytest.raises(RuntimeError, match="closed WinRT async coroutine"): + operation.__await__() + + async def reject_reuse(): + task = asyncio.create_task(operation) + with pytest.raises( + RuntimeError, + match="cannot reuse already awaited WinRT async coroutine", + ): + await task + + asyncio.run(reject_reuse()) + operation.release() + + def test_release_preserves_owning_task_cancellation(tmp_path): path = tmp_path / "dynwinrt-release-cancellation.txt" path.write_text("release") From 9778588b6192e308f986850d7e11828279e00b90 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Thu, 3 Sep 2026 11:13:22 +0800 Subject: [PATCH 3/4] Restore structural Python async protocols Keep the existing WinRTAsync contracts structurally compatible while exposing dedicated coroutine return protocols for generated asyncio task inputs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/README.md | 7 ++- bindings/py/dynwinrt.pyi | 25 ++++++---- bindings/py/src/lib.rs | 36 ++++++++++---- bindings/py/tests/test_phase1.py | 8 +++- tests/e2e/typecheck/python_generated_api.py | 47 +++++++++++++++++-- .../src/codegen/winrt/python/generator/mod.rs | 2 +- .../src/codegen/winrt/python/method.rs | 4 +- .../src/codegen/winrt/python/stubs.rs | 2 +- .../src/codegen/winrt/python/type_helpers.rs | 22 ++++----- .../tests/delegate_dependency_closure_test.rs | 8 ++-- .../tests/ireference_struct_field_test.rs | 2 +- .../snapshots/data_writer_py/data_writer.py | 6 +-- 12 files changed, 120 insertions(+), 49 deletions(-) diff --git a/bindings/py/README.md b/bindings/py/README.md index 7e1112ae..53e0db51 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -34,8 +34,11 @@ async with asyncio.TaskGroup() as group: task = group.create_task(writer.store_async()) ``` -Their public types are `WinRTAsync[T]` and -`WinRTAsyncWithProgress[T, P]`; the concrete runtime wrappers remain private. +Generated methods return `WinRTCoroutine[T]` and +`WinRTCoroutineWithProgress[T, P]`, which retain the structural +`WinRTAsync[T]` and `WinRTAsyncWithProgress[T, P]` contracts while also being +typed as coroutines for `asyncio.create_task()`. The concrete runtime wrappers +remain private. Regenerated bindings no longer block inside async methods. Existing code that expects an immediate result must use `await operation` or `operation.wait()`. diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index dcec08f1..0b8a8184 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -1,6 +1,5 @@ -from abc import ABCMeta, abstractmethod from collections.abc import Coroutine -from typing import Any, Callable, Generic, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload +from typing import Any, Awaitable, Callable, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload from uuid import UUID _T = TypeVar("_T", covariant=True) @@ -37,6 +36,8 @@ __all__ = [ "DynWinRtElementFactory", "WinRTAsync", "WinRTAsyncWithProgress", + "WinRTCoroutine", + "WinRTCoroutineWithProgress", "ProjectedLifetimeScope", "projected_lifetime_scope", "project_as", @@ -380,20 +381,28 @@ class DynWinRTValue: def __str__(self) -> str: ... -class WinRTAsync(Coroutine[Any, Any, _T], metaclass=ABCMeta): - @abstractmethod +class WinRTAsync(Awaitable[_T], Protocol[_T]): def wait(self) -> _T: ... - @abstractmethod def cancel(self) -> None: ... - @abstractmethod def release(self) -> None: ... -class WinRTAsyncWithProgress(WinRTAsync[_T], Generic[_T, _P], metaclass=ABCMeta): - @abstractmethod +class WinRTAsyncWithProgress(WinRTAsync[_T], Protocol[_T, _P]): def progress(self, callback: Callable[[_P], object]) -> None: ... +class WinRTCoroutine( # type: ignore[misc] + WinRTAsync[_T], Coroutine[Any, Any, _T], Protocol[_T] +): ... + + +class WinRTCoroutineWithProgress( + WinRTAsyncWithProgress[_T, _P], + WinRTCoroutine[_T], + Protocol[_T, _P], +): ... + + @final class DynWinRTArray: def __len__(self) -> int: ... diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 7d673482..701266ff 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -17,7 +17,6 @@ mod dynwinrt { super::async_runtime::init_async_runtime(); m.py().run( c" -from abc import abstractmethod as _abstractmethod from collections.abc import ( Coroutine as _Coroutine, Iterable as _Iterable, @@ -33,7 +32,8 @@ from contextvars import ContextVar as _ContextVar from operator import index as _index from threading import get_ident as _thread_get_ident from types import TracebackType as _TracebackType -from typing import Any as _Any, Callable as _Callable, Generic as _Generic, TypeVar as _TypeVar +from typing import Any as _Any, Awaitable as _Awaitable, Callable as _Callable +from typing import Protocol as _Protocol, TypeVar as _TypeVar from uuid import UUID as _UUID from weakref import WeakValueDictionary as _WeakValueDictionary @@ -41,18 +41,32 @@ _T = _TypeVar('_T', covariant=True) _P = _TypeVar('_P', covariant=True) _WINRT_EPOCH = _datetime(1601, 1, 1, tzinfo=_timezone.utc) -class WinRTAsync(_Coroutine[_Any, _Any, _T]): - @_abstractmethod +class WinRTAsync(_Awaitable[_T], _Protocol[_T]): def wait(self) -> _T: ... - @_abstractmethod def cancel(self) -> None: ... - @_abstractmethod def release(self) -> None: ... -class WinRTAsyncWithProgress(WinRTAsync[_T], _Generic[_T, _P]): - @_abstractmethod +class WinRTAsyncWithProgress(WinRTAsync[_T], _Protocol[_T, _P]): def progress(self, callback: _Callable[[_P], object]) -> None: ... +class WinRTCoroutine(WinRTAsync[_T], _Protocol[_T]): + def send(self, value: _Any, /) -> _Any: ... + def throw( + self, + typ: type[BaseException] | BaseException, + val: _Any = None, + tb: _TracebackType | None = None, + /, + ) -> _Any: ... + def close(self) -> None: ... + +class WinRTCoroutineWithProgress( + WinRTAsyncWithProgress[_T, _P], + WinRTCoroutine[_T], + _Protocol[_T, _P], +): + pass + _active_projected_lifetime_scope = _ContextVar( 'dynwinrt_active_projected_lifetime_scope', default=None, @@ -516,8 +530,8 @@ def _dynwinrt_dispatch_progress(callback, converter, value): m.add_class::()?; m.py().run( c" -WinRTAsync.register(_DynWinRTAsync) -WinRTAsyncWithProgress.register(_DynWinRTAsyncWithProgress) +_Coroutine.register(_DynWinRTAsync) +_Coroutine.register(_DynWinRTAsyncWithProgress) ", Some(&m.dict()), None, @@ -544,6 +558,8 @@ __all__ = [name for name in __all__ if not name.startswith('_')] for _name in ( 'WinRTAsync', 'WinRTAsyncWithProgress', + 'WinRTCoroutine', + 'WinRTCoroutineWithProgress', 'ProjectedLifetimeScope', 'projected_lifetime_scope', 'project_as', diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index 185d8702..20c9af2e 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -7,7 +7,8 @@ Covers: * DynWinRTMethodHandle.invoke_all — multi-out-parameter invocation * DynWinRTValue.cancel — IAsyncInfo::Cancel - * WinRTAsync — public asyncio-compatible protocols + * WinRTAsync — public structural async protocols + * WinRTCoroutine — asyncio-compatible return protocols * DynWinRTArray.to_bytes/from_bytes — Pythonic byte-buffer interop * DynWinRTArray.from_object_values — T[] of object/interface elements * DynWinRTValue.to_bytes/from_bytes — copied IBuffer interop @@ -42,6 +43,8 @@ release_projected, WinRTAsync, WinRTAsyncWithProgress, + WinRTCoroutine, + WinRTCoroutineWithProgress, WinGUID, ro_initialize, register_xaml_runtime_class, @@ -246,7 +249,6 @@ def test_async_wrapper_is_a_public_coroutine(tmp_path): assert inspect.isawaitable(operation) assert asyncio.iscoroutine(operation) assert isinstance(operation, Coroutine) - assert isinstance(operation, WinRTAsync) operation.release() @@ -1029,6 +1031,8 @@ def __del__(self): def test_async_protocols_are_public(): assert WinRTAsync.__name__ == "WinRTAsync" assert WinRTAsyncWithProgress.__name__ == "WinRTAsyncWithProgress" + assert WinRTCoroutine.__name__ == "WinRTCoroutine" + assert WinRTCoroutineWithProgress.__name__ == "WinRTCoroutineWithProgress" assert not hasattr(dynwinrt, "_DynWinRTAsync") diff --git a/tests/e2e/typecheck/python_generated_api.py b/tests/e2e/typecheck/python_generated_api.py index 4765b730..3902d0c9 100644 --- a/tests/e2e/typecheck/python_generated_api.py +++ b/tests/e2e/typecheck/python_generated_api.py @@ -2,13 +2,15 @@ # Licensed under the MIT License. import asyncio -from collections.abc import Coroutine, Sequence +from collections.abc import Coroutine, Generator, Sequence from typing import Any, Awaitable, List, Tuple from dynwinrt import ( DynWinRTArray, WinRTAsync, WinRTAsyncWithProgress, + WinRTCoroutine, + WinRTCoroutineWithProgress, DynWinRTMethodSig, DynWinRTType, DynWinRTValue, @@ -29,6 +31,28 @@ ) +class StructuralAsyncAdapter: + def __await__(self) -> Generator[None, None, int]: + if False: + yield None + return self.wait() + + def wait(self) -> int: + return 1 + + def cancel(self) -> None: + pass + + def release(self) -> None: + pass + + +def check_structural_async_compatibility() -> None: + adapter: WinRTAsync[int] = StructuralAsyncAdapter() + awaitable: Awaitable[int] = adapter + _: Tuple[WinRTAsync[int], Awaitable[int]] = (adapter, awaitable) + + def check_runtime_stubs() -> None: iid: WinGUID = WinGUID.parse("00000000-0000-0000-c000-000000000046") interface: DynWinRTType = DynWinRTType.register_interface("IUnknown", iid) @@ -90,21 +114,36 @@ def check_async_types( output: IOutputStream, buffer: IBuffer, ) -> None: - store: WinRTAsync[int] = writer.store_async() + store: WinRTCoroutine[int] = writer.store_async() + legacy_store: WinRTAsync[int] = store awaitable: Awaitable[int] = store coroutine: Coroutine[Any, Any, int] = store task: asyncio.Task[int] = asyncio.create_task(store) - write: WinRTAsyncWithProgress[int, int] = output.write_async(buffer) + write: WinRTCoroutineWithProgress[int, int] = output.write_async(buffer) + legacy_write: WinRTAsyncWithProgress[int, int] = write write.progress(lambda value: value) progress_awaitable: Awaitable[int] = write + progress_coroutine: Coroutine[Any, Any, int] = write progress_task: asyncio.Task[int] = asyncio.TaskGroup().create_task(write) _: Tuple[ + WinRTAsync[int], Awaitable[int], Coroutine[Any, Any, int], asyncio.Task[int], + WinRTAsyncWithProgress[int, int], Awaitable[int], + Coroutine[Any, Any, int], asyncio.Task[int], - ] = (awaitable, coroutine, task, progress_awaitable, progress_task) + ] = ( + legacy_store, + awaitable, + coroutine, + task, + legacy_write, + progress_awaitable, + progress_coroutine, + progress_task, + ) def check_ibuffer_bytes() -> None: 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 ceba1796..704addde 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -129,7 +129,7 @@ pub fn generate_runtime_support_module() -> String { } const ASYNC_IMPORT_LINE: &str = "\ -from dynwinrt import WinRTAsync, WinRTAsyncWithProgress +from dynwinrt import WinRTCoroutine, WinRTCoroutineWithProgress from dynwinrt.dynwinrt import _DynWinRTAsync, _DynWinRTAsyncWithProgress "; diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs index d30f08f9..8c4bcd1d 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs @@ -1026,7 +1026,7 @@ mod tests { true, ); - assert!(code.contains("def load_async(self) -> WinRTAsync[int]:")); + assert!(code.contains("def load_async(self) -> WinRTCoroutine[int]:")); assert!(code.contains("return _dynwinrt_track_projected(_DynWinRTAsync(")); assert!(code.contains("'WinRTAsync')")); assert!(code.contains("lambda value: value.to_u32()")); @@ -1062,7 +1062,7 @@ mod tests { ); assert!(code.contains( - "def write_async(self, buffer: 'DynWinRTValue') -> WinRTAsyncWithProgress[int, int]:" + "def write_async(self, buffer: 'DynWinRTValue') -> WinRTCoroutineWithProgress[int, int]:" )); assert!(code.contains("return _dynwinrt_track_projected(_DynWinRTAsyncWithProgress(")); assert!(code.contains("'WinRTAsyncWithProgress')")); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index a9aebc17..0987b796 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -46,7 +46,7 @@ from ._typing import ( DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, _DynWinRTProjector, )\n"; -const ASYNC_IMPORT_LINE: &str = "from dynwinrt import WinRTAsync, WinRTAsyncWithProgress\n"; +const ASYNC_IMPORT_LINE: &str = "from dynwinrt import WinRTCoroutine, WinRTCoroutineWithProgress\n"; pub fn generate_typing_support_module() -> String { format!( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs index e04113a1..950cd4da 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs @@ -174,17 +174,17 @@ fn py_async_return_type_with_result( context: &PythonProjectionContext, ) -> Option { match typ { - TypeMeta::AsyncAction => Some("WinRTAsync[None]".to_string()), + TypeMeta::AsyncAction => Some("WinRTCoroutine[None]".to_string()), TypeMeta::AsyncOperation(result) => Some(format!( - "WinRTAsync[{}]", + "WinRTCoroutine[{}]", result_override.unwrap_or_else(|| py_return_type_safe(Some(result), context)) )), TypeMeta::AsyncActionWithProgress(progress) => Some(format!( - "WinRTAsyncWithProgress[None, {}]", + "WinRTCoroutineWithProgress[None, {}]", py_return_type_safe(Some(progress), context) )), TypeMeta::AsyncOperationWithProgress(result, progress) => Some(format!( - "WinRTAsyncWithProgress[{}, {}]", + "WinRTCoroutineWithProgress[{}, {}]", result_override.unwrap_or_else(|| py_return_type_safe(Some(result), context)), py_return_type_safe(Some(progress), context) )), @@ -270,15 +270,15 @@ pub(super) fn py_output_type(typ: &TypeMeta, context: &PythonProjectionContext) "list[DynWinRTValue | None]".to_string() } TypeMeta::AsyncOperation(inner) => { - format!("WinRTAsync[{}]", py_output_type(inner, context)) + format!("WinRTCoroutine[{}]", py_output_type(inner, context)) } TypeMeta::AsyncOperationWithProgress(result, progress) => format!( - "WinRTAsyncWithProgress[{}, {}]", + "WinRTCoroutineWithProgress[{}, {}]", py_output_type(result, context), py_output_type(progress, context) ), TypeMeta::AsyncActionWithProgress(progress) => format!( - "WinRTAsyncWithProgress[None, {}]", + "WinRTCoroutineWithProgress[None, {}]", py_output_type(progress, context) ), _ => py_return_type_safe(Some(typ), context), @@ -330,16 +330,16 @@ fn py_return_type(typ: Option<&TypeMeta>, context: &PythonProjectionContext) -> format!("'{}'", context.reference_name_for_type(typ)) } Some(TypeMeta::AsyncOperation(inner)) => { - format!("WinRTAsync[{}]", py_return_type(Some(inner), context)) + format!("WinRTCoroutine[{}]", py_return_type(Some(inner), context)) } Some(TypeMeta::AsyncOperationWithProgress(result, progress)) => format!( - "WinRTAsyncWithProgress[{}, {}]", + "WinRTCoroutineWithProgress[{}, {}]", py_return_type(Some(result), context), py_return_type(Some(progress), context) ), - Some(TypeMeta::AsyncAction) => "WinRTAsync[None]".to_string(), + Some(TypeMeta::AsyncAction) => "WinRTCoroutine[None]".to_string(), Some(TypeMeta::AsyncActionWithProgress(progress)) => format!( - "WinRTAsyncWithProgress[None, {}]", + "WinRTCoroutineWithProgress[None, {}]", py_return_type(Some(progress), context) ), Some(TypeMeta::Array(inner)) => py_array_return_type(inner, context), diff --git a/tools/dynwinrt-codegen/tests/delegate_dependency_closure_test.rs b/tools/dynwinrt-codegen/tests/delegate_dependency_closure_test.rs index 91552c21..df26c315 100644 --- a/tools/dynwinrt-codegen/tests/delegate_dependency_closure_test.rs +++ b/tools/dynwinrt-codegen/tests/delegate_dependency_closure_test.rs @@ -163,16 +163,16 @@ fn generated_interfaces_import_only_runtime_delegates() { "{dts}", ); assert!( - py.contains("WinRTAsync[list[DynWinRTValue | None]]",) + py.contains("WinRTCoroutine[list[DynWinRTValue | None]]",) && py.contains("value.as_array().to_values()",) && py.contains("def callbacks(self) -> list[DynWinRTValue | None]:",) - && !py.contains("WinRTAsync[list[AsyncHandler | None]]",), + && !py.contains("WinRTCoroutine[list[AsyncHandler | None]]",), "{py}", ); assert!( - pyi.contains("WinRTAsync[list[DynWinRTValue | None]]",) + pyi.contains("WinRTCoroutine[list[DynWinRTValue | None]]",) && pyi.contains("def callbacks(self) -> list[DynWinRTValue | None]:",) - && !pyi.contains("WinRTAsync[list[AsyncHandler | None]]",), + && !pyi.contains("WinRTCoroutine[list[AsyncHandler | None]]",), "{pyi}", ); } diff --git a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs index 00c10f94..f1eb5ac2 100644 --- a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs +++ b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs @@ -454,7 +454,7 @@ fn sdk_http_progress_ireference_u64_fields_are_native_optional_values() { ); assert!( py.contains("lambda value: _unpack_http_progress(value)") - && pyi.contains("WinRTAsyncWithProgress[str, 'HttpProgress']"), + && pyi.contains("WinRTCoroutineWithProgress[str, 'HttpProgress']"), "Python struct progress projection was not preserved:\n{py}\n{pyi}" ); } diff --git a/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py b/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py index 89f256ed..281623ce 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py +++ b/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py @@ -14,7 +14,7 @@ _dynwinrt_symbol, _dynwinrt_track_projected, _dynwinrt_uuid, _dynwinrt_vector, _dynwinrt_wrap_values, ) -from dynwinrt import WinRTAsync, WinRTAsyncWithProgress +from dynwinrt import WinRTCoroutine, WinRTCoroutineWithProgress from dynwinrt.dynwinrt import _DynWinRTAsync, _DynWinRTAsyncWithProgress if TYPE_CHECKING: @@ -216,10 +216,10 @@ def write_string(self, value: str) -> int: def measure_string(self, value: str) -> int: return _IDataWriter.method(28).invoke(self._obj, [DynWinRTValue.from_hstring(value)]).to_u32() - def store_async(self) -> WinRTAsync[int]: + def store_async(self) -> WinRTCoroutine[int]: return _dynwinrt_track_projected(_DynWinRTAsync(_IDataWriter.method(29).invoke(self._obj, []), lambda value: value.to_u32()), 'WinRTAsync') - def flush_async(self) -> WinRTAsync[bool]: + def flush_async(self) -> WinRTCoroutine[bool]: return _dynwinrt_track_projected(_DynWinRTAsync(_IDataWriter.method(30).invoke(self._obj, []), lambda value: value.to_bool()), 'WinRTAsync') def detach_buffer(self) -> IBuffer | None: From 2de5d8e16831ec5052f4175e2cc4d0f2217af2ac Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Thu, 3 Sep 2026 15:37:53 +0800 Subject: [PATCH 4/4] Fix Python async progress callback teardown Deactivate native and queued progress dispatch captures when coroutine execution finishes, is cancelled, or is released so late WinRT callbacks cannot retain observers or target a closed event loop. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/src/async_runtime.rs | 164 +++++++++++++++++++++------- bindings/py/src/lib.rs | 6 +- bindings/py/tests/test_e2e_winrt.py | 2 + bindings/py/tests/test_phase1.py | 6 +- 4 files changed, 132 insertions(+), 46 deletions(-) diff --git a/bindings/py/src/async_runtime.rs b/bindings/py/src/async_runtime.rs index 0ea26328..c2943997 100644 --- a/bindings/py/src/async_runtime.rs +++ b/bindings/py/src/async_runtime.rs @@ -11,6 +11,7 @@ use crate::errors::{ use crate::runtime::DynWinRTValue; use pyo3::exceptions::{PyRuntimeError, PyTypeError}; use pyo3::prelude::*; +use pyo3::types::PyList; use windows::Win32::Foundation::CO_E_NOTINITIALIZED; use windows::Win32::System::Com::{ APTTYPE_CURRENT, APTTYPE_MAINSTA, APTTYPE_STA, APTTYPEQUALIFIER, APTTYPEQUALIFIER_NONE, @@ -279,7 +280,11 @@ impl CoroutineProtocol { let (owner, coroutine) = self.begin_call(operation, py, require_started)?; let result = coroutine.call_method1(py, "send", (value,)); self.finish_call(py, owner, coroutine, &result)?; - result + let cleanup_result = match operation { + Some(operation) if result.is_err() => operation.clear_progress_dispatcher(py), + _ => Ok(()), + }; + finish_with_cleanup(py, result, cleanup_result) } fn throw( @@ -329,10 +334,15 @@ impl CoroutineProtocol { self.finish_call(py, owner, coroutine, &result)?; if let Err(primary_error) = &result { if let Some(operation) = operation { - if !operation.future_is_done(py)? { - if let Err(cleanup_error) = operation.stop(py) { - append_cleanup_error(py, primary_error, &cleanup_error)?; - } + let progress_result = operation.clear_progress_dispatcher(py); + let stop_result = match operation.future_is_done(py) { + Ok(true) => Ok(()), + Ok(false) => operation.stop(py), + Err(error) => Err(error), + }; + let cleanup_result = finish_with_cleanup(py, stop_result, progress_result); + if let Err(cleanup_error) = cleanup_result { + append_cleanup_error(py, primary_error, &cleanup_error)?; } } } @@ -428,6 +438,42 @@ struct AsyncOperation { value: dynwinrt::WinRTValue, converter: Py, state: Mutex, + progress_dispatcher: Mutex>>, +} + +struct ProgressDispatcher { + event_loop: Py, + // Loop handles retain this list, which is cleared to release captures and disable queued work. + dispatch_state: Py, + dispatch_progress: Py, + callback_context: Py, +} + +impl ProgressDispatcher { + fn deactivate(&self, py: Python<'_>) -> PyResult<()> { + self.dispatch_state.call_method0(py, "clear").map(|_| ()) + } + + fn dispatch(&self, py: Python<'_>, value: dynwinrt::WinRTValue) -> PyResult<()> { + if self.event_loop.call_method0(py, "is_closed")?.extract(py)? { + return Ok(()); + } + + let raw = Py::new(py, DynWinRTValue(value))?; + let context = self.callback_context.call_method0(py, "copy")?; + let context_run = context.getattr(py, "run")?; + self.event_loop.call_method1( + py, + "call_soon_threadsafe", + ( + context_run, + self.dispatch_progress.clone_ref(py), + self.dispatch_state.clone_ref(py), + raw, + ), + )?; + Ok(()) + } } impl AsyncOperation { @@ -437,6 +483,7 @@ impl AsyncOperation { value: value.0.clone(), converter, state: Mutex::new(ExecutionState::Idle), + progress_dispatcher: Mutex::new(None), }) } @@ -447,6 +494,7 @@ impl AsyncOperation { } fn stop(&self, py: Python<'_>) -> PyResult<()> { + let progress_result = self.clear_progress_dispatcher(py); let cancel_result = self.cancel(); let future = { let mut state = self.lock_state()?; @@ -459,7 +507,36 @@ impl AsyncOperation { Some(future) => future.call_method0(py, "cancel").map(|_| ()), None => Ok(()), }; - finish_with_cleanup(py, cancel_result, future_result) + let cancel_result = finish_with_cleanup(py, cancel_result, future_result); + finish_with_cleanup(py, cancel_result, progress_result) + } + + fn lock_progress_dispatcher( + &self, + ) -> PyResult>>> { + self.progress_dispatcher + .lock() + .map_err(|_| PyRuntimeError::new_err("progress dispatcher lock was poisoned")) + } + + fn set_progress_dispatcher( + &self, + py: Python<'_>, + dispatcher: Arc, + ) -> PyResult<()> { + let previous = self.lock_progress_dispatcher()?.replace(dispatcher); + match previous { + Some(previous) => previous.deactivate(py), + None => Ok(()), + } + } + + fn clear_progress_dispatcher(&self, py: Python<'_>) -> PyResult<()> { + let dispatcher = self.lock_progress_dispatcher()?.take(); + match dispatcher { + Some(dispatcher) => dispatcher.deactivate(py), + None => Ok(()), + } } fn future_is_done(&self, py: Python<'_>) -> PyResult { @@ -626,8 +703,10 @@ impl DynWinRTAsync { self.operation()?.wait(py) } - fn cancel(&self) -> PyResult<()> { - self.operation()?.cancel() + fn cancel(&self, py: Python<'_>) -> PyResult<()> { + let operation = self.operation()?; + let progress_result = operation.clear_progress_dispatcher(py); + finish_with_cleanup(py, operation.cancel(), progress_result) } fn release(&mut self, py: Python<'_>) -> PyResult<()> { @@ -713,8 +792,10 @@ impl DynWinRTAsyncWithProgress { self.operation()?.wait(py) } - fn cancel(&self) -> PyResult<()> { - self.operation()?.cancel() + fn cancel(&self, py: Python<'_>) -> PyResult<()> { + let operation = self.operation()?; + let progress_result = operation.clear_progress_dispatcher(py); + finish_with_cleanup(py, operation.cancel(), progress_result) } fn release(&mut self, py: Python<'_>) -> PyResult<()> { @@ -755,38 +836,31 @@ impl DynWinRTAsyncWithProgress { let handler_iid = info.progress_handler_iid().ok_or_else(|| { PyRuntimeError::new_err("cannot compute the WinRT progress handler IID") })?; - let converter = self.progress_converter.clone_ref(py); - let dispatch_progress = py - .import("dynwinrt.dynwinrt")? - .getattr("_dynwinrt_dispatch_progress")? - .unbind(); - let callback_context = py - .import("contextvars")? - .getattr("copy_context")? - .call0()? - .unbind(); + let dispatcher = Arc::new(ProgressDispatcher { + event_loop: loop_, + dispatch_state: PyList::new(py, [callback, self.progress_converter.clone_ref(py)])? + .into_any() + .unbind(), + dispatch_progress: py + .import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_dispatch_progress")? + .unbind(), + callback_context: py + .import("contextvars")? + .getattr("copy_context")? + .call0()? + .unbind(), + }); + // The native handler must not extend the Python callback or event-loop lifetime. + let weak_dispatcher = Arc::downgrade(&dispatcher); let progress_callback: dynwinrt::ProgressCallback = Box::new(move |value| { Python::attach(|py| { - let result = (|| -> PyResult<()> { - let raw = Py::new(py, DynWinRTValue(value))?; - let context = callback_context.call_method0(py, "copy")?; - let context_run = context.getattr(py, "run")?; - loop_.call_method1( - py, - "call_soon_threadsafe", - ( - context_run, - dispatch_progress.clone_ref(py), - callback.clone_ref(py), - converter.clone_ref(py), - raw, - ), - )?; - Ok(()) - })(); - if let Err(error) = result { - error.write_unraisable(py, Some(callback.bind(py))); + let Some(dispatcher) = weak_dispatcher.upgrade() else { + return; + }; + if let Err(error) = dispatcher.dispatch(py, value) { + error.write_unraisable(py, Some(dispatcher.dispatch_state.bind(py))); } }); }); @@ -798,9 +872,15 @@ impl DynWinRTAsyncWithProgress { "failed to create WinRT progress handler", ) })?; - finish_progress_registration(info.set_progress_handler(&handler), || { - info.is_started().map_err(map_dynwinrt_error) - }) + match info.set_progress_handler(&handler) { + Ok(()) => operation.set_progress_dispatcher(py, dispatcher), + Err(error) => { + let registration_result = finish_progress_registration(Err(error), || { + info.is_started().map_err(map_dynwinrt_error) + }); + finish_with_cleanup(py, registration_result, dispatcher.deactivate(py)) + } + } } fn __repr__(&self) -> &'static str { diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 701266ff..fff04792 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -505,8 +505,10 @@ def _dynwinrt_link_cancellation(task, future): future.cancel() task.add_done_callback(cancel_inner) -def _dynwinrt_dispatch_progress(callback, converter, value): - callback(converter(value)) +def _dynwinrt_dispatch_progress(dispatch_state, value): + if dispatch_state: + callback, converter = dispatch_state + callback(converter(value)) ", Some(&m.dict()), None, diff --git a/bindings/py/tests/test_e2e_winrt.py b/bindings/py/tests/test_e2e_winrt.py index 2de40883..e331b437 100644 --- a/bindings/py/tests/test_e2e_winrt.py +++ b/bindings/py/tests/test_e2e_winrt.py @@ -710,6 +710,8 @@ def __call__(self, _value): cancel_projected.release() del observer, cancel_projected, cancel_task await asyncio.sleep(0) + gc.collect() + assert observer_ref() is None return body, snapshots, cancel_raw, observer_ref body, snapshots, cancel_raw, observer_ref = asyncio.run(run_operation()) diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index 20c9af2e..b4b68fe1 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -530,12 +530,14 @@ def test_progress_dispatch_propagates_callback_errors(): def fail(_value): raise ValueError("progress callback failed") + dispatch_state = [fail, lambda value: value.to_number()] with pytest.raises(ValueError, match="progress callback failed"): _dynwinrt_dispatch_progress( - fail, - lambda value: value.to_number(), + dispatch_state, DynWinRTValue.from_u32(17), ) + dispatch_state.clear() + _dynwinrt_dispatch_progress(dispatch_state, DynWinRTValue.from_u32(17)) def test_observable_vector_reports_mutations_and_unsubscribes():