diff --git a/bindings/py/README.md b/bindings/py/README.md index b57af1d8..5f1f6275 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -550,9 +550,50 @@ with RoApartment(RO_INIT_SINGLETHREADED): model are supported. Requesting a conflicting model raises `OSError` with `RPC_E_CHANGED_MODE`. The low-level `ro_initialize()` API remains available, but each successful call, including `S_FALSE`, must be paired with one -`ro_uninitialize()` call on the same thread. Only this library's successful -initializations count toward its managed apartment depth; a third-party COM -initialization is not counted. +`ro_uninitialize()` call on the same thread. `ro_uninitialize()` rejects calls +without a matching `dynwinrt.ro_initialize()` on that thread, including calls +intended to balance an initialization made by another library. Only this +library's successful initializations count toward its managed apartment depth. + +Do not close the final managed apartment from a synchronous native-to-Python +callback (for example, a `PropertySet.map_changed` handler). `close()`, +`__exit__()`, and `ro_uninitialize()` raise `RuntimeError` **before** +`RoUninitialize` in that situation. A named `RoApartment` remains active; wait +for both the callback and its outer native call to return, release any retained +native callback values, then retry `apartment.close()` on the owner thread. +Non-final nested initializations may still be balanced inside the callback. +`ro_uninitialize()` cannot consume a `RoApartment` initialization. + +If a final `RoApartment` is dropped during a callback (including an unnamed +`with RoApartment():` whose `__exit__` failed), its initialization stays in a +same-thread pending lease rather than being uninitialized inside the native +stack. After the native call returns, recover the lease explicitly: + +```python +apartment = RoApartment.recover_pending() # on the original OS thread +# Release any remaining native PropertySet / callback references first. +apartment.close() +``` + +`recover_pending()` raises if called inside a callback or if no lease is +pending on that thread; calling it from another thread cannot consume the +owner's lease. It does not close or release anything automatically. Retain a +named apartment when possible so `.close()` can simply be retried. A failed +owner cleanup is a different pending lease: use +`retry_pending_apartment_close()` (or recover and close the guard) after fixing +the release failure. Each pending lease may be claimed only once; the retry +helper cannot consume a callback-deferred lease. An implicit drop without an +earlier failed close emits a native stderr diagnostic. + +An apartment is bound to the OS thread on which `RoApartment()` was created. +Calling `__enter__()`, `close()`, or `__exit__()` on another thread raises +`RuntimeError` without changing its state; retry on the creating thread. +If its last Python reference is instead dropped on a different thread, native +uninitialization is **not** attempted there: a native stderr diagnostic +identifies the pending lease, which the creating thread can explicitly retrieve +using `RoApartment.recover_pending()` and close after native references are +released. +Do not depend on Python garbage collection to close an apartment. WinRT is never initialized implicitly. A call on a thread without an apartment raises `OSError` with `CO_E_NOTINITIALIZED` in `error.winerror`; its message @@ -852,22 +893,21 @@ and reports an error instead. An unfinished async future prevents the final apartment close without silently cancelling work. Settle or explicitly cancel it, then call the owner-thread guard's `close()` again. If an unnamed `RoApartment` context's -close failed, use `retry_pending_apartment_close()` on the same thread. A +owner cleanup failed, use `retry_pending_apartment_close()` on the same thread; +if it was rejected during a native callback, use `RoApartment.recover_pending()` +after the outer native call returns. A non-agile WinRT async operation awaited from asyncio checks completion on its own apartment thread rather than passing its native reference to a worker. Explicitly cancelling that asyncio task calls native `IAsyncInfo::Cancel` on the owner thread; ordinary apartment cleanup never cancels an external task. Calls to `RoApartment.close()` on another OS thread raise without changing the -apartment state. Only an implicit wrong-thread finalizer or interpreter -shutdown without a usable GIL can force a diagnostic and retain unsafe native -references until process exit; normal close never treats a leak as success. - -Reentrant apartment teardown is a separate limitation: do not call -`RoApartment.close()` inside a native event callback that is still dispatching -on that apartment. Closing inside `PropertySet.MapChanged` has crashed with -`0xC0000005` on both the original base and this branch. Let the callback -return before closing its apartment on the owning thread. The owner-after-exit -protection above does not make teardown during an active callback safe. +apartment state. An implicit wrong-thread finalizer preserves its pending +native initialization for explicit recovery on the owner OS thread. If that +thread has exited, or interpreter shutdown makes the Python GIL unavailable, +native cleanup fails closed with a diagnostic instead of releasing COM after +teardown; normal close never treats a leak as success. A final close attempted +from a synchronous native callback is rejected before the owner drain and +`RoUninitialize`, then can be retried once the callback and native call return. ### Embedded host callback shutdown diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index f029fb7e..7f26c269 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -86,6 +86,8 @@ class RoApartment: self, exc_type: object, exc_value: object, traceback: object ) -> Literal[False]: ... def close(self) -> None: ... + @staticmethod + def recover_pending() -> RoApartment: ... def __repr__(self) -> str: ... @final diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index 163b0027..d3598897 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -2,9 +2,11 @@ // Licensed under the MIT License. use std::{ - cell::Cell, + cell::{Cell, RefCell}, + marker::PhantomData, + rc::Rc, sync::{ - Arc, Mutex, + Arc, Mutex, MutexGuard, atomic::{AtomicBool, Ordering}, }, thread::{self, ThreadId}, @@ -99,7 +101,9 @@ pub(crate) fn with_python_callback( }; #[cfg(test)] CALLBACK_ATTACH_ATTEMPTS.fetch_add(1, Ordering::SeqCst); + let callback_guard = NativeCallbackGuard::enter(); let result = Python::try_attach(callback); + drop(callback_guard); drop(permit); match result { Some(result) => Some(result), @@ -234,6 +238,158 @@ fn set_typed_field( // Runtime initialization // ====================================================================== +#[derive(Clone, Copy)] +struct PendingApartment { + apartment_type: i32, + retry_cleanup: bool, +} + +struct ForeignDropQueue { + owner_alive: bool, + pending: Vec, +} + +struct OwnerDropQueue(Arc>); + +impl OwnerDropQueue { + fn new() -> Self { + Self(Arc::new(Mutex::new(ForeignDropQueue { + owner_alive: true, + pending: Vec::new(), + }))) + } +} + +impl Drop for OwnerDropQueue { + fn drop(&mut self) { + let (pending, poisoned) = { + let (mut queue, poisoned) = lock_foreign_drops(&self.0); + queue.owner_alive = false; + (queue.pending.len(), poisoned) + }; + if poisoned { + native_apartment_diagnostic("RoApartment owner-thread pending state was poisoned"); + } + if pending != 0 { + native_apartment_diagnostic(&format!( + "{} dropped RoApartment initialization(s) were not recovered before their \ + owner OS thread exited", + pending + )); + } + } +} + +fn lock_foreign_drops(queue: &Mutex) -> (MutexGuard<'_, ForeignDropQueue>, bool) { + match queue.lock() { + Ok(guard) => (guard, false), + Err(poisoned) => { + queue.clear_poison(); + (poisoned.into_inner(), true) + } + } +} + +fn native_apartment_diagnostic(message: &str) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "{message}"); +} + +thread_local! { + static MANAGED_APARTMENT_DEPTH: Cell = const { Cell::new(0) }; + static MANUAL_APARTMENT_DEPTH: Cell = const { Cell::new(0) }; + static PENDING_APARTMENT_CLOSES: RefCell> = const { RefCell::new(Vec::new()) }; + static CALLBACK_PENDING_APARTMENTS: RefCell> = const { RefCell::new(Vec::new()) }; + static PENDING_RETRY_IN_PROGRESS: Cell = const { Cell::new(false) }; + static NATIVE_CALLBACK_DEPTH: Cell = const { Cell::new(0) }; + static FOREIGN_DROPS: OwnerDropQueue = OwnerDropQueue::new(); +} + +pub(crate) struct NativeCallbackGuard { + counted: bool, + _owner_thread: PhantomData>, +} + +impl NativeCallbackGuard { + pub(crate) fn enter() -> Self { + let counted = NATIVE_CALLBACK_DEPTH + .try_with(|depth| { + let Some(next) = depth.get().checked_add(1) else { + return false; + }; + depth.set(next); + true + }) + .unwrap_or(false); + Self { + counted, + _owner_thread: PhantomData, + } + } +} + +impl Drop for NativeCallbackGuard { + fn drop(&mut self) { + if self.counted { + let _ = NATIVE_CALLBACK_DEPTH.try_with(|depth| depth.set(depth.get() - 1)); + } + } +} + +struct PendingRetryGuard; + +impl PendingRetryGuard { + fn enter() -> PyResult { + PENDING_RETRY_IN_PROGRESS + .try_with(|busy| { + if busy.replace(true) { + return Err(PyRuntimeError::new_err( + "an apartment cleanup retry is already in progress on this thread", + )); + } + Ok(Self) + }) + .map_err(|_| { + PyRuntimeError::new_err("owner-thread pending state is unavailable during teardown") + })? + } +} + +impl Drop for PendingRetryGuard { + fn drop(&mut self) { + let _ = PENDING_RETRY_IN_PROGRESS.try_with(|busy| busy.set(false)); + } +} + +fn check_reentrant_uninitialize(operation: &str) -> PyResult<()> { + let callback_active = NATIVE_CALLBACK_DEPTH + .try_with(|depth| depth.get() != 0) + .map_err(|_| { + PyRuntimeError::new_err(format!( + "{operation}: owner-thread callback state is unavailable during teardown" + )) + })?; + let final_apartment = if callback_active { + MANAGED_APARTMENT_DEPTH + .try_with(|depth| depth.get() <= 1) + .map_err(|_| { + PyRuntimeError::new_err( + "owner-thread apartment state is unavailable during teardown", + ) + })? + } else { + false + }; + if final_apartment { + return Err(PyRuntimeError::new_err(format!( + "{operation} cannot risk uninitializing the final COM apartment during a synchronous \ + native callback on this thread; retry after the callback and native invocation \ + return. Recover a dropped context with RoApartment.recover_pending() on this thread." + ))); + } + Ok(()) +} + #[pyclass] pub struct WinAppSDKContext(pub(crate) dynwinrt::WinAppSdkContext); @@ -249,16 +405,12 @@ impl WinAppSDKContext { pub struct RoApartment { apartment_type: i32, active: bool, - owner_thread: Option, + close_rejected: bool, + owner_thread: ThreadId, + foreign_drops: Arc>, cleanup_failed: bool, } -thread_local! { - static MANAGED_APARTMENT_DEPTH: Cell = const { Cell::new(0) }; - static MANUAL_APARTMENT_DEPTH: Cell = const { Cell::new(0) }; - static PENDING_APARTMENT_CLOSES: Cell = const { Cell::new(0) }; -} - #[link(name = "kernel32")] unsafe extern "system" { fn OutputDebugStringA(message: *const u8); @@ -327,12 +479,19 @@ fn managed_apartment_depth() -> usize { } fn enter_managed_apartment(apartment_type: i32) -> PyResult<()> { + MANAGED_APARTMENT_DEPTH.try_with(|_| ()).map_err(|_| { + PyRuntimeError::new_err("owner-thread apartment state is unavailable during teardown") + })?; unsafe { RoInitialize(ro_init_type(apartment_type)) }.map_err(map_windows_error)?; MANAGED_APARTMENT_DEPTH.with(|depth| depth.set(depth.get() + 1)); Ok(()) } -fn leave_managed_apartment(py: Python<'_>) -> PyResult<()> { +fn leave_managed_apartment_with_drain( + operation: &str, + drain: impl FnOnce() -> PyResult<()>, +) -> PyResult<()> { + check_reentrant_uninitialize(operation)?; let depth = managed_apartment_depth(); if depth == 0 { return Err(PyRuntimeError::new_err( @@ -340,15 +499,22 @@ fn leave_managed_apartment(py: Python<'_>) -> PyResult<()> { )); } if depth == 1 { - py.import("dynwinrt.dynwinrt")? - .getattr("_dynwinrt_drain_apartment_owners")? - .call0()?; + drain()?; } MANAGED_APARTMENT_DEPTH.with(|state| state.set(depth - 1)); unsafe { windows::Win32::System::WinRT::RoUninitialize() }; Ok(()) } +fn leave_managed_apartment(py: Python<'_>, operation: &str) -> PyResult<()> { + leave_managed_apartment_with_drain(operation, || { + py.import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_drain_apartment_owners")? + .call0()?; + Ok(()) + }) +} + /// `apartment_type` used when Python omits it: the multithreaded apartment. const DEFAULT_APARTMENT_TYPE: i32 = RO_INIT_MULTITHREADED.0; @@ -370,7 +536,32 @@ fn ro_init_type(apartment_type: i32) -> RO_INIT_TYPE { } impl RoApartment { + fn enqueue_owner_recovery(&self) -> (bool, bool) { + let (mut queue, poisoned) = lock_foreign_drops(&self.foreign_drops); + if queue.owner_alive { + queue.pending.push(PendingApartment { + apartment_type: self.apartment_type, + retry_cleanup: self.cleanup_failed, + }); + (true, poisoned) + } else { + (false, poisoned) + } + } + + fn check_owner_thread(&self, operation: &str) -> PyResult<()> { + if thread::current().id() != self.owner_thread { + return Err(PyRuntimeError::new_err(format!( + "{operation} must run on the OS thread where RoApartment was created; \ + its initializing thread and apartment are unchanged. Retry on that owner thread, or recover a \ + guard dropped on another thread with RoApartment.recover_pending()." + ))); + } + Ok(()) + } + fn initialize(&mut self) -> PyResult<()> { + self.check_owner_thread("RoApartment.__enter__()")?; if self.active { return Err(PyRuntimeError::new_err( "the COM apartment context is already active", @@ -378,20 +569,26 @@ impl RoApartment { } enter_managed_apartment(self.apartment_type)?; self.active = true; - self.owner_thread = Some(thread::current().id()); + self.close_rejected = false; + self.cleanup_failed = false; Ok(()) } - fn finish(&mut self, py: Python<'_>) -> PyResult<()> { + fn finish_with_drain( + &mut self, + operation: &str, + drain: impl FnOnce() -> PyResult<()>, + ) -> PyResult<()> { + self.check_owner_thread(operation)?; if !self.active { return Ok(()); } - if self.owner_thread != Some(thread::current().id()) { - return Err(PyRuntimeError::new_err( - "RoApartment.close() must run on its initializing thread", - )); + if let Err(error) = check_reentrant_uninitialize(operation) { + self.close_rejected = true; + return Err(error); } - if let Err(error) = leave_managed_apartment(py) { + self.close_rejected = false; + if let Err(error) = leave_managed_apartment_with_drain(operation, drain) { self.cleanup_failed = true; return Err(error); } @@ -399,6 +596,20 @@ impl RoApartment { self.cleanup_failed = false; Ok(()) } + + fn finish(&mut self, py: Python<'_>, operation: &str) -> PyResult<()> { + self.finish_with_drain(operation, || { + py.import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_drain_apartment_owners")? + .call0()?; + Ok(()) + }) + } + + #[cfg(test)] + fn uninitialize(&mut self, operation: &str) -> PyResult<()> { + self.finish_with_drain(operation, || Ok(())) + } } impl Drop for RoApartment { @@ -406,28 +617,89 @@ impl Drop for RoApartment { if !self.active { return; } - if self.owner_thread != Some(thread::current().id()) || !python_gil_usable() { + if thread::current().id() != self.owner_thread { + let (queued, poisoned) = self.enqueue_owner_recovery(); + self.active = false; + if poisoned { + native_apartment_diagnostic( + "RoApartment owner-thread pending state was poisoned; its native \ + initialization remains recoverable on the owner thread.", + ); + } + let message = if queued { + "RoApartment was dropped on a different OS thread; its COM apartment remains \ + active on the creating thread. Call RoApartment.recover_pending().close() \ + there after native calls and retained references have been released." + } else { + "RoApartment was dropped after its owner OS thread exited; its COM apartment \ + cannot be recovered on a different thread." + }; + native_apartment_diagnostic(message); + return; + } + let gil_usable = python_gil_usable(); + if !gil_usable { log_unsafe_apartment_teardown(); + } + if !self.close_rejected + && !self.cleanup_failed + && gil_usable + && check_reentrant_uninitialize("RoApartment.close()").is_ok() + && Python::try_attach(|py| match self.finish(py, "RoApartment.close()") { + Ok(()) => true, + Err(error) => { + if !self.close_rejected { + error.write_unraisable(py, None); + } + false + } + }) == Some(true) + { return; } + self.active = false; if self.cleanup_failed { if PENDING_APARTMENT_CLOSES - .try_with(|pending| pending.set(pending.get() + 1)) - .is_err() + .try_with(|pending| { + pending + .try_borrow_mut() + .map(|mut pending| pending.push(self.apartment_type)) + }) + .is_ok_and(|result| result.is_ok()) { - log_unsafe_apartment_teardown(); + return; + } + } else if CALLBACK_PENDING_APARTMENTS + .try_with(|pending| { + pending + .try_borrow_mut() + .map(|mut pending| pending.push(self.apartment_type)) + }) + .is_ok_and(|result| result.is_ok()) + { + if !self.close_rejected { + native_apartment_diagnostic( + "RoApartment was dropped during a synchronous native callback or without \ + a usable Python GIL; its COM apartment remains active. Call \ + RoApartment.recover_pending().close() on this thread after the native call.", + ); } return; } - if Python::try_attach(|py| { - if let Err(error) = self.finish(py) { - PENDING_APARTMENT_CLOSES.with(|pending| pending.set(pending.get() + 1)); - error.write_unraisable(py, None); - } - }) - .is_none() - { - log_unsafe_apartment_teardown(); + let (queued, poisoned) = self.enqueue_owner_recovery(); + if poisoned { + native_apartment_diagnostic("RoApartment owner-thread pending queue was poisoned"); + } + if queued { + native_apartment_diagnostic( + "RoApartment owner-thread pending state is unavailable; native initialization \ + remains recoverable with RoApartment.recover_pending()", + ); + } else { + native_apartment_diagnostic( + "RoApartment owner-thread state and recovery queue were unavailable during \ + teardown; native uninitialization was not attempted", + ); } } } @@ -436,13 +708,27 @@ impl Drop for RoApartment { impl RoApartment { #[new] #[pyo3(signature = (apartment_type=None))] - fn new(apartment_type: Option) -> Self { - Self { + fn new(apartment_type: Option) -> PyResult { + MANAGED_APARTMENT_DEPTH.try_with(|_| ()).map_err(|_| { + PyRuntimeError::new_err( + "RoApartment cannot be created after its owner-thread state was destroyed", + ) + })?; + let foreign_drops = FOREIGN_DROPS + .try_with(|queue| queue.0.clone()) + .map_err(|_| { + PyRuntimeError::new_err( + "RoApartment cannot be created after its owner-thread state was destroyed", + ) + })?; + Ok(Self { apartment_type: apartment_type.unwrap_or(DEFAULT_APARTMENT_TYPE), active: false, - owner_thread: None, + close_rejected: false, + owner_thread: thread::current().id(), + foreign_drops, cleanup_failed: false, - } + }) } fn __enter__(mut slf: PyRefMut<'_, Self>) -> PyResult> { @@ -457,7 +743,7 @@ impl RoApartment { _traceback: &Bound<'_, PyAny>, ) -> PyResult { let py = _exc_type.py(); - match self.finish(py) { + match self.finish(py, "RoApartment.__exit__()") { Ok(()) => Ok(false), Err(cleanup_error) if !_exc_value.is_none() => { py.import("dynwinrt.dynwinrt")? @@ -470,14 +756,114 @@ impl RoApartment { } fn close(&mut self, py: Python<'_>) -> PyResult<()> { - self.finish(py) + self.finish(py, "RoApartment.close()") } - fn __repr__(&self) -> String { - format!( + #[staticmethod] + fn recover_pending() -> PyResult { + let callback_active = NATIVE_CALLBACK_DEPTH + .try_with(|depth| depth.get() != 0) + .map_err(|_| { + PyRuntimeError::new_err( + "owner-thread callback state is unavailable during teardown", + ) + })?; + if callback_active { + return Err(PyRuntimeError::new_err( + "recover_pending() must be called on the owner thread after the synchronous \ + native callback and invocation return", + )); + } + if PENDING_RETRY_IN_PROGRESS.try_with(Cell::get).map_err(|_| { + PyRuntimeError::new_err("owner-thread pending state is unavailable during teardown") + })? { + return Err(PyRuntimeError::new_err( + "an apartment cleanup retry is already in progress on this thread", + )); + } + let foreign_drops = FOREIGN_DROPS + .try_with(|queue| queue.0.clone()) + .map_err(|_| { + PyRuntimeError::new_err( + "owner-thread apartment recovery queue is unavailable during teardown", + ) + })?; + let local = CALLBACK_PENDING_APARTMENTS + .try_with(|state| -> PyResult> { + let mut state = state.try_borrow_mut().map_err(|_| { + PyRuntimeError::new_err("owner-thread apartment state is already in use") + })?; + Ok(state.pop()) + }) + .map_err(|_| { + PyRuntimeError::new_err( + "owner-thread apartment state is unavailable during teardown", + ) + })??; + let pending = match local { + Some(apartment_type) => PendingApartment { + apartment_type, + retry_cleanup: false, + }, + None => { + let (pending, poisoned) = { + let (mut queue, poisoned) = lock_foreign_drops(&foreign_drops); + (queue.pending.pop(), poisoned) + }; + if poisoned { + native_apartment_diagnostic( + "RoApartment owner-thread pending state was poisoned; recovering its \ + native initialization before any COM uninitialization.", + ); + } + match pending { + Some(pending) => pending, + None => { + let cleanup_pending = PENDING_APARTMENT_CLOSES + .try_with(|state| { + state + .try_borrow_mut() + .map(|mut state| state.pop()) + .map_err(|_| { + PyRuntimeError::new_err( + "owner-thread pending state is already in use", + ) + }) + }) + .map_err(|_| { + PyRuntimeError::new_err( + "owner-thread pending state is unavailable during teardown", + ) + })?? + .ok_or_else(|| { + PyRuntimeError::new_err( + "no dropped RoApartment is pending on this thread", + ) + })?; + PendingApartment { + apartment_type: cleanup_pending, + retry_cleanup: true, + } + } + } + } + }; + Ok(Self { + apartment_type: pending.apartment_type, + active: true, + close_rejected: false, + cleanup_failed: pending.retry_cleanup, + owner_thread: thread::current().id(), + foreign_drops, + }) + } + + fn __repr__(&self) -> PyResult { + self.check_owner_thread("RoApartment.__repr__()")?; + Ok(format!( "RoApartment(apartment_type={}, active={})", self.apartment_type, self.active - ) + )) } } @@ -503,21 +889,69 @@ pub fn ro_uninitialize(py: Python<'_>) -> PyResult<()> { "ro_uninitialize() requires a successful ro_initialize() on this thread", )); } - leave_managed_apartment(py)?; + leave_managed_apartment(py, "ro_uninitialize()")?; MANUAL_APARTMENT_DEPTH.with(|state| state.set(depth - 1)); Ok(()) } #[pyfunction] pub fn retry_pending_apartment_close(py: Python<'_>) -> PyResult<()> { - let pending = PENDING_APARTMENT_CLOSES.with(Cell::get); - if pending == 0 { + let local_pending = PENDING_APARTMENT_CLOSES + .try_with(|pending| { + pending + .try_borrow() + .map(|pending| !pending.is_empty()) + .map_err(|_| { + PyRuntimeError::new_err("owner-thread pending state is already in use") + }) + }) + .map_err(|_| { + PyRuntimeError::new_err("owner-thread pending state is unavailable during teardown") + })??; + let foreign_pending = if !local_pending { + FOREIGN_DROPS + .try_with(|owner| { + let (queue, poisoned) = lock_foreign_drops(&owner.0); + if poisoned { + native_apartment_diagnostic( + "RoApartment owner-thread pending state was poisoned during cleanup retry", + ); + } + queue.pending.iter().any(|pending| pending.retry_cleanup) + }) + .map_err(|_| { + PyRuntimeError::new_err( + "owner-thread apartment recovery queue is unavailable during teardown", + ) + })? + } else { + false + }; + if !local_pending && !foreign_pending { return Err(PyRuntimeError::new_err( "no failed RoApartment close is pending on this thread", )); } - leave_managed_apartment(py)?; - PENDING_APARTMENT_CLOSES.with(|state| state.set(pending - 1)); + let _retry = PendingRetryGuard::enter()?; + leave_managed_apartment(py, "retry_pending_apartment_close()")?; + if local_pending { + PENDING_APARTMENT_CLOSES.with(|pending| { + pending + .borrow_mut() + .pop() + .expect("pending cleanup was checked"); + }); + } else { + FOREIGN_DROPS.with(|owner| { + let (mut queue, _) = lock_foreign_drops(&owner.0); + let index = queue + .pending + .iter() + .rposition(|pending| pending.retry_cleanup) + .expect("pending foreign cleanup was checked"); + queue.pending.remove(index); + }); + } Ok(()) } @@ -3474,6 +3908,323 @@ mod tests { use pyo3::types::PyDict; use std::ffi::c_void; use std::sync::atomic::{AtomicU32, Ordering}; + use std::time::Duration; + + struct LateDropProbe { + apartment: Option, + state_was_destroyed: Arc, + creation_was_rejected: Arc, + } + + impl Drop for LateDropProbe { + fn drop(&mut self) { + self.state_was_destroyed.store( + CALLBACK_PENDING_APARTMENTS.try_with(|_| ()).is_err(), + Ordering::SeqCst, + ); + self.creation_was_rejected + .store(RoApartment::new(None).is_err(), Ordering::SeqCst); + drop(self.apartment.take()); + } + } + + thread_local! { + static LATE_APARTMENT_DROP: RefCell> = const { RefCell::new(None) }; + } + + fn test_ro_uninitialize() -> PyResult<()> { + let depth = MANUAL_APARTMENT_DEPTH.with(Cell::get); + if depth == 0 { + return Err(PyRuntimeError::new_err( + "ro_uninitialize() requires a successful ro_initialize() on this thread", + )); + } + leave_managed_apartment_with_drain("ro_uninitialize()", || Ok(()))?; + MANUAL_APARTMENT_DEPTH.with(|state| state.set(depth - 1)); + Ok(()) + } + + #[test] + fn reentrant_apartment_guard_preserves_nested_and_manual_initializations() { + Python::initialize(); + std::thread::spawn(|| { + Python::attach(|py| { + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + let outer_callback = NativeCallbackGuard::enter(); + let inner_callback = NativeCallbackGuard::enter(); + let error = apartment.uninitialize("RoApartment.close()").unwrap_err(); + assert!(error.is_instance_of::(py)); + assert!(error.to_string().contains("retry after the callback")); + assert!(apartment.active); + + let mut nested = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + nested.initialize().unwrap(); + nested.uninitialize("RoApartment.close()").unwrap(); + ro_initialize(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + test_ro_uninitialize().unwrap(); + assert!(test_ro_uninitialize().is_err()); + assert!(apartment.active); + drop(inner_callback); + assert!(apartment.uninitialize("RoApartment.close()").is_err()); + drop(outer_callback); + + assert!(test_ro_uninitialize().is_err()); + apartment.uninitialize("RoApartment.close()").unwrap(); + assert!(!apartment.active); + apartment.uninitialize("RoApartment.close()").unwrap(); + let mut other_model = RoApartment::new(Some(RO_INIT_MULTITHREADED.0)).unwrap(); + other_model.initialize().unwrap(); + other_model.uninitialize("RoApartment.close()").unwrap(); + }); + }) + .join() + .unwrap(); + } + + #[test] + fn dropped_final_apartment_requires_owner_thread_recovery() { + Python::initialize(); + std::thread::spawn(|| { + Python::attach(|py| { + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + let callback = NativeCallbackGuard::enter(); + apartment + .uninitialize("RoApartment.__exit__()") + .unwrap_err(); + drop(apartment); + assert!(RoApartment::recover_pending().is_err()); + drop(callback); + + let wrong_thread_error = py.detach(|| { + std::thread::spawn(|| { + Python::attach(|py| { + RoApartment::recover_pending() + .err() + .expect("wrong-thread recovery should fail") + .value(py) + .str() + .unwrap() + .to_str() + .unwrap() + .to_owned() + }) + }) + .join() + .unwrap() + }); + assert!(wrong_thread_error.contains("on this thread")); + + let mut recovered = RoApartment::recover_pending().unwrap(); + assert!(recovered.active); + assert!(RoApartment::recover_pending().is_err()); + recovered.uninitialize("RoApartment.close()").unwrap(); + assert!(!recovered.active); + }); + }) + .join() + .unwrap(); + } + + #[test] + fn foreign_close_and_drop_preserve_owner_thread_retry() { + let _serial = crate::errors::UNRAISABLE_HOOK_TEST_LOCK.lock().unwrap(); + Python::initialize(); + std::thread::spawn(|| { + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + let apartment = std::thread::spawn(move || { + assert!(apartment.uninitialize("RoApartment.close()").is_err()); + assert!(apartment.active); + apartment + }) + .join() + .unwrap(); + assert!(apartment.active); + + let callback = NativeCallbackGuard::enter(); + std::thread::spawn(move || drop(apartment)).join().unwrap(); + assert!(RoApartment::recover_pending().is_err()); + drop(callback); + + let mut recovered = RoApartment::recover_pending().unwrap(); + assert!(recovered.active); + recovered.uninitialize("RoApartment.close()").unwrap(); + let mut other_model = RoApartment::new(Some(RO_INIT_MULTITHREADED.0)).unwrap(); + other_model.initialize().unwrap(); + other_model.uninitialize("RoApartment.close()").unwrap(); + }) + .join() + .unwrap(); + } + + #[test] + fn poisoned_foreign_drop_queue_keeps_lease_recoverable() { + let _serial = crate::errors::UNRAISABLE_HOOK_TEST_LOCK.lock().unwrap(); + Python::initialize(); + std::thread::spawn(|| { + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + let queue = apartment.foreign_drops.clone(); + let poisoned = std::panic::catch_unwind(|| { + let _guard = queue.lock().unwrap(); + panic!("poison the owner-thread recovery queue"); + }); + assert!(poisoned.is_err()); + + std::thread::spawn(move || drop(apartment)).join().unwrap(); + assert!(!queue.is_poisoned()); + let poisoned_again = std::panic::catch_unwind(|| { + let _guard = queue.lock().unwrap(); + panic!("poison the owner-thread queue before recovery"); + }); + assert!(poisoned_again.is_err()); + let mut recovered = RoApartment::recover_pending().unwrap(); + assert!(!queue.is_poisoned()); + recovered.uninitialize("RoApartment.close()").unwrap(); + assert!(RoApartment::recover_pending().is_err()); + }) + .join() + .unwrap(); + } + + #[test] + fn closed_owner_queue_rejects_foreign_drop_without_native_cleanup() { + let _serial = crate::errors::UNRAISABLE_HOOK_TEST_LOCK.lock().unwrap(); + Python::initialize(); + let (sender, receiver) = std::sync::mpsc::channel(); + let owner = std::thread::spawn(move || { + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + sender.send(apartment).unwrap(); + }); + let apartment = receiver.recv().unwrap(); + owner.join().unwrap(); + + let queue = apartment.foreign_drops.clone(); + assert!(!lock_foreign_drops(&queue).0.owner_alive); + drop(apartment); + let (queue, _) = lock_foreign_drops(&queue); + assert!(queue.pending.is_empty()); + } + + #[test] + fn foreign_drop_does_not_wait_for_owners_python_gil() { + Python::initialize(); + std::thread::spawn(|| { + Python::attach(|_py| { + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + let callback = NativeCallbackGuard::enter(); + let (sent, received) = std::sync::mpsc::channel(); + let worker = std::thread::spawn(move || { + drop(apartment); + sent.send(()).unwrap(); + }); + assert!( + received.recv_timeout(Duration::from_secs(3)).is_ok(), + "foreign Drop waited for the owner to release Python's GIL" + ); + worker.join().unwrap(); + assert!(RoApartment::recover_pending().is_err()); + drop(callback); + let mut recovered = RoApartment::recover_pending().unwrap(); + recovered.uninitialize("RoApartment.close()").unwrap(); + }); + }) + .join() + .unwrap(); + } + + #[test] + fn owner_queue_closes_with_unrecovered_foreign_drop() { + let (sent, received) = std::sync::mpsc::channel(); + let (continue_owner, owner_waits) = std::sync::mpsc::channel::<()>(); + let owner = std::thread::spawn(move || { + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + sent.send(apartment).unwrap(); + owner_waits.recv().unwrap(); + }); + let apartment = received.recv().unwrap(); + let queue = apartment.foreign_drops.clone(); + drop(apartment); + assert_eq!(lock_foreign_drops(&queue).0.pending.len(), 1); + continue_owner.send(()).unwrap(); + owner.join().unwrap(); + let (queue, _) = lock_foreign_drops(&queue); + assert!(!queue.owner_alive); + assert_eq!(queue.pending.len(), 1); + } + + #[test] + fn owner_drop_while_pending_state_is_borrowed_remains_recoverable() { + Python::initialize(); + std::thread::spawn(|| { + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + CALLBACK_PENDING_APARTMENTS.with(|pending| { + let borrowed = pending.borrow(); + drop(apartment); + assert!(borrowed.is_empty()); + }); + let mut recovered = RoApartment::recover_pending().unwrap(); + assert_eq!(recovered.apartment_type, RO_INIT_SINGLETHREADED.0); + recovered.uninitialize("RoApartment.close()").unwrap(); + let mut other_model = RoApartment::new(Some(RO_INIT_MULTITHREADED.0)).unwrap(); + other_model.initialize().unwrap(); + other_model.uninitialize("RoApartment.close()").unwrap(); + }) + .join() + .unwrap(); + } + + #[test] + fn owner_drop_after_apartment_tls_teardown_fails_closed() { + let state_was_destroyed = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let creation_was_rejected = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let observed = state_was_destroyed.clone(); + let rejected = creation_was_rejected.clone(); + std::thread::spawn(move || { + LATE_APARTMENT_DROP.with(|_| ()); + CALLBACK_PENDING_APARTMENTS.with(|_| ()); + let mut apartment = RoApartment::new(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + LATE_APARTMENT_DROP.with(|slot| { + *slot.borrow_mut() = Some(LateDropProbe { + apartment: Some(apartment), + state_was_destroyed: observed, + creation_was_rejected: rejected, + }); + }); + }) + .join() + .unwrap(); + assert!(state_was_destroyed.load(Ordering::SeqCst)); + assert!(creation_was_rejected.load(Ordering::SeqCst)); + } + + #[test] + fn manual_uninitialize_requires_matching_owner_thread_initialization() { + Python::initialize(); + std::thread::spawn(|| { + assert!(test_ro_uninitialize().is_err()); + ro_initialize(Some(RO_INIT_SINGLETHREADED.0)).unwrap(); + assert!( + std::thread::spawn(|| test_ro_uninitialize().is_err()) + .join() + .unwrap() + ); + test_ro_uninitialize().unwrap(); + + let mut apartment = RoApartment::new(Some(RO_INIT_MULTITHREADED.0)).unwrap(); + apartment.initialize().unwrap(); + apartment.uninitialize("RoApartment.close()").unwrap(); + }) + .join() + .unwrap(); + } fn initialize_embedded_binding(py: Python<'_>) { let package_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) @@ -4042,7 +4793,7 @@ mod tests { Python::initialize(); std::thread::spawn(|| { assert_eq!(unsafe { pyo3::ffi::PyGILState_Check() }, 0); - let mut apartment = RoApartment::new(Some(1)); + let mut apartment = RoApartment::new(Some(1)).unwrap(); apartment.initialize().unwrap(); assert_eq!(managed_apartment_depth(), 1); drop(apartment); @@ -4185,7 +4936,7 @@ mod tests { Python::initialize(); Python::attach(initialize_embedded_binding); - let mut apartment = RoApartment::new(Some(1)); + let mut apartment = RoApartment::new(Some(1)).unwrap(); apartment.initialize().unwrap(); let (source, counts) = QueryProbe::new(); let owned = DynWinRTValue::new_managed(dynwinrt::WinRTValue::Object(source.clone()), false); diff --git a/tests/e2e/runners/py_apartment_reentrancy.py b/tests/e2e/runners/py_apartment_reentrancy.py new file mode 100644 index 00000000..b2a920af --- /dev/null +++ b/tests/e2e/runners/py_apartment_reentrancy.py @@ -0,0 +1,450 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Isolated, real PropertySet MapChanged/apartment lifetime regressions.""" + +import argparse +import os +import sys +import threading + + +def blocked_close(action): + try: + action() + except RuntimeError as error: + message = str(error) + assert 'synchronous native callback' in message, message + assert 'retry after the callback' in message, message + else: + raise AssertionError('final apartment uninitialization succeeded in a native callback') + + +def run_case(generated, mode, scenario): + sys.path.insert(0, os.path.dirname(os.path.abspath(generated))) + import dynwinrt as dw + from dynwinrt.dynwinrt import _dynwinrt_track_native + from python_bindings import PropertySet + + class TrackedOwner: + def __init__(self): + self.releases = 0 + + def release(self): + self.releases += 1 + + def switch_models(): + with dw.RoApartment(1 - mode) as opposite: + assert 'active=true' in repr(opposite) + + def dispose(mapping, token): + mapping.off_map_changed(token) + dw.release_projected(mapping) + + def callback_pending_only(): + from dynwinrt.dynwinrt import _managed_apartment_depth + + assert _managed_apartment_depth() == 1 + try: + dw.retry_pending_apartment_close() + except RuntimeError as error: + assert 'no failed RoApartment close' in str(error), error + else: + raise AssertionError('cleanup retry consumed a callback-deferred apartment') + assert _managed_apartment_depth() == 1 + + def foreign_error(action): + errors = [] + + def on_foreign_thread(): + try: + action() + except BaseException as error: + errors.append(error) + + thread = threading.Thread(target=on_foreign_thread) + thread.start() + thread.join(timeout=5) + assert not thread.is_alive() and len(errors) == 1, errors + assert type(errors[0]) is RuntimeError, errors[0] + return str(errors[0]) + + if scenario in ('close', 'exit'): + apartment = dw.RoApartment(mode) + apartment.__enter__() + events = [] + retained = [] + tracked = _dynwinrt_track_native(TrackedOwner()) + + def on_changed(sender, args): + events.append(args.key) + if not retained: + retained.extend((sender, args)) + assert sender[args.key] is None + if scenario == 'close': + blocked_close(apartment.close) + else: + blocked_close(lambda: apartment.__exit__(None, None, None)) + assert 'active=true' in repr(apartment) + assert tracked.releases == 0 and not mapping._obj.is_released() + assert args.key in sender + + mapping = PropertySet() + token = mapping.on_map_changed(on_changed) + mapping.insert('first', None) + mapping.insert('second', None) + assert events == ['first', 'second'], events + assert tracked.releases == 0 + sender, args = retained + assert args.key == 'first' and sender['first'] is None + dispose(mapping, token) + dw.release_projected(args) + dw.release_projected(sender) + if scenario == 'close': + apartment.close() + apartment.close() + else: + assert apartment.__exit__(None, None, None) is False + assert 'active=false' in repr(apartment) + assert tracked.releases == 1 + switch_models() + + elif scenario == 'nested': + outer = dw.RoApartment(mode) + inner = dw.RoApartment(mode) + outer.__enter__() + inner.__enter__() + events = [] + tracked = _dynwinrt_track_native(TrackedOwner()) + + def on_changed(sender, args): + events.append(args.key) + inner.close() + assert 'active=false' in repr(inner) + blocked_close(outer.close) + assert tracked.releases == 0 + assert 'active=true' in repr(outer) + assert sender[args.key] is None + + mapping = PropertySet() + token = mapping.on_map_changed(on_changed) + mapping.insert('nested', None) + assert events == ['nested'], events + dispose(mapping, token) + outer.close() + assert tracked.releases == 1 + switch_models() + + elif scenario == 'manual': + dw.ro_initialize(mode) + dw.ro_initialize(mode) + events = [] + tracked = _dynwinrt_track_native(TrackedOwner()) + + def on_changed(sender, args): + events.append(args.key) + dw.ro_uninitialize() + blocked_close(dw.ro_uninitialize) + assert tracked.releases == 0 + assert sender[args.key] is None + + mapping = PropertySet() + token = mapping.on_map_changed(on_changed) + mapping.insert('manual', None) + assert events == ['manual'], events + dispose(mapping, token) + dw.ro_uninitialize() + assert tracked.releases == 1 + switch_models() + + elif scenario == 'pending': + outer = dw.RoApartment(mode) + outer.__enter__() + events = [] + + def on_changed(sender, args): + events.append(args.key) + + def unnamed_context(): + with dw.RoApartment(mode): + outer.close() + + blocked_close(unnamed_context) + assert 'active=false' in repr(outer) + try: + dw.RoApartment.recover_pending() + except RuntimeError as error: + assert 'after' in str(error), error + else: + raise AssertionError('pending apartment recovered inside its native callback') + assert sender[args.key] is None + + mapping = PropertySet() + token = mapping.on_map_changed(on_changed) + mapping.insert('pending', None) + assert events == ['pending'], events + callback_pending_only() + + wrong_thread = [] + + def recover_on_wrong_thread(): + try: + dw.RoApartment.recover_pending() + except RuntimeError as error: + wrong_thread.append(str(error)) + + thread = threading.Thread(target=recover_on_wrong_thread) + thread.start() + thread.join(timeout=5) + assert not thread.is_alive() and len(wrong_thread) == 1, wrong_thread + assert 'on this thread' in wrong_thread[0], wrong_thread + + recovered = dw.RoApartment.recover_pending() + assert 'active=true' in repr(recovered) + try: + dw.RoApartment.recover_pending() + except RuntimeError as error: + assert 'no dropped RoApartment' in str(error), error + else: + raise AssertionError('recovered the same pending apartment twice') + dispose(mapping, token) + recovered.close() + switch_models() + + elif scenario == 'drop': + outer = dw.RoApartment(mode) + outer.__enter__() + inner = dw.RoApartment(mode) + inner.__enter__() + + def on_changed(sender, args): + outer.close() + inner_holder.pop() + assert sender[args.key] is None + + inner_holder = [inner] + del inner + mapping = PropertySet() + token = mapping.on_map_changed(on_changed) + mapping.insert('dropped', None) + callback_pending_only() + recovered = dw.RoApartment.recover_pending() + dispose(mapping, token) + recovered.close() + switch_models() + + elif scenario == 'pending_error': + outer = dw.RoApartment(mode) + outer.__enter__() + unraisable = [] + original_hook = sys.unraisablehook + sys.unraisablehook = unraisable.append + + def on_changed(_sender, _args): + with dw.RoApartment(mode): + outer.close() + + mapping = PropertySet() + token = mapping.on_map_changed(on_changed) + try: + try: + mapping.insert('pending-error', None) + except OSError: + pass + finally: + sys.unraisablehook = original_hook + assert len(unraisable) == 1, unraisable + assert isinstance(unraisable[0].exc_value, RuntimeError) + assert 'synchronous native callback' in str(unraisable[0].exc_value) + unraisable.clear() + assert 'active=false' in repr(outer) + callback_pending_only() + recovered = dw.RoApartment.recover_pending() + dispose(mapping, token) + recovered.close() + switch_models() + + elif scenario == 'foreign_enter': + apartment = dw.RoApartment(mode) + message = foreign_error(apartment.__enter__) + assert 'OS thread where RoApartment was created' in message, message + assert 'active=false' in repr(apartment) + apartment.__enter__() + mapping = PropertySet() + dw.release_projected(mapping) + apartment.close() + switch_models() + + elif scenario in ('foreign_close', 'foreign_exit', 'foreign_manual'): + apartment = dw.RoApartment(mode) + apartment.__enter__() + events = [] + mapping = PropertySet() + token = mapping.on_map_changed(lambda _sender, args: events.append(args.key)) + if scenario == 'foreign_close': + message = foreign_error(apartment.close) + elif scenario == 'foreign_exit': + message = foreign_error(lambda: apartment.__exit__(None, None, None)) + else: + message = foreign_error(dw.ro_uninitialize) + try: + dw.ro_uninitialize() + except RuntimeError as error: + assert 'requires a successful ro_initialize()' in str(error), error + else: + raise AssertionError('manual uninitialize consumed a RoApartment context') + if scenario == 'foreign_manual': + assert 'requires a successful ro_initialize()' in message, message + else: + assert 'OS thread where RoApartment was created' in message, message + assert 'active=true' in repr(apartment) + mapping.insert('owner-still-active', None) + assert events == ['owner-still-active'], events + dispose(mapping, token) + apartment.close() + switch_models() + + elif scenario == 'foreign_drop': + apartment = dw.RoApartment(mode) + apartment.__enter__() + events = [] + + def on_changed(_sender, args): + events.append(args.key) + try: + dw.RoApartment.recover_pending() + except RuntimeError as error: + assert 'native callback' in str(error), error + else: + raise AssertionError('foreign-dropped apartment recovered in a native callback') + + mapping = PropertySet() + token = mapping.on_map_changed(on_changed) + holder = [apartment] + del apartment + + def drop_on_foreign_thread(): + value = holder.pop() + del value + + thread = threading.Thread(target=drop_on_foreign_thread) + thread.start() + thread.join(timeout=5) + assert not thread.is_alive() and not holder, holder + mapping.insert('owner-still-active', None) + assert events == ['owner-still-active'], events + callback_pending_only() + dispose(mapping, token) + recovered = dw.RoApartment.recover_pending() + assert 'active=true' in repr(recovered) + recovered.close() + switch_models() + + elif scenario in ('cleanup_retry', 'cleanup_recover'): + from dynwinrt.dynwinrt import _dynwinrt_track_native, _managed_apartment_depth + + class FailingOwner: + def __init__(self): + self.attempts = 0 + + def release(self): + self.attempts += 1 + if self.attempts == 1: + raise RuntimeError('owner release failed') + if scenario == 'cleanup_retry': + for action in (dw.retry_pending_apartment_close, dw.RoApartment.recover_pending): + try: + action() + except RuntimeError as error: + assert 'already in progress' in str(error), error + else: + raise AssertionError('a reentrant pending helper double-consumed the lease') + + try: + with dw.RoApartment(mode): + mapping = PropertySet() + dw.release_projected(mapping) + owner = _dynwinrt_track_native(FailingOwner()) + except RuntimeError as error: + assert str(error) == 'owner release failed', error + else: + raise AssertionError('an unnamed context hid its owner-drain failure') + assert owner.attempts == 1 and _managed_apartment_depth() == 1 + if scenario == 'cleanup_retry': + dw.retry_pending_apartment_close() + else: + recovered = dw.RoApartment.recover_pending() + assert f'apartment_type={mode}, active=true' in repr(recovered) + try: + dw.retry_pending_apartment_close() + except RuntimeError as error: + assert 'no failed RoApartment close' in str(error), error + else: + raise AssertionError('cleanup retry consumed an already recovered lease') + assert _managed_apartment_depth() == 1 and owner.attempts == 1 + recovered.close() + assert owner.attempts == 2 and _managed_apartment_depth() == 0 + for action in (dw.retry_pending_apartment_close, dw.RoApartment.recover_pending): + try: + action() + except RuntimeError: + pass + else: + raise AssertionError('a completed apartment lease was consumed twice') + switch_models() + + elif scenario == 'exception': + apartment = dw.RoApartment(mode) + apartment.__enter__() + unraisable = [] + original_hook = sys.unraisablehook + sys.unraisablehook = unraisable.append + + def on_changed(_sender, _args): + blocked_close(apartment.close) + raise ValueError('handler failed after blocked close') + + mapping = PropertySet() + token = mapping.on_map_changed(on_changed) + try: + try: + mapping.insert('failed', None) + except OSError: + pass + finally: + sys.unraisablehook = original_hook + assert len(unraisable) == 1, unraisable + assert isinstance(unraisable[0].exc_value, ValueError) + assert 'handler failed after blocked close' in str(unraisable[0].exc_value) + mapping.off_map_changed(token) + unraisable.clear() + events = [] + token = mapping.on_map_changed(lambda _sender, args: events.append(args.key)) + mapping.insert('after', None) + assert events == ['after'], events + dispose(mapping, token) + apartment.close() + switch_models() + + else: + raise AssertionError(f'unknown apartment scenario: {scenario}') + + print(f'PASS {scenario} apartment={mode}', flush=True) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--generated', required=True) + parser.add_argument('--mode', type=int, choices=[0, 1], required=True) + parser.add_argument( + '--scenario', + choices=[ + 'close', 'exit', 'nested', 'manual', 'pending', 'drop', + 'pending_error', 'exception', 'foreign_enter', 'foreign_close', + 'foreign_exit', 'foreign_manual', 'foreign_drop', + 'cleanup_retry', 'cleanup_recover', + ], + required=True, + ) + args = parser.parse_args() + run_case(args.generated, args.mode, args.scenario) diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index cdeb87f4..d88b3901 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -20,6 +20,7 @@ import subprocess import sys import os +import subprocess import threading @@ -1559,6 +1560,65 @@ def observe_null(sender, args): dw.release_projected(null_events[0][1]) dw.release_projected(null_events[0][0]) del obj['null-element'] + if cls.__name__ == 'PropertySet': + runner = os.path.join( + os.path.dirname(__file__), 'py_apartment_reentrancy.py' + ) + for mode in (dw.RO_INIT_SINGLETHREADED, dw.RO_INIT_MULTITHREADED): + for scenario in ( + 'close', 'exit', 'nested', 'manual', 'pending', + 'drop', 'pending_error', 'exception', + 'foreign_enter', 'foreign_close', 'foreign_exit', + 'foreign_manual', 'foreign_drop', + 'cleanup_retry', 'cleanup_recover', + ): + try: + child = subprocess.run( + [ + sys.executable, '-I', runner, + '--generated', generated_dir, + '--mode', str(mode), + '--scenario', scenario, + ], + capture_output=True, text=True, + timeout=30, check=False, + ) + except subprocess.TimeoutExpired as error: + cr['error'] = ( + f'{scenario} apartment={mode} timed out in ' + f'a native callback: {error}' + ) + return cr + if ( + child.returncode + or f'PASS {scenario} apartment={mode}' not in child.stdout + ): + cr['error'] = ( + f'{scenario} apartment={mode} failed with ' + f'0x{child.returncode & 0xffffffff:08X}: ' + f'{child.stdout} {child.stderr}' + ) + return cr + if ( + scenario == 'foreign_drop' + and 'RoApartment was dropped on a different OS thread' + not in child.stderr + ): + cr['error'] = ( + f'{scenario} apartment={mode} did not report the ' + f'foreign drop: {child.stderr!r}' + ) + return cr + if ( + scenario == 'drop' + and 'RoApartment was dropped during a synchronous native callback' + not in child.stderr + ): + cr['error'] = ( + f'{scenario} apartment={mode} did not report the ' + f'pending drop: {child.stderr!r}' + ) + return cr cr['pass'] = True elif kind == 'work_item_callback_passthrough': diff --git a/tests/e2e/typecheck/python_generated_api.py b/tests/e2e/typecheck/python_generated_api.py index d7427187..d2b61024 100644 --- a/tests/e2e/typecheck/python_generated_api.py +++ b/tests/e2e/typecheck/python_generated_api.py @@ -17,6 +17,7 @@ DynWinRTMethodSig, DynWinRTType, DynWinRTValue, + RoApartment, WinGUID, ) from dynwinrt.values import ( @@ -92,6 +93,7 @@ def check_structural_async_compatibility() -> None: def check_runtime_stubs() -> None: + assert_type(RoApartment.recover_pending(), RoApartment) iid: WinGUID = WinGUID.parse("00000000-0000-0000-c000-000000000046") interface: DynWinRTType = DynWinRTType.register_interface("IUnknown", iid) signature: DynWinRTMethodSig = DynWinRTMethodSig().add_out(