diff --git a/bindings/py/README.md b/bindings/py/README.md index 5f1f6275..c46f0934 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -595,6 +595,16 @@ using `RoApartment.recover_pending()` and close after native references are released. Do not depend on Python garbage collection to close an apartment. +If releasing an apartment-owned native callback runs a captured object's +finalizer, a successful same-model `ro_initialize()` in that finalizer remains +active after the outer close and must still be paired with `ro_uninitialize()`. +The outer close consumes only its own initialization, not the newly acquired +one. Manual closes and pending-close retries reserve their in-progress lease +before owner cleanup, including cleanup-failure leases queued by a foreign-thread +guard drop. If cleanup fails, that exact lease remains retryable without +discarding any initialization or pending lease acquired during cleanup. Owners +already released by the drain stay released. + WinRT is never initialized implicitly. A call on a thread without an apartment raises `OSError` with `CO_E_NOTINITIALIZED` in `error.winerror`; its message explains how to open one. diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index d3598897..55e9a88c 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -501,7 +501,8 @@ fn leave_managed_apartment_with_drain( if depth == 1 { drain()?; } - MANAGED_APARTMENT_DEPTH.with(|state| state.set(depth - 1)); + // Releasing an owner can run Python finalizers that successfully initialize again. + MANAGED_APARTMENT_DEPTH.with(|state| state.set(state.get() - 1)); unsafe { windows::Win32::System::WinRT::RoUninitialize() }; Ok(()) } @@ -889,13 +890,17 @@ pub fn ro_uninitialize(py: Python<'_>) -> PyResult<()> { "ro_uninitialize() requires a successful ro_initialize() on this thread", )); } - leave_managed_apartment(py, "ro_uninitialize()")?; + // Reserve the closing manual lease so cleanup cannot consume it a second time. MANUAL_APARTMENT_DEPTH.with(|state| state.set(depth - 1)); - Ok(()) + let result = leave_managed_apartment(py, "ro_uninitialize()"); + if result.is_err() { + MANUAL_APARTMENT_DEPTH.with(|state| state.set(state.get() + 1)); + } + result } -#[pyfunction] -pub fn retry_pending_apartment_close(py: Python<'_>) -> PyResult<()> { +fn retry_pending_apartment_close_with_drain(drain: impl FnOnce() -> PyResult<()>) -> PyResult<()> { + let _retry = PendingRetryGuard::enter()?; let local_pending = PENDING_APARTMENT_CLOSES .try_with(|pending| { pending @@ -932,15 +937,21 @@ pub fn retry_pending_apartment_close(py: Python<'_>) -> PyResult<()> { "no failed RoApartment close is pending on this thread", )); } - let _retry = PendingRetryGuard::enter()?; - leave_managed_apartment(py, "retry_pending_apartment_close()")?; - if local_pending { - PENDING_APARTMENT_CLOSES.with(|pending| { + // Reserve this lease, not an entry added by a finalizer during the drain. + let (pending, foreign_index) = if local_pending { + let apartment_type = PENDING_APARTMENT_CLOSES.with(|pending| { pending .borrow_mut() .pop() - .expect("pending cleanup was checked"); + .expect("pending cleanup was checked") }); + ( + PendingApartment { + apartment_type, + retry_cleanup: true, + }, + None, + ) } else { FOREIGN_DROPS.with(|owner| { let (mut queue, _) = lock_foreign_drops(&owner.0); @@ -949,10 +960,33 @@ pub fn retry_pending_apartment_close(py: Python<'_>) -> PyResult<()> { .iter() .rposition(|pending| pending.retry_cleanup) .expect("pending foreign cleanup was checked"); - queue.pending.remove(index); - }); + (queue.pending.remove(index), Some(index)) + }) + }; + let result = leave_managed_apartment_with_drain("retry_pending_apartment_close()", drain); + if result.is_err() { + if let Some(index) = foreign_index { + FOREIGN_DROPS.with(|owner| { + let (mut queue, _) = lock_foreign_drops(&owner.0); + queue.pending.insert(index, pending); + }); + } else { + PENDING_APARTMENT_CLOSES.with(|state| { + state.borrow_mut().push(pending.apartment_type); + }); + } } - Ok(()) + result +} + +#[pyfunction] +pub fn retry_pending_apartment_close(py: Python<'_>) -> PyResult<()> { + retry_pending_apartment_close_with_drain(|| { + py.import("dynwinrt.dynwinrt")? + .getattr("_dynwinrt_drain_apartment_owners")? + .call0()?; + Ok(()) + }) } #[pyfunction] @@ -4807,6 +4841,139 @@ mod tests { .unwrap(); } + #[test] + fn owner_drain_preserves_reentrant_initializations_and_failed_close() { + Python::initialize(); + for apartment_type in [0, 1] { + for fail_drain in [false, true] { + thread::spawn(move || { + assert_eq!(managed_apartment_depth(), 0); + enter_managed_apartment(apartment_type).unwrap(); + let result = leave_managed_apartment_with_drain("owner drain test", || { + enter_managed_apartment(apartment_type)?; + if fail_drain { + Err(PyRuntimeError::new_err( + "owner drain failed after initialization", + )) + } else { + Ok(()) + } + }); + assert_eq!(result.is_err(), fail_drain); + assert_eq!(managed_apartment_depth(), if fail_drain { 2 } else { 1 }); + if fail_drain { + leave_managed_apartment_with_drain("owner drain test", || { + panic!("a non-final close must not drain owners") + }) + .unwrap(); + assert_eq!(managed_apartment_depth(), 1); + } + leave_managed_apartment_with_drain("owner drain test", || Ok(())).unwrap(); + assert_eq!(managed_apartment_depth(), 0); + unsafe { RoInitialize(ro_init_type(1 - apartment_type)) }.unwrap(); + unsafe { windows::Win32::System::WinRT::RoUninitialize() }; + }) + .join() + .unwrap(); + } + } + } + + #[test] + fn pending_retry_reserves_exact_lease_and_restores_after_reentrant_failure() { + Python::initialize(); + for apartment_type in [0, 1] { + for foreign in [false, true] { + for fail_drain in [false, true] { + thread::spawn(move || { + let enqueue = |apartment_type| { + if foreign { + FOREIGN_DROPS.with(|owner| { + lock_foreign_drops(&owner.0) + .0 + .pending + .push(PendingApartment { + apartment_type, + retry_cleanup: true, + }); + }); + } else { + PENDING_APARTMENT_CLOSES.with(|state| { + state.borrow_mut().push(apartment_type); + }); + } + }; + let pending_types = || { + if foreign { + FOREIGN_DROPS.with(|owner| { + lock_foreign_drops(&owner.0) + .0 + .pending + .iter() + .map(|pending| pending.apartment_type) + .collect::>() + }) + } else { + PENDING_APARTMENT_CLOSES.with(|state| state.borrow().clone()) + } + }; + enter_managed_apartment(apartment_type).unwrap(); + enqueue(apartment_type); + let new_type = if apartment_type == 1 { 7 } else { 0 }; + let result = retry_pending_apartment_close_with_drain(|| { + assert!( + pending_types().is_empty(), + "the closing lease was not reserved" + ); + assert!(RoApartment::recover_pending().is_err()); + enter_managed_apartment(new_type)?; + enqueue(new_type); + assert!( + retry_pending_apartment_close_with_drain(|| { + panic!("a nested retry must not consume another pending lease") + }) + .is_err() + ); + assert!(RoApartment::recover_pending().is_err()); + if fail_drain { + Err(PyRuntimeError::new_err( + "owner drain failed after initialization", + )) + } else { + Ok(()) + } + }); + assert_eq!(result.is_err(), fail_drain); + assert_eq!(managed_apartment_depth(), if fail_drain { 2 } else { 1 }); + assert!(!PENDING_RETRY_IN_PROGRESS.with(Cell::get)); + if fail_drain { + assert_eq!( + pending_types(), + if foreign { + vec![apartment_type, new_type] + } else { + vec![new_type, apartment_type] + } + ); + } else { + assert_eq!(pending_types(), vec![new_type]); + } + for _ in 0..if fail_drain { 2 } else { 1 } { + retry_pending_apartment_close_with_drain(|| Ok(())).unwrap(); + } + assert!(pending_types().is_empty()); + assert!(RoApartment::recover_pending().is_err()); + assert_eq!(managed_apartment_depth(), 0); + unsafe { RoInitialize(ro_init_type(1 - apartment_type)) }.unwrap(); + unsafe { windows::Win32::System::WinRT::RoUninitialize() }; + }) + .join() + .unwrap(); + } + } + } + } + #[test] fn foreign_python_array_and_vector_inputs_reject_before_com_addref() { Python::initialize(); diff --git a/bindings/py/tests/test_native_container_lifetime.py b/bindings/py/tests/test_native_container_lifetime.py index 506b2ac3..a405d2af 100644 --- a/bindings/py/tests/test_native_container_lifetime.py +++ b/bindings/py/tests/test_native_container_lifetime.py @@ -4,6 +4,7 @@ """Native container owners must be disposed before their COM apartment exits.""" import gc +from pathlib import Path import subprocess import sys import weakref @@ -1701,6 +1702,39 @@ def test_managed_apartment_drain_is_reentrant_and_unbalanced_calls_fail(script, assert marker in result.stdout +@pytest.mark.parametrize("apartment_type", [0, 1]) +@pytest.mark.parametrize( + "scenario", + [ + "close", "exit", "drop", "manual", "retry", + "close_failure", "manual_failure", "retry_failure", + "manual_nested_pair", "retry_nested_pair", + "recover", "recover_failure", + "foreign_retry", "foreign_retry_failure", "foreign_retry_nested_pair", + "foreign_recover", "foreign_recover_failure", + ], +) +def test_owner_drain_preserves_reentrant_initialization_leases(apartment_type, scenario): + runner = Path(__file__).resolve().parents[3].joinpath( + "tests", "e2e", "runners", "py_apartment_owner_reinitialization.py" + ) + result = subprocess.run( + [ + sys.executable, "-I", str(runner), + "--mode", str(apartment_type), "--scenario", scenario, + ], + capture_output=True, + text=True, + timeout=45, + check=False, + ) + assert result.returncode == 0, ( + scenario, apartment_type, hex(result.returncode & 0xFFFFFFFF), + result.stdout, result.stderr, + ) + assert f"PASS owner-reinitialization {scenario} apartment={apartment_type}" in result.stdout + + def test_wrong_thread_apartment_close_preserves_native_owners(): result = subprocess.run( [sys.executable, "-B", "-c", _WRONG_THREAD_APARTMENT], diff --git a/tests/e2e/e2e_specs.json b/tests/e2e/e2e_specs.json index 34432212..24bfd50d 100644 --- a/tests/e2e/e2e_specs.json +++ b/tests/e2e/e2e_specs.json @@ -33,6 +33,16 @@ { "kind": "static_equals", "member": "unescape_component", "args": ["hello%20world"], "expected": "hello world" } ] }, + { + "id": "deferral_owner_drain_reinitialization", + "namespace": "Windows.Foundation", + "class": "Deferral", + "langs": ["py"], + "instantiate": { "kind": "none" }, + "checks": [ + { "kind": "apartment_owner_reinitialization", "member": "__init__" } + ] + }, { "id": "uri_python_constructor", "namespace": "Windows.Foundation", diff --git a/tests/e2e/e2e_specs.schema.json b/tests/e2e/e2e_specs.schema.json index d39b83b2..4aaf2c69 100644 --- a/tests/e2e/e2e_specs.schema.json +++ b/tests/e2e/e2e_specs.schema.json @@ -81,6 +81,7 @@ "async_progress_cancel_error", "async_cancellation", "unscoped_uri_apartment_exit", + "apartment_owner_reinitialization", "threadpool_async_apartment_owner", "nonagile_async_apartment_exit", "property_set_equals", diff --git a/tests/e2e/runners/py_apartment_owner_reinitialization.py b/tests/e2e/runners/py_apartment_owner_reinitialization.py new file mode 100644 index 00000000..d2976d2d --- /dev/null +++ b/tests/e2e/runners/py_apartment_owner_reinitialization.py @@ -0,0 +1,274 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Real delegate finalizers must preserve initialization leases during owner drain.""" + +import argparse +import ctypes +import gc +import importlib +import os +import sys +import threading +import traceback +import weakref + + +SCENARIOS = ( + "close", "exit", "drop", "manual", "retry", + "close_failure", "manual_failure", "retry_failure", + "manual_nested_pair", "retry_nested_pair", + "recover", "recover_failure", + "foreign_retry", "foreign_retry_failure", "foreign_retry_nested_pair", + "foreign_recover", "foreign_recover_failure", +) + + +def run_case(generated, mode, scenario): + import dynwinrt as dw + import dynwinrt.dynwinrt as native + + if generated is None: + # Windows.Foundation.DeferralCompletedHandler has an empty Invoke signature. + iid = dw.WinGUID.parse("ed32a372-f3c8-4faa-9cfb-470148da3888") + parameter_types = [] + uri_type = None + else: + sys.path.insert(0, os.path.dirname(os.path.abspath(generated))) + package = os.path.basename(os.path.abspath(generated)) + metadata = importlib.import_module( + f"{package}.windows__foundation__deferral_completed_handler" + ) + iid = metadata.IID_DeferralCompletedHandler + parameter_types = metadata.DeferralCompletedHandler_PARAM_TYPES + uri_type = importlib.import_module(f"{package}.windows.foundation").Uri + assert parameter_types == [] + + combase = ctypes.WinDLL("combase.dll") + combase.RoInitialize.argtypes = (ctypes.c_uint32,) + combase.RoInitialize.restype = ctypes.c_long + combase.RoUninitialize.argtypes = () + combase.RoUninitialize.restype = None + manual = scenario.startswith("manual") + foreign = scenario.startswith("foreign_") + retry = scenario.startswith("retry") or scenario.startswith("foreign_retry") + recover = "recover" in scenario + pending = retry or recover + nested_pair = scenario.endswith("nested_pair") + fail_after = scenario.endswith("failure") + finalized = [] + destructor_errors = [] + unraisable = [] + observed = [] + calls = [] + original_hook = sys.unraisablehook + sys.unraisablehook = lambda event: unraisable.append(str(event.exc_value)) + + def unavailable(action, messages): + try: + action() + except RuntimeError as error: + assert any(message in str(error) for message in messages), error + else: + raise AssertionError("an in-progress or completed lease was consumed twice") + + def check_pending_unavailable(): + unavailable( + dw.retry_pending_apartment_close, + ("no failed RoApartment close", "already in progress"), + ) + unavailable( + dw.RoApartment.recover_pending, + ("no dropped RoApartment", "already in progress"), + ) + + class Captured: + def __del__(self): + try: + frame = sys._getframe() + in_drain = False + while frame is not None: + in_drain |= frame.f_code.co_name == "_dynwinrt_drain_apartment_owners" + frame = frame.f_back + assert in_drain, "captured object finalized outside the owner drain" + assert native._managed_apartment_depth() == 1 + if nested_pair: + if manual: + unavailable(dw.ro_uninitialize, ("requires a successful",)) + else: + check_pending_unavailable() + try: + dw.ro_initialize(1 - mode) + except OSError as error: + assert error.winerror == -2147417850, error # RPC_E_CHANGED_MODE + else: + raise AssertionError("a conflicting initialization succeeded") + assert native._managed_apartment_depth() == 1 + same_model = combase.RoInitialize(mode) + assert same_model == 1, same_model # S_FALSE also requires a paired close. + combase.RoUninitialize() + dw.ro_initialize(mode) + assert native._managed_apartment_depth() == 2 + if nested_pair: + if retry: + check_pending_unavailable() + dw.ro_uninitialize() + assert native._managed_apartment_depth() == 1 + if manual: + unavailable(dw.ro_uninitialize, ("requires a successful",)) + finalized.append((in_drain, same_model)) + except BaseException: + destructor_errors.append(traceback.format_exc()) + + class FailingOwner: + def __init__(self): + self.checks = 0 + self.releases = 0 + + def _check_apartment_release(self): + self.checks += 1 + if pending and self.checks == 1: + raise RuntimeError("initial owner drain failed") + + def release(self): + self.releases += 1 + if fail_after and self.releases == 1: + assert finalized, "failure occurred before the reinitializing finalizer" + raise RuntimeError("owner drain failed after reinitialization") + + def make_delegate(): + captured = Captured() + observed.append(weakref.ref(captured)) + + def callback(): + assert captured is observed[0]() + calls.append("native") + + return dw.DynWinRtDelegate.create(iid, parameter_types, callback) + + def reference_count(value): + pointer = value.as_raw() + vtable = ctypes.c_void_p.from_address(pointer).value + width = ctypes.sizeof(ctypes.c_void_p) + call = ctypes.WINFUNCTYPE(ctypes.c_uint32, ctypes.c_void_p) + add_ref = call(ctypes.c_void_p.from_address(vtable + width).value) + release = call(ctypes.c_void_p.from_address(vtable + 2 * width).value) + added = add_ref(pointer) + remaining = release(pointer) + assert added == remaining + 1 + return remaining + + apartment = None + if manual: + dw.ro_initialize(mode) + else: + apartment = dw.RoApartment(mode) + apartment.__enter__() + failure = native._dynwinrt_track_native(FailingOwner()) if pending or fail_after else None + delegate = make_delegate() + alias = delegate.to_value().cast(iid) + assert alias.invoke_delegate(iid, dw.DynWinRTMethodSig(), []) == [] + assert calls == ["native"] and not unraisable + references = reference_count(alias) + delegate.release() + remaining = reference_count(alias) + assert references == remaining + 1 and remaining == 1 + gc.collect() + assert observed[0]() is not None and not finalized and not destructor_errors + + if pending: + try: + apartment.close() + except RuntimeError as error: + assert str(error) == "initial owner drain failed", error + else: + raise AssertionError("owner-drain preflight failure was hidden") + assert "active=true" in repr(apartment) and not alias.is_released() + assert native._managed_apartment_depth() == 1 and not finalized + if foreign: + holder = [apartment] + apartment = None + worker = threading.Thread(target=holder.clear) + worker.start() + worker.join(5) + assert not worker.is_alive() and not holder, "foreign guard Drop did not complete" + else: + apartment = None + gc.collect() + assert failure.releases == 0, "guard Drop retried an already failed close" + if recover: + apartment = dw.RoApartment.recover_pending() + assert f"apartment_type={mode}, active=true" in repr(apartment) + check_pending_unavailable() + + def close(): + nonlocal apartment + if manual: + dw.ro_uninitialize() + elif retry: + dw.retry_pending_apartment_close() + elif scenario == "exit": + assert apartment.__exit__(None, None, None) is False + elif scenario == "drop": + apartment = None + gc.collect() + else: + apartment.close() + + if fail_after: + try: + close() + except RuntimeError as error: + assert str(error) == "owner drain failed after reinitialization", error + else: + raise AssertionError("failure after reinitialization was hidden") + assert native._managed_apartment_depth() == 2 + assert failure.releases == 1 and finalized == [(True, 1)] + if apartment is not None: + assert "active=true" in repr(apartment) + close() + gc.collect() + assert not destructor_errors and not unraisable, (destructor_errors, unraisable) + assert finalized == [(True, 1)] and observed[0]() is None + assert delegate.is_released() and alias.is_released() + if apartment is not None: + assert "active=false" in repr(apartment) + apartment.close() + if nested_pair: + assert native._managed_apartment_depth() == 0 + else: + assert native._managed_apartment_depth() == 1 + if uri_type is None: + live = dw.DynWinRTValue.activation_factory("Windows.Foundation.Uri") + value = live + else: + live = uri_type("https://example.com/reinitialized") + assert live.host == "example.com" + value = live._obj + scalar = dw.DynWinRTArray.from_i32_values([17]) + dw.ro_uninitialize() + assert value.is_released() and scalar.to_i32_list() == [17] + if failure is not None: + assert failure.releases == (2 if fail_after else 1) + assert native._managed_apartment_depth() == 0 + unavailable(dw.ro_uninitialize, ("requires a successful",)) + check_pending_unavailable() + opposite = combase.RoInitialize(1 - mode) + assert opposite == 0, f"native initialization leaked: {opposite:#x}" + combase.RoUninitialize() + assert not destructor_errors and not unraisable, (destructor_errors, unraisable) + sys.unraisablehook = original_hook + print( + f"PASS owner-reinitialization {scenario} apartment={mode} " + f"native-refs={references}->{remaining}->finalized S_FALSE=1 opposite=S_OK", + flush=True, + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--generated") + parser.add_argument("--mode", type=int, choices=(0, 1), required=True) + parser.add_argument("--scenario", choices=SCENARIOS, 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 d88b3901..cdda977e 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -17,10 +17,10 @@ import inspect import json import re +import runpy import subprocess import sys import os -import subprocess import threading @@ -3212,6 +3212,30 @@ def block_on_sta(): return cr cr['pass'] = True + elif kind == 'apartment_owner_reinitialization': + runner = os.path.join( + os.path.dirname(__file__), 'py_apartment_owner_reinitialization.py' + ) + scenarios = runpy.run_path(runner)['SCENARIOS'] + for mode in (dw.RO_INIT_SINGLETHREADED, dw.RO_INIT_MULTITHREADED): + for scenario in scenarios: + child = subprocess.run( + [ + sys.executable, '-I', runner, '--generated', generated_dir, + '--mode', str(mode), '--scenario', scenario, + ], + capture_output=True, text=True, timeout=45, check=False, + ) + marker = f'PASS owner-reinitialization {scenario} apartment={mode}' + if child.returncode or marker not in child.stdout: + cr['error'] = ( + f'{marker}: isolated Python exited ' + f'{hex(child.returncode & 0xFFFFFFFF)}: ' + f'{child.stdout} {child.stderr}' + ) + return cr + cr['pass'] = True + elif kind == 'threadpool_async_apartment_owner': for mode, marker in ( ('pending', 'pending-async-retry'),