Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
193 changes: 180 additions & 13 deletions bindings/py/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand All @@ -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]
Expand Down Expand Up @@ -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::<Vec<_>>()
})
} 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();
Expand Down
34 changes: 34 additions & 0 deletions bindings/py/tests/test_native_container_lifetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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],
Expand Down
10 changes: 10 additions & 0 deletions tests/e2e/e2e_specs.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions tests/e2e/e2e_specs.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading